[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735ZYQGVM0P656ZGRJ37Z8A":3,"skill-same:01M735ZYQGVM0P656ZGRJ37Z8A":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},"01M735ZYQGVM0P656ZGRJ37Z8A","automotive-zonal",null,"Automotive Zonal expertise. Covers 5 topics: Automotive Ethernet, Network Security Zonal, Service Oriented Communication, Zonal Architecture Design, Zone Controller Development.","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-zonal\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: automotive-zonal\ndescription: >\n  Automotive Zonal expertise. Covers 5 topics: Automotive Ethernet, Network Security Zonal, Service Oriented Communication, Zonal Architecture Design, Zone Controller Development.\ntags: [automotive, automotive-zonal]\n---\n\n# Automotive Zonal\n\n## Automotive Ethernet\n\n# Automotive Ethernet - TSN & AVB\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in automotive Ethernet technologies including Time-Sensitive Networking (TSN), Audio Video Bridging (AVB), physical layer standards (100BASE-T1, 1000BASE-T1), switch configuration, VLAN management, and Quality of Service (QoS) for deterministic vehicle networks.\n\n## Core Competencies\n\n### 1. Physical Layer Standards\n\n#### 100BASE-T1 (IEEE 802.3bw)\n```c\n\u002F\u002F 100BASE-T1 PHY Configuration\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3bw\n    uint16_t data_rate_mbps;    \u002F\u002F 100 Mbps full-duplex\n    uint8_t wire_pairs;         \u002F\u002F 1 twisted pair\n    uint16_t max_length_m;      \u002F\u002F 15 meters (typ), 40m (max)\n    float voltage_p2p;          \u002F\u002F 2.4V peak-to-peak\n    uint8_t encoding;           \u002F\u002F PAM3 (3-level)\n    bool pma_master;            \u002F\u002F Master\u002FSlave negotiation\n} BASE100_T1_Config;\n\n\u002F\u002F Example configuration for zone controller\nBASE100_T1_Config zcu_phy = {\n    .standard = IEEE_802_3bw,\n    .data_rate_mbps = 100,\n    .wire_pairs = 1,\n    .max_length_m = 15,\n    .voltage_p2p = 2.4,\n    .encoding = PAM3,\n    .pma_master = true  \u002F\u002F Zone controller is master\n};\n```\n\n#### 1000BASE-T1 (IEEE 802.3bp)\n```c\n\u002F\u002F 1000BASE-T1 PHY Configuration (for cameras, ADAS)\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3bp\n    uint16_t data_rate_mbps;    \u002F\u002F 1000 Mbps full-duplex\n    uint8_t wire_pairs;         \u002F\u002F 1 unshielded twisted pair\n    uint16_t max_length_m;      \u002F\u002F 15m (standard), 40m (extended)\n    uint8_t encoding;           \u002F\u002F PAM3\n    bool automotive_grade;      \u002F\u002F AEC-Q100 qualified\n    float temp_range[2];        \u002F\u002F -40°C to +125°C\n} BASE1000_T1_Config;\n\n\u002F\u002F Camera link configuration\nBASE1000_T1_Config camera_phy = {\n    .standard = IEEE_802_3bp,\n    .data_rate_mbps = 1000,\n    .wire_pairs = 1,\n    .max_length_m = 15,\n    .encoding = PAM3,\n    .automotive_grade = true,\n    .temp_range = {-40.0, 125.0}\n};\n```\n\n#### 10BASE-T1S (IEEE 802.3cg) - Multidrop Bus\n```c\n\u002F\u002F 10BASE-T1S for low-cost sensor networks\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3cg\n    uint16_t data_rate_mbps;    \u002F\u002F 10 Mbps half-duplex\n    uint8_t topology;           \u002F\u002F Multidrop bus\n    uint8_t max_nodes;          \u002F\u002F 8 nodes per segment\n    uint16_t max_length_m;      \u002F\u002F 25 meters\n    uint8_t collision_detection; \u002F\u002F CSMA\u002FCD\n    bool plca_mode;             \u002F\u002F Physical Layer Collision Avoidance\n} BASE10_T1S_Config;\n\n\u002F\u002F Sensor bus configuration\nBASE10_T1S_Config sensor_bus = {\n    .standard = IEEE_802_3cg,\n    .data_rate_mbps = 10,\n    .topology = MULTIDROP_BUS,\n    .max_nodes = 8,\n    .max_length_m = 25,\n    .collision_detection = CSMA_CD,\n    .plca_mode = true  \u002F\u002F Enables deterministic access\n};\n```\n\n### 2. Time-Sensitive Networking (TSN)\n\n#### IEEE 802.1 TSN Standards\n\n**Key Standards:**\n- **802.1AS** - Precision Time Protocol (gPTP) for time synchronization\n- **802.1Qbv** - Time-Aware Shaper (TAS) for scheduled traffic\n- **802.1Qav** - Credit-Based Shaper (CBS) for AVB streams\n- **802.1Qbu** - Frame Preemption for low-latency\n- **802.1Qci** - Per-Stream Filtering and Policing\n- **802.1CB** - Frame Replication and Elimination for Reliability (FRER)\n\n```python\n# TSN Configuration Example\nclass TSNSwitchConfig:\n    def __init__(self):\n        self.gptp_domain = 0  # Time domain for sync\n        self.sync_interval_ms = 125  # gPTP sync every 125ms\n        self.time_aware_shaper = True\n        self.frame_preemption = True\n        self.stream_reservation = True\n\n    def configure_tas_schedule(self):\n        \"\"\"\n        Configure Time-Aware Shaper (802.1Qbv) for deterministic scheduling.\n        Divides time into repeating cycles with gates for each priority queue.\n        \"\"\"\n\n        # 1ms cycle time (1,000,000 ns)\n        cycle_time_ns = 1_000_000\n\n        schedule = {\n            'cycle_time_ns': cycle_time_ns,\n            'gates': [\n                # Time slot 0-100μs: Priority 7 (Safety-critical)\n                {\n                    'start_ns': 0,\n                    'duration_ns': 100_000,\n                    'open_gates': [7],  # Only priority 7 queue open\n                    'traffic_class': 'Safety'\n                },\n                # Time slot 100-300μs: Priority 6 (ADAS)\n                {\n                    'start_ns': 100_000,\n                    'duration_ns': 200_000,\n                    'open_gates': [6],\n                    'traffic_class': 'Control'\n                },\n                # Time slot 300-800μs: Priority 4-5 (Video streams)\n                {\n                    'start_ns': 300_000,\n                    'duration_ns': 500_000,\n                    'open_gates': [4, 5],\n                    'traffic_class': 'AVB'\n                },\n                # Time slot 800-1000μs: Priority 0-3 (Best effort)\n                {\n                    'start_ns': 800_000,\n                    'duration_ns': 200_000,\n                    'open_gates': [0, 1, 2, 3],\n                    'traffic_class': 'BestEffort'\n                }\n            ]\n        }\n\n        return schedule\n\n    def configure_stream_reservation(self, stream_id, bandwidth_mbps, latency_us):\n        \"\"\"\n        Configure stream reservation for AVB\u002FTSN streams (802.1Qat\u002FQcc).\n\n        Args:\n            stream_id: Unique stream identifier\n            bandwidth_mbps: Required bandwidth in Mbps\n            latency_us: Maximum latency in microseconds\n        \"\"\"\n\n        stream_config = {\n            'stream_id': stream_id,\n            'talker_mac': '00:11:22:33:44:55',\n            'listener_mac': ['00:11:22:33:44:66'],\n            'vlan_id': 100,\n            'priority': 6,  # SR Class A\n            'max_frame_size': 1522,\n            'max_interval_frames': 1,\n            'bandwidth_mbps': bandwidth_mbps,\n            'max_latency_us': latency_us,\n            'redundancy': 'FRER'  # Frame Replication\n        }\n\n        return stream_config\n```\n\n#### gPTP Time Synchronization (802.1AS)\n\n```c\n\u002F\u002F gPTP Time Synchronization Configuration\ntypedef struct {\n    uint8_t domain_number;           \u002F\u002F 0 for automotive\n    uint32_t sync_interval_ns;       \u002F\u002F 125ms = 125,000,000 ns\n    uint32_t pdelay_interval_ns;     \u002F\u002F Peer delay measurement\n    int8_t clock_class;              \u002F\u002F 248 for automotive grandmaster\n    int8_t clock_accuracy;           \u002F\u002F 0xFE (unknown)\n    uint16_t offset_scaled_log_var;  \u002F\u002F Variance of clock\n    uint8_t priority1;               \u002F\u002F 248\n    uint8_t priority2;               \u002F\u002F 248\n    bool as_capable;                 \u002F\u002F TSN-capable port\n} gPTP_Config_t;\n\n\u002F\u002F Grandmaster clock (gateway)\ngPTP_Config_t grandmaster = {\n    .domain_number = 0,\n    .sync_interval_ns = 125000000,  \u002F\u002F 125ms\n    .pdelay_interval_ns = 1000000000,  \u002F\u002F 1 second\n    .clock_class = 248,  \u002F\u002F Automotive default application-specific\n    .clock_accuracy = 0xFE,\n    .offset_scaled_log_var = 0x4E5D,\n    .priority1 = 248,\n    .priority2 = 248,\n    .as_capable = true\n};\n\n\u002F\u002F Typical time sync accuracy: ±500ns between nodes\n```\n\n### 3. VLAN Configuration\n\n```python\nclass VLANManager:\n    \"\"\"\n    Manage VLANs for traffic segregation in zonal architecture.\n    \"\"\"\n\n    def __init__(self):\n        self.vlans = {\n            100: {'name': 'Safety', 'priority': 7, 'color': 'RED'},\n            200: {'name': 'ADAS', 'priority': 6, 'color': 'ORANGE'},\n            300: {'name': 'Infotainment', 'priority': 5, 'color': 'YELLOW'},\n            400: {'name': 'Body', 'priority': 4, 'color': 'GREEN'},\n            500: {'name': 'Diagnostics', 'priority': 3, 'color': 'BLUE'},\n            999: {'name': 'Management', 'priority': 7, 'color': 'PURPLE'}\n        }\n\n    def configure_switch_ports(self):\n        \"\"\"\n        Configure switch ports with VLAN memberships.\n        \"\"\"\n\n        port_config = {\n            'port_1': {  # Gateway uplink\n                'mode': 'trunk',\n                'allowed_vlans': [100, 200, 300, 400, 500, 999],\n                'native_vlan': 999,\n                'pvid': 999\n            },\n            'port_2': {  # Front-left ZCU\n                'mode': 'trunk',\n                'allowed_vlans': [100, 400],  # Safety + Body\n                'native_vlan': 400,\n                'pvid': 400\n            },\n            'port_3': {  # Front camera (ADAS)\n                'mode': 'access',\n                'vlan': 200,  # ADAS VLAN only\n                'pvid': 200\n            },\n            'port_4': {  # Rear camera (infotainment)\n                'mode': 'access',\n                'vlan': 300,  # Infotainment VLAN\n                'pvid': 300\n            },\n            'port_5': {  # Diagnostic connector (OBD-II)\n                'mode': 'access',\n                'vlan': 500,\n                'pvid': 500\n            }\n        }\n\n        return port_config\n```\n\n### 4. Quality of Service (QoS)\n\n#### Priority Mapping (IEEE 802.1Q)\n\n```c\n\u002F\u002F 8 priority levels (0-7)\ntypedef enum {\n    PRIORITY_0_BEST_EFFORT = 0,     \u002F\u002F Background\n    PRIORITY_1_BACKGROUND = 1,      \u002F\u002F Backup data\n    PRIORITY_2_EXCELLENT_EFFORT = 2, \u002F\u002F Business-critical\n    PRIORITY_3_CRITICAL_APPS = 3,    \u002F\u002F Call signaling\n    PRIORITY_4_VIDEO = 4,            \u002F\u002F Streaming video\n    PRIORITY_5_VOICE = 5,            \u002F\u002F Interactive voice\u002Fvideo\n    PRIORITY_6_CONTROL = 6,          \u002F\u002F Control plane (ADAS)\n    PRIORITY_7_NETWORK_CONTROL = 7   \u002F\u002F Safety-critical\n} EthernetPriority_t;\n\n\u002F\u002F Traffic class mapping\ntypedef struct {\n    EthernetPriority_t priority;\n    uint8_t traffic_class;\n    uint16_t max_latency_us;\n    char description[32];\n} QoS_Mapping_t;\n\nQoS_Mapping_t qos_table[] = {\n    {PRIORITY_7_NETWORK_CONTROL, 7, 100, \"Safety (ABS, ESC)\"},\n    {PRIORITY_6_CONTROL, 6, 500, \"ADAS (Braking, Steering)\"},\n    {PRIORITY_5_VOICE, 5, 2000, \"Camera streams\"},\n    {PRIORITY_4_VIDEO, 4, 10000, \"Infotainment video\"},\n    {PRIORITY_3_CRITICAL_APPS, 3, 20000, \"Diagnostics\"},\n    {PRIORITY_2_EXCELLENT_EFFORT, 2, 50000, \"SW updates\"},\n    {PRIORITY_1_BACKGROUND, 1, 100000, \"Telemetry\"},\n    {PRIORITY_0_BEST_EFFORT, 0, 1000000, \"General data\"}\n};\n```\n\n#### Credit-Based Shaper (802.1Qav)\n\n```python\ndef configure_cbs(port, stream_class):\n    \"\"\"\n    Configure Credit-Based Shaper for AVB traffic (SR Class A\u002FB).\n\n    Args:\n        port: Ethernet port number\n        stream_class: 'A' for Class A (2ms), 'B' for Class B (50ms)\n    \"\"\"\n\n    if stream_class == 'A':\n        config = {\n            'idle_slope': 0x3FFF,      # 75% of link bandwidth\n            'send_slope': -0x2AAA,     # -25% of link bandwidth\n            'hi_credit': 0x186A0,      # 100,000 credits\n            'lo_credit': -0x186A0,     # -100,000 credits\n            'priority': 6\n        }\n    elif stream_class == 'B':\n        config = {\n            'idle_slope': 0x1FFF,      # 50% of link bandwidth\n            'send_slope': -0x1FFF,     # -50% of link bandwidth\n            'hi_credit': 0xC350,       # 50,000 credits\n            'lo_credit': -0xC350,      # -50,000 credits\n            'priority': 5\n        }\n\n    return config\n```\n\n### 5. Automotive Ethernet Switch Configuration\n\n```yaml\n# Example switch configuration (YAML)\nswitch:\n  model: \"NXP SJA1110\"\n  ports: 10\n  tsn_capable: true\n\n  global_config:\n    gptp_domain: 0\n    management_vlan: 999\n\n  port_1:  # Uplink to gateway\n    speed: \"1000BASE-T1\"\n    mode: \"trunk\"\n    vlans: [100, 200, 300, 400, 500, 999]\n    tsn:\n      tas_enabled: true\n      frame_preemption: true\n\n  port_2:  # Front-left zone controller\n    speed: \"100BASE-T1\"\n    mode: \"trunk\"\n    vlans: [100, 400]\n    tsn:\n      tas_enabled: true\n\n  port_3:  # Front camera\n    speed: \"1000BASE-T1\"\n    mode: \"access\"\n    vlan: 200\n    qos:\n      priority: 6\n      cbs_enabled: true\n      stream_reservation: true\n\n  port_4:  # Rear camera\n    speed: \"1000BASE-T1\"\n    mode: \"access\"\n    vlan: 200\n    qos:\n      priority: 6\n      cbs_enabled: true\n```\n\n## Network Performance Targets\n\n| Traffic Type | Priority | Max Latency | Jitter | Packet Loss |\n|--------------|----------|-------------|--------|-------------|\n| Safety (ABS, ESC) | 7 | \u003C100 μs | \u003C10 μs | 0% |\n| ADAS Control | 6 | \u003C500 μs | \u003C50 μs | \u003C10^-9 |\n| Camera Streams | 5-6 | \u003C2 ms | \u003C100 μs | \u003C10^-6 |\n| Infotainment | 4 | \u003C10 ms | \u003C1 ms | \u003C10^-4 |\n| Diagnostics | 3 | \u003C50 ms | N\u002FA | \u003C10^-3 |\n| Best Effort | 0-2 | \u003C1 s | N\u002FA | \u003C10^-2 |\n\n## Tools & Testing\n\n**Network Analyzers:**\n- **Vector VN5600** - TSN-capable network interface\n- **Wireshark with Automotive plugins** - Packet capture and analysis\n- **Ixia\u002FKeysight IxNetwork** - TSN traffic generation and testing\n\n**Configuration Tools:**\n- **NXP SJA1110 Config Tool** - Switch configuration\n- **Vector CANoe.Ethernet** - Network simulation\n- **Marvell TSN Studio** - TSN stream configuration\n\n## References\n\n- IEEE 802.1 TSN Task Group Standards\n- SAE J3161 On-Board Ethernet Communication\n- OPEN Alliance BroadR-Reach Specification\n- AUTOSAR Ethernet Communication Specification\n\n---\n\n## Network Security Zonal\n\n# Network Security for Zonal Architecture\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in securing automotive Ethernet networks in zonal architectures. Covers MACsec (IEEE 802.1AE), IPsec, firewall rules for zone controllers, intrusion detection systems (IDS), secure gateway design, and IDPS deployment for vehicle networks.\n\n## Core Competencies\n\n### 1. MACsec (IEEE 802.1AE) - Layer 2 Encryption\n\n```c\n\u002F\u002F MACsec Configuration for Automotive Ethernet\ntypedef struct {\n    uint8_t enabled;\n    uint8_t cipher_suite;       \u002F\u002F AES-GCM-128 or AES-GCM-256\n    uint8_t confidentiality;    \u002F\u002F Encrypt payload\n    uint8_t integrity;          \u002F\u002F ICV (Integrity Check Value)\n    uint32_t pn;                \u002F\u002F Packet Number (anti-replay)\n    uint8_t key[32];            \u002F\u002F 128-bit or 256-bit key\n    uint8_t sci[8];             \u002F\u002F Secure Channel Identifier\n} MACSec_Config_t;\n\n\u002F\u002F Example: MACsec between gateway and zone controller\nMACSec_Config_t macsec_link = {\n    .enabled = 1,\n    .cipher_suite = AES_GCM_256,\n    .confidentiality = 1,       \u002F\u002F Encrypt\n    .integrity = 1,             \u002F\u002F 16-byte ICV\n    .pn = 0x00000001,          \u002F\u002F Initial packet number\n    .key = {0x2b, 0x7e, 0x15, ...},  \u002F\u002F 256-bit key from key management\n    .sci = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}\n};\n```\n\n**MACsec Frame Structure:**\n```\n┌──────────────────────────────────────────────┐\n│ Ethernet Header (14 bytes)                   │\n├──────────────────────────────────────────────┤\n│ SecTAG (8 bytes)                             │\n│  - TCI\u002FAN (1 byte): Version, encrypted flag │\n│  - SL (1 byte): Short Length                │\n│  - PN (4 bytes): Packet Number              │\n│  - SCI (8 bytes): Secure Channel ID         │\n├──────────────────────────────────────────────┤\n│ Encrypted Payload                            │\n├──────────────────────────────────────────────┤\n│ ICV (16 bytes): Integrity Check Value        │\n└──────────────────────────────────────────────┘\n```\n\n**Performance Impact:**\n- Latency overhead: ~100-200 μs\n- Throughput reduction: ~5-10% (due to encryption)\n- CPU overhead: ~15% on zone controller\n\n### 2. IPsec for End-to-End Security\n\n```python\nclass IPsecTunnel:\n    \"\"\"\n    IPsec tunnel configuration for secure SOME\u002FIP communication.\n    \"\"\"\n\n    def __init__(self):\n        self.mode = 'ESP'  # Encapsulating Security Payload\n        self.encryption = 'AES-256-CBC'\n        self.authentication = 'HMAC-SHA256'\n        self.pfs = True  # Perfect Forward Secrecy\n\n    def configure_tunnel(self, local_ip, remote_ip):\n        \"\"\"\n        Configure IPsec tunnel between two ECUs.\n\n        Args:\n            local_ip: Local zone controller IP\n            remote_ip: Remote zone controller\u002Fgateway IP\n        \"\"\"\n\n        config = {\n            'src': local_ip,\n            'dst': remote_ip,\n            'protocol': 'ESP',  # ESP for encryption + auth\n            'spi': 0x1234,  # Security Parameter Index\n            'encryption': {\n                'algorithm': 'AES-256-CBC',\n                'key': self._generate_key(256)\n            },\n            'authentication': {\n                'algorithm': 'HMAC-SHA256',\n                'key': self._generate_key(256)\n            },\n            'lifetime': 3600,  # Rekey every hour\n            'anti_replay': True,\n            'window_size': 64\n        }\n\n        return config\n\n    def _generate_key(self, bits):\n        \"\"\"Generate cryptographic key (placeholder - use proper KMS).\"\"\"\n        import secrets\n        return secrets.token_bytes(bits \u002F\u002F 8)\n\n# Example: Secure tunnel from FL zone to gateway\ntunnel = IPsecTunnel()\nconfig = tunnel.configure_tunnel(\n    local_ip='192.168.1.10',   # FL Zone Controller\n    remote_ip='192.168.1.1'     # Gateway\n)\n```\n\n### 3. Firewall Rules for Zone Controllers\n\n```python\nclass ZonalFirewall:\n    \"\"\"\n    Stateful firewall for zone controller Ethernet interface.\n    \"\"\"\n\n    def __init__(self, zone_id):\n        self.zone_id = zone_id\n        self.rules = []\n        self.default_policy = 'DROP'  # Deny by default\n\n    def add_rule(self, rule):\n        \"\"\"\n        Add firewall rule.\n\n        Rule format:\n        {\n            'src_ip': '192.168.1.0\u002F24',\n            'dst_ip': '192.168.2.10',\n            'protocol': 'UDP',\n            'dst_port': 30500,\n            'action': 'ALLOW'\u002F'DROP'\u002F'REJECT',\n            'priority': 100\n        }\n        \"\"\"\n        self.rules.append(rule)\n        # Sort by priority\n        self.rules.sort(key=lambda x: x['priority'])\n\n    def evaluate_packet(self, packet):\n        \"\"\"\n        Evaluate packet against firewall rules.\n\n        Returns:\n            'ALLOW', 'DROP', or 'REJECT'\n        \"\"\"\n\n        for rule in self.rules:\n            if self._match_rule(packet, rule):\n                return rule['action']\n\n        return self.default_policy\n\n    def _match_rule(self, packet, rule):\n        \"\"\"Check if packet matches rule.\"\"\"\n        # Check source IP\n        if not self._ip_in_subnet(packet['src_ip'], rule.get('src_ip', 'any')):\n            return False\n\n        # Check destination IP\n        if not self._ip_in_subnet(packet['dst_ip'], rule.get('dst_ip', 'any')):\n            return False\n\n        # Check protocol\n        if rule.get('protocol', 'any') != 'any' and packet['protocol'] != rule['protocol']:\n            return False\n\n        # Check port\n        if rule.get('dst_port') and packet.get('dst_port') != rule['dst_port']:\n            return False\n\n        return True\n\n# Example: Firewall rules for FL Zone Controller\nfw = ZonalFirewall(zone_id='FL_ZONE')\n\n# Allow SOME\u002FIP from gateway\nfw.add_rule({\n    'src_ip': '192.168.1.1',     # Gateway\n    'dst_ip': '192.168.1.10',     # FL Zone\n    'protocol': 'UDP',\n    'dst_port': 30500,            # SOME\u002FIP service port\n    'action': 'ALLOW',\n    'priority': 100\n})\n\n# Allow diagnostic access (DoIP)\nfw.add_rule({\n    'src_ip': '192.168.5.0\u002F24',   # Diagnostic VLAN\n    'dst_ip': '192.168.1.10',\n    'protocol': 'TCP',\n    'dst_port': 13400,            # DoIP port\n    'action': 'ALLOW',\n    'priority': 200\n})\n\n# Block all other incoming traffic\nfw.add_rule({\n    'src_ip': 'any',\n    'dst_ip': '192.168.1.10',\n    'action': 'DROP',\n    'priority': 1000\n})\n```\n\n### 4. Intrusion Detection System (IDS)\n\n```python\nclass AutomotiveIDS:\n    \"\"\"\n    Intrusion Detection System for automotive Ethernet networks.\n    Detects anomalies and attacks specific to vehicle networks.\n    \"\"\"\n\n    def __init__(self):\n        self.baseline = {}  # Normal traffic patterns\n        self.alerts = []\n\n    def detect_anomalies(self, traffic_sample):\n        \"\"\"\n        Detect network anomalies.\n\n        Detection methods:\n        - Signature-based: Known attack patterns\n        - Anomaly-based: Deviation from baseline\n        - Behavior-based: Unusual communication patterns\n        \"\"\"\n\n        alerts = []\n\n        # 1. Port scan detection\n        if self._detect_port_scan(traffic_sample):\n            alerts.append({\n                'type': 'PORT_SCAN',\n                'severity': 'HIGH',\n                'description': 'Port scan detected from ' + traffic_sample['src_ip']\n            })\n\n        # 2. DoS detection (flooding)\n        if self._detect_dos(traffic_sample):\n            alerts.append({\n                'type': 'DOS_ATTACK',\n                'severity': 'CRITICAL',\n                'description': 'Potential DoS attack detected'\n            })\n\n        # 3. Unusual SOME\u002FIP service access\n        if self._detect_unauthorized_service_access(traffic_sample):\n            alerts.append({\n                'type': 'UNAUTHORIZED_ACCESS',\n                'severity': 'HIGH',\n                'description': 'Unauthorized SOME\u002FIP service access'\n            })\n\n        # 4. ARP spoofing detection\n        if self._detect_arp_spoofing(traffic_sample):\n            alerts.append({\n                'type': 'ARP_SPOOFING',\n                'severity': 'CRITICAL',\n                'description': 'ARP spoofing detected'\n            })\n\n        # 5. Replay attack detection (abnormal packet rate)\n        if self._detect_replay(traffic_sample):\n            alerts.append({\n                'type': 'REPLAY_ATTACK',\n                'severity': 'MEDIUM',\n                'description': 'Potential replay attack detected'\n            })\n\n        return alerts\n\n    def _detect_port_scan(self, traffic):\n        \"\"\"\n        Detect port scanning:\n        - Multiple connection attempts to different ports\n        - From same source IP in short time window\n        \"\"\"\n\n        src_ip = traffic.get('src_ip')\n        unique_ports = traffic.get('unique_dst_ports', [])\n        time_window = traffic.get('time_window_sec', 0)\n\n        # More than 20 ports in 10 seconds = port scan\n        if len(unique_ports) > 20 and time_window \u003C 10:\n            return True\n\n        return False\n\n    def _detect_dos(self, traffic):\n        \"\"\"\n        Detect Denial of Service:\n        - Packet rate > 10x baseline\n        - Same message repeated at high rate\n        \"\"\"\n\n        pkt_rate = traffic.get('packets_per_second', 0)\n        baseline_rate = self.baseline.get('avg_pkt_rate', 100)\n\n        if pkt_rate > baseline_rate * 10:\n            return True\n\n        return False\n\n    def _detect_unauthorized_service_access(self, traffic):\n        \"\"\"\n        Detect unauthorized SOME\u002FIP service access:\n        - Access to service not in whitelist\n        - Access from unauthorized client\n        \"\"\"\n\n        service_id = traffic.get('someip_service_id')\n        client_ip = traffic.get('src_ip')\n\n        authorized_services = {\n            0x1234: ['192.168.1.1'],  # Battery service - gateway only\n            0x5678: ['192.168.1.1', '192.168.1.10']  # Body service - gateway + FL zone\n        }\n\n        if service_id in authorized_services:\n            if client_ip not in authorized_services[service_id]:\n                return True\n\n        return False\n\n    def _detect_arp_spoofing(self, traffic):\n        \"\"\"\n        Detect ARP spoofing:\n        - Different MAC for same IP\n        - Gratuitous ARP with conflicting info\n        \"\"\"\n\n        if traffic.get('protocol') == 'ARP':\n            ip = traffic.get('ip')\n            mac = traffic.get('mac')\n\n            known_mac = self.baseline.get('ip_to_mac', {}).get(ip)\n\n            if known_mac and known_mac != mac:\n                return True  # MAC changed for this IP\n\n        return False\n\n    def _detect_replay(self, traffic):\n        \"\"\"\n        Detect replay attacks:\n        - Same packet repeated (duplicate sequence numbers)\n        - Packet rate anomaly for specific message\n        \"\"\"\n\n        msg_id = traffic.get('msg_id')\n        pkt_count = traffic.get('pkt_count', 0)\n        baseline_count = self.baseline.get('msg_counts', {}).get(msg_id, 1)\n\n        if pkt_count > baseline_count * 5:\n            return True\n\n        return False\n```\n\n### 5. Secure Gateway Design\n\n```c\n\u002F\u002F Secure gateway functionality\ntypedef struct {\n    uint8_t zone_count;\n    struct {\n        uint8_t zone_id;\n        uint32_t ip_address;\n        uint8_t vlan_id;\n        bool macsec_enabled;\n        bool ipsec_enabled;\n        bool firewall_enabled;\n    } zones[8];\n\n    struct {\n        bool ids_enabled;\n        bool ips_enabled;           \u002F\u002F Intrusion Prevention\n        uint16_t alert_threshold;\n        char siem_server[64];       \u002F\u002F SIEM logging\n    } security;\n\n} SecureGateway_t;\n\n\u002F\u002F Example gateway configuration\nSecureGateway_t gateway = {\n    .zone_count = 4,\n    .zones = {\n        {.zone_id = 1, .ip_address = 0xC0A80110, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true},  \u002F\u002F FL Zone\n        {.zone_id = 2, .ip_address = 0xC0A80120, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true},  \u002F\u002F FR Zone\n        {.zone_id = 3, .ip_address = 0xC0A80130, .vlan_id = 200, .macsec_enabled = true, .ipsec_enabled = true, .firewall_enabled = true},   \u002F\u002F ADAS Zone (extra IPsec)\n        {.zone_id = 4, .ip_address = 0xC0A80140, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true}   \u002F\u002F RL Zone\n    },\n\n    .security = {\n        .ids_enabled = true,\n        .ips_enabled = true,        \u002F\u002F Block detected attacks automatically\n        .alert_threshold = 10,      \u002F\u002F Alert after 10 suspicious events\n        .siem_server = \"192.168.99.10\"\n    }\n};\n```\n\n## Security Architecture Layers\n\n```\n┌────────────────────────────────────────────┐\n│  Layer 7: Application Security            │\n│  - SOME\u002FIP authentication                 │\n│  - Service access control                 │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 4-6: Transport\u002FSession Security    │\n│  - IPsec (ESP): End-to-end encryption     │\n│  - TLS 1.3: For diagnostic protocols      │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 3: Network Security                │\n│  - Firewall: Packet filtering             │\n│  - IDS\u002FIPS: Anomaly detection             │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 2: Data Link Security              │\n│  - MACsec (IEEE 802.1AE): Link encryption │\n│  - 802.1X: Port-based authentication      │\n└────────────────────────────────────────────┘\n```\n\n## Key Management\n\n```python\nclass VehicleKeyManagement:\n    \"\"\"\n    Key management for MACsec and IPsec.\n    Supports both static provisioning and dynamic key exchange.\n    \"\"\"\n\n    def __init__(self):\n        self.keys = {}\n        self.key_lifetime_hours = 24  # Rotate every 24 hours\n\n    def provision_static_key(self, zone_id, key_type, key_material):\n        \"\"\"\n        Provision static key during manufacturing.\n\n        Args:\n            zone_id: Zone controller ID\n            key_type: 'MACSEC' or 'IPSEC'\n            key_material: 256-bit key\n        \"\"\"\n\n        self.keys[zone_id] = {\n            'type': key_type,\n            'key': key_material,\n            'provisioned_at': time.time(),\n            'valid_until': time.time() + (self.key_lifetime_hours * 3600)\n        }\n\n    def rotate_keys(self):\n        \"\"\"\n        Automatic key rotation every 24 hours.\n        Uses Diffie-Hellman key exchange for new keys.\n        \"\"\"\n\n        for zone_id, key_info in self.keys.items():\n            if time.time() > key_info['valid_until']:\n                # Generate new key\n                new_key = self._dh_key_exchange(zone_id)\n                self.keys[zone_id]['key'] = new_key\n                self.keys[zone_id]['valid_until'] = time.time() + (self.key_lifetime_hours * 3600)\n\n    def _dh_key_exchange(self, zone_id):\n        \"\"\"Diffie-Hellman key exchange (simplified).\"\"\"\n        # In production, use proper DH or ECDH\n        import secrets\n        return secrets.token_bytes(32)  # 256-bit key\n```\n\n## Performance Impact\n\n| Security Feature | Latency Overhead | CPU Overhead | Throughput Impact |\n|------------------|------------------|--------------|-------------------|\n| MACsec (AES-128) | +100 μs | +10% | -5% |\n| MACsec (AES-256) | +150 μs | +15% | -8% |\n| IPsec (ESP) | +200 μs | +20% | -10% |\n| Firewall | +50 μs | +5% | -2% |\n| IDS (passive) | +10 μs | +8% | 0% |\n| IPS (active) | +100 μs | +15% | -5% |\n\n## Tools & Testing\n\n- **Wireshark with MACsec plugin** - Decrypt and analyze MACsec traffic\n- **Scapy** - Craft attack packets for security testing\n- **Suricata** - Open-source IDS\u002FIPS engine\n- **Kali Linux** - Penetration testing toolkit\n- **CANalyze** - Automotive-specific security testing\n\n## References\n\n- IEEE 802.1AE (MACsec) Standard\n- ISO\u002FSAE 21434 Cybersecurity Engineering\n- UNECE R155 Cybersecurity Regulation\n- AUTOSAR Secure Communication Specification\n\n---\n\n## Service Oriented Communication\n\n# Service-Oriented Communication - SOME\u002FIP & DDS\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in service-oriented middleware for automotive zonal architectures. Covers SOME\u002FIP (Scalable Service-Oriented Middleware over IP), DDS (Data Distribution Service), service discovery, publish-subscribe patterns, event-driven architecture, and method invocations over Ethernet.\n\n## Core Competencies\n\n### 1. SOME\u002FIP (AUTOSAR Standard)\n\n#### Protocol Overview\n\n**SOME\u002FIP = Scalable Service-Oriented Middleware over IP**\n- Used in AUTOSAR Adaptive Platform\n- Transport: UDP or TCP over IPv4\u002FIPv6\n- Serialization: SOME\u002FIP binary format\n- Discovery: SOME\u002FIP-SD (Service Discovery)\n\n```c\n\u002F\u002F SOME\u002FIP Message Header (16 bytes)\ntypedef struct __attribute__((packed)) {\n    uint32_t message_id;      \u002F\u002F Service ID (16 bits) + Method ID (16 bits)\n    uint32_t length;          \u002F\u002F Payload length + 8\n    uint32_t request_id;      \u002F\u002F Client ID (16 bits) + Session ID (16 bits)\n    uint8_t  protocol_version; \u002F\u002F 0x01\n    uint8_t  interface_version; \u002F\u002F Service interface version\n    uint8_t  message_type;    \u002F\u002F REQUEST=0x00, RESPONSE=0x80, ERROR=0x81, NOTIFICATION=0x02\n    uint8_t  return_code;     \u002F\u002F E_OK=0x00, E_NOT_OK=0x01, etc.\n} SOMEIP_Header_t;\n\n\u002F\u002F Example: Request message\nSOMEIP_Header_t request = {\n    .message_id = 0x12340001,  \u002F\u002F Service 0x1234, Method 0x0001\n    .length = 24,              \u002F\u002F Header (16) + Payload (8)\n    .request_id = 0x00010001,  \u002F\u002F Client 0x0001, Session 0x0001\n    .protocol_version = 0x01,\n    .interface_version = 0x01,\n    .message_type = 0x00,      \u002F\u002F REQUEST\n    .return_code = 0x00        \u002F\u002F E_OK\n};\n```\n\n#### Service Definition (FIDL)\n\n```fidl\n\u002F\u002F Franca IDL (FIDL) - SOME\u002FIP Service Definition\npackage org.genivi.battery\n\ninterface BatteryManagementService {\n    version { major 1 minor 0 }\n\n    \u002F\u002F Methods (Request\u002FResponse)\n    method GetBatteryStatus {\n        out {\n            UInt8 stateOfCharge    \u002F\u002F 0-100%\n            Float voltage           \u002F\u002F Volts\n            Float current           \u002F\u002F Amps\n            Int8 temperature        \u002F\u002F Celsius\n        }\n    }\n\n    method SetChargingLimit {\n        in {\n            UInt8 targetSoC        \u002F\u002F Target SOC %\n        }\n        out {\n            Boolean success\n        }\n    }\n\n    \u002F\u002F Events (Notifications)\n    broadcast BatteryAlarm {\n        out {\n            UInt16 alarmCode\n            String description\n        }\n    }\n\n    \u002F\u002F Attributes (Getter\u002FSetter\u002FNotification)\n    attribute UInt8 stateOfCharge readonly\n\n    \u002F\u002F Error codes\n    enumeration BatteryError {\n        OK = 0\n        INVALID_PARAMETER = 1\n        HARDWARE_FAULT = 2\n        COMMUNICATION_ERROR = 3\n    }\n}\n```\n\n#### SOME\u002FIP Service Implementation\n\n```cpp\n#include \u003CCommonAPI\u002FCommonAPI.hpp>\n#include \u003Cv1\u002Forg\u002Fgenivi\u002Fbattery\u002FBatteryManagementServiceProxy.hpp>\n\nusing namespace v1::org::genivi::battery;\n\nclass BatteryClient {\npublic:\n    BatteryClient() {\n        runtime_ = CommonAPI::Runtime::get();\n        proxy_ = runtime_->buildProxy\u003CBatteryManagementServiceProxy>(\n            \"local\", \"BatteryService\");\n\n        \u002F\u002F Wait for service availability\n        while (!proxy_->isAvailable()) {\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n\n        \u002F\u002F Subscribe to battery alarms\n        proxy_->getBatteryAlarmEvent().subscribe(\n            [](uint16_t alarmCode, std::string description) {\n                std::cout \u003C\u003C \"Alarm \" \u003C\u003C alarmCode \u003C\u003C \": \"\n                          \u003C\u003C description \u003C\u003C std::endl;\n            });\n    }\n\n    void getBatteryStatus() {\n        \u002F\u002F Synchronous method call\n        CommonAPI::CallStatus callStatus;\n        uint8_t soc;\n        float voltage, current;\n        int8_t temperature;\n\n        proxy_->GetBatteryStatus(callStatus, soc, voltage, current, temperature);\n\n        if (callStatus == CommonAPI::CallStatus::SUCCESS) {\n            std::cout \u003C\u003C \"SOC: \" \u003C\u003C (int)soc \u003C\u003C \"%\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Voltage: \" \u003C\u003C voltage \u003C\u003C \"V\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Current: \" \u003C\u003C current \u003C\u003C \"A\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Temperature: \" \u003C\u003C (int)temperature \u003C\u003C \"°C\" \u003C\u003C std::endl;\n        }\n    }\n\n    void setChargingLimit(uint8_t targetSoC) {\n        \u002F\u002F Asynchronous method call with callback\n        proxy_->SetChargingLimitAsync(\n            targetSoC,\n            [](const CommonAPI::CallStatus& status, bool success) {\n                if (status == CommonAPI::CallStatus::SUCCESS && success) {\n                    std::cout \u003C\u003C \"Charging limit set successfully\" \u003C\u003C std::endl;\n                }\n            });\n    }\n\nprivate:\n    std::shared_ptr\u003CCommonAPI::Runtime> runtime_;\n    std::shared_ptr\u003CBatteryManagementServiceProxy\u003C>> proxy_;\n};\n```\n\n#### SOME\u002FIP-SD (Service Discovery)\n\n```python\nclass SOMEIPServiceDiscovery:\n    \"\"\"\n    SOME\u002FIP Service Discovery (SOME\u002FIP-SD) implementation.\n    Uses UDP multicast (224.244.224.245:30490) for service advertisement.\n    \"\"\"\n\n    def __init__(self):\n        self.multicast_group = '224.244.224.245'\n        self.multicast_port = 30490\n        self.services = {}\n\n    def offer_service(self, service_id, instance_id, endpoint):\n        \"\"\"\n        Offer a service via SOME\u002FIP-SD.\n\n        Args:\n            service_id: Service identifier (16-bit)\n            instance_id: Instance identifier (16-bit)\n            endpoint: (IP, port, protocol)  protocol='UDP' or 'TCP'\n        \"\"\"\n\n        offer_message = {\n            'message_type': 'OfferService',\n            'service_id': service_id,\n            'instance_id': instance_id,\n            'major_version': 1,\n            'minor_version': 0,\n            'ttl': 3,  # Time-to-live in seconds (0xFFFFFF = infinite)\n            'endpoint': {\n                'ipv4': endpoint[0],\n                'port': endpoint[1],\n                'protocol': endpoint[2]  # UDP or TCP\n            }\n        }\n\n        # Send cyclic offers (every 1 second)\n        # Until service is stopped\n        return offer_message\n\n    def find_service(self, service_id, instance_id=None):\n        \"\"\"\n        Find a service via SOME\u002FIP-SD.\n\n        Args:\n            service_id: Service to find\n            instance_id: Specific instance (None = any)\n\n        Returns:\n            List of available service endpoints\n        \"\"\"\n\n        find_message = {\n            'message_type': 'FindService',\n            'service_id': service_id,\n            'instance_id': instance_id if instance_id else 0xFFFF,  # ANY\n            'major_version': 0xFF,  # ANY\n            'minor_version': 0xFFFFFFFF  # ANY\n        }\n\n        # Wait for OfferService responses\n        # Return list of endpoints\n        return []\n\n# Example usage:\nsd = SOMEIPServiceDiscovery()\n\n# Offer battery service\nsd.offer_service(\n    service_id=0x1234,\n    instance_id=0x0001,\n    endpoint=('192.168.1.10', 30500, 'UDP')\n)\n\n# Find battery service\nendpoints = sd.find_service(service_id=0x1234)\n```\n\n### 2. DDS (Data Distribution Service)\n\n#### DDS Quality of Service (QoS)\n\n```python\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nclass ReliabilityKind(Enum):\n    BEST_EFFORT = 0  # UDP-like, lossy\n    RELIABLE = 1      # TCP-like, guaranteed delivery\n\nclass DurabilityKind(Enum):\n    VOLATILE = 0          # Only for live data\n    TRANSIENT_LOCAL = 1   # Store last value for late joiners\n    TRANSIENT = 2         # Persist across processes\n    PERSISTENT = 3        # Persist to disk\n\n@dataclass\nclass DDSQoS:\n    \"\"\"DDS Quality of Service configuration.\"\"\"\n\n    reliability: ReliabilityKind\n    durability: DurabilityKind\n    history_depth: int  # Number of samples to keep\n    max_blocking_time_ms: int  # Max time to block writer\n    latency_budget_ms: int  # Hint for latency optimization\n    lifespan_ms: int  # Sample validity duration\n\n# Example QoS profiles for different use cases\n\n# Safety-critical real-time data (ESC, ABS)\nSAFETY_QOS = DDSQoS(\n    reliability=ReliabilityKind.RELIABLE,\n    durability=DurabilityKind.VOLATILE,\n    history_depth=1,  # Only latest value matters\n    max_blocking_time_ms=10,\n    latency_budget_ms=5,\n    lifespan_ms=100\n)\n\n# Sensor data (high-rate, best-effort)\nSENSOR_QOS = DDSQoS(\n    reliability=ReliabilityKind.BEST_EFFORT,\n    durability=DurabilityKind.VOLATILE,\n    history_depth=5,\n    max_blocking_time_ms=0,  # Non-blocking\n    latency_budget_ms=1,\n    lifespan_ms=50\n)\n\n# Configuration data (late-joiner support)\nCONFIG_QOS = DDSQoS(\n    reliability=ReliabilityKind.RELIABLE,\n    durability=DurabilityKind.TRANSIENT_LOCAL,\n    history_depth=1,\n    max_blocking_time_ms=1000,\n    latency_budget_ms=100,\n    lifespan_ms=0  # No expiration\n)\n```\n\n#### DDS Topic Definition (IDL)\n\n```idl\n\u002F\u002F OMG IDL for DDS topics\nmodule automotive {\n    module battery {\n\n        struct BatteryStatus {\n            unsigned long timestamp;    \u002F\u002F Unix timestamp (ms)\n            octet stateOfCharge;        \u002F\u002F 0-100%\n            float voltage;              \u002F\u002F Volts\n            float current;              \u002F\u002F Amps\n            char temperature;           \u002F\u002F Celsius\n            boolean charging;\n        };\n\n        struct BatteryAlarm {\n            unsigned long timestamp;\n            unsigned short alarmCode;\n            string\u003C256> description;\n            octet severity;  \u002F\u002F 0=Info, 1=Warning, 2=Error, 3=Critical\n        };\n\n    };\n};\n```\n\n#### DDS Publisher\u002FSubscriber (C++)\n\n```cpp\n#include \u003Cdds\u002Fdds.hpp>\n#include \"BatteryStatus.hpp\"\n\nusing namespace automotive::battery;\n\nclass BatteryPublisher {\npublic:\n    BatteryPublisher() {\n        \u002F\u002F Create DDS participant (one per application)\n        participant_ = dds::domain::DomainParticipant(0);\n\n        \u002F\u002F Create topic\n        topic_ = dds::topic::Topic\u003CBatteryStatus>(\n            participant_, \"BatteryStatusTopic\");\n\n        \u002F\u002F Create publisher with QoS\n        dds::pub::qos::PublisherQos pub_qos;\n        publisher_ = dds::pub::Publisher(participant_, pub_qos);\n\n        \u002F\u002F Create data writer\n        dds::pub::qos::DataWriterQos writer_qos;\n        writer_qos \u003C\u003C SAFETY_QOS;  \u002F\u002F Use safety QoS profile\n        writer_ = dds::pub::DataWriter\u003CBatteryStatus>(publisher_, topic_, writer_qos);\n    }\n\n    void publishStatus(uint8_t soc, float voltage, float current, int8_t temp) {\n        BatteryStatus status;\n        status.timestamp(std::chrono::system_clock::now().time_since_epoch().count());\n        status.stateOfCharge(soc);\n        status.voltage(voltage);\n        status.current(current);\n        status.temperature(temp);\n        status.charging(current > 0);\n\n        writer_.write(status);\n    }\n\nprivate:\n    dds::domain::DomainParticipant participant_;\n    dds::topic::Topic\u003CBatteryStatus> topic_;\n    dds::pub::Publisher publisher_;\n    dds::pub::DataWriter\u003CBatteryStatus> writer_;\n};\n\nclass BatterySubscriber {\npublic:\n    BatterySubscriber() {\n        participant_ = dds::domain::DomainParticipant(0);\n        topic_ = dds::topic::Topic\u003CBatteryStatus>(\n            participant_, \"BatteryStatusTopic\");\n\n        dds::sub::qos::SubscriberQos sub_qos;\n        subscriber_ = dds::sub::Subscriber(participant_, sub_qos);\n\n        dds::sub::qos::DataReaderQos reader_qos;\n        reader_qos \u003C\u003C SAFETY_QOS;\n        reader_ = dds::sub::DataReader\u003CBatteryStatus>(subscriber_, topic_, reader_qos);\n\n        \u002F\u002F Register listener for data arrival\n        reader_.listener(\n            new BatteryStatusListener(),\n            dds::core::status::StatusMask::data_available());\n    }\n\nprivate:\n    class BatteryStatusListener : public dds::sub::NoOpDataReaderListener\u003CBatteryStatus> {\n    public:\n        void on_data_available(dds::sub::DataReader\u003CBatteryStatus>& reader) override {\n            auto samples = reader.take();\n            for (const auto& sample : samples) {\n                if (sample.info().valid()) {\n                    std::cout \u003C\u003C \"SOC: \" \u003C\u003C (int)sample.data().stateOfCharge() \u003C\u003C \"%\"\n                              \u003C\u003C \" Voltage: \" \u003C\u003C sample.data().voltage() \u003C\u003C \"V\"\n                              \u003C\u003C std::endl;\n                }\n            }\n        }\n    };\n\n    dds::domain::DomainParticipant participant_;\n    dds::topic::Topic\u003CBatteryStatus> topic_;\n    dds::sub::Subscriber subscriber_;\n    dds::sub::DataReader\u003CBatteryStatus> reader_;\n};\n```\n\n### 3. Service Discovery Mechanisms\n\n#### Comparison\n\n| Feature | SOME\u002FIP-SD | DDS Discovery |\n|---------|-----------|---------------|\n| Transport | UDP multicast | UDP\u002FTCP multicast + unicast |\n| Discovery time | 1-3 seconds | \u003C100ms |\n| Overhead | Low (periodic offers) | Medium (SPDP + SEDP) |\n| Dynamic reconfiguration | Yes | Yes |\n| QoS negotiation | Limited | Extensive |\n| Best for | AUTOSAR Adaptive | Complex data flows |\n\n### 4. Event-Driven Architecture Patterns\n\n```python\nclass EventBus:\n    \"\"\"\n    Automotive event bus for service-oriented communication.\n    Supports both SOME\u002FIP and DDS backends.\n    \"\"\"\n\n    def __init__(self, backend='someip'):\n        self.backend = backend\n        self.subscribers = {}\n\n    def publish(self, topic, data, qos='reliable'):\n        \"\"\"\n        Publish event to topic.\n\n        Args:\n            topic: Event topic name\n            data: Event payload\n            qos: 'reliable' or 'best_effort'\n        \"\"\"\n\n        if self.backend == 'someip':\n            # SOME\u002FIP notification\n            self._someip_notify(topic, data)\n        elif self.backend == 'dds':\n            # DDS publish\n            self._dds_publish(topic, data, qos)\n\n    def subscribe(self, topic, callback, qos='reliable'):\n        \"\"\"\n        Subscribe to topic with callback.\n\n        Args:\n            topic: Topic name\n            callback: Function to call on event\n            qos: QoS requirements\n        \"\"\"\n\n        if topic not in self.subscribers:\n            self.subscribers[topic] = []\n\n        self.subscribers[topic].append({\n            'callback': callback,\n            'qos': qos\n        })\n\n        if self.backend == 'someip':\n            self._someip_subscribe(topic)\n        elif self.backend == 'dds':\n            self._dds_subscribe(topic, qos)\n\n# Usage example:\nbus = EventBus(backend='someip')\n\n# Subscribe to battery alarms\nbus.subscribe('battery\u002Falarm', lambda alarm: print(f\"Alarm: {alarm}\"))\n\n# Publish alarm event\nbus.publish('battery\u002Falarm', {\n    'code': 0x1234,\n    'severity': 'critical',\n    'description': 'Over-temperature detected'\n})\n```\n\n## Performance Characteristics\n\n### SOME\u002FIP\n- **Latency**: 1-5ms (local), 10-50ms (remote)\n- **Throughput**: Up to 100 Mbps per service\n- **Overhead**: ~16 bytes header per message\n- **Discovery time**: 1-3 seconds (configurable)\n\n### DDS\n- **Latency**: \u003C1ms (local), 5-20ms (remote)\n- **Throughput**: Up to 1 Gbps aggregate\n- **Overhead**: ~20 bytes RTPS header\n- **Discovery time**: \u003C100ms\n\n## Best Practices\n\n1. **Use SOME\u002FIP** for AUTOSAR Adaptive services, ECU-to-ECU communication\n2. **Use DDS** for high-throughput sensor data, complex QoS requirements\n3. **Choose UDP** for time-critical best-effort data (sensors)\n4. **Choose TCP** for reliable control commands, configuration\n5. **Minimize service interfaces** - Fewer, richer services better than many small ones\n6. **Use service versioning** - Major version in service ID, minor in header\n\n## Tools\n\n- **Vector MICROSAR** - SOME\u002FIP stack for AUTOSAR Classic\u002FAdaptive\n- **RTI Connext DDS** - High-performance DDS implementation\n- **Eclipse Cyclone DDS** - Open-source DDS (used in ROS 2)\n- **vsomeip** - Open-source SOME\u002FIP implementation (BMW\u002FGENIVI)\n- **CommonAPI** - Language bindings for SOME\u002FIP and DDS\n\n## References\n\n- AUTOSAR Specification of SOME\u002FIP Protocol (PRS_SOMEIPPROTOCOL)\n- OMG Data Distribution Service (DDS) Specification v1.4\n- AUTOSAR Adaptive Platform R22-11\n- SOME\u002FIP Protocol Specification v1.3.0\n\n---\n\n## Zonal Architecture Design\n\n# Zonal Architecture Design\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in designing next-generation vehicle E\u002FE zonal architectures. Covers zone controller placement, domain consolidation, topology optimization, cable harness reduction strategies, and migration from traditional domain architectures to zonal designs.\n\n## Core Competencies\n\n### 1. Zone Controller Placement Strategy\n\n#### Optimal Zone Count\nTypical modern vehicles use **4-8 zones**:\n- **4 zones**: Entry-level vehicles (FL, FR, RL, RR corners)\n- **6 zones**: Mid-range (4 corners + front-center + rear-center)\n- **8 zones**: Premium (4 corners + FC, RC, left-center, right-center)\n\n**Placement Criteria:**\n```python\nclass ZonePlacementOptimizer:\n    def __init__(self, vehicle_model):\n        self.vehicle = vehicle_model\n        self.sensors = []\n        self.actuators = []\n\n    def optimize_zones(self, max_cable_length=2.0):\n        \"\"\"\n        Optimize zone placement to minimize cable length.\n\n        Args:\n            max_cable_length: Maximum cable run in meters (default 2m)\n\n        Returns:\n            List of zone controller locations\n        \"\"\"\n        from sklearn.cluster import KMeans\n        import numpy as np\n\n        # Get all sensor\u002Factuator positions\n        positions = np.array([\n            [comp.x, comp.y, comp.z]\n            for comp in self.sensors + self.actuators\n        ])\n\n        # Cluster to find optimal zone centers\n        n_zones = self._estimate_zone_count(positions, max_cable_length)\n        kmeans = KMeans(n_clusters=n_zones, random_state=42)\n        kmeans.fit(positions)\n\n        zones = []\n        for i, center in enumerate(kmeans.cluster_centers_):\n            zone = {\n                'id': f'ZCU_{i+1}',\n                'location': center.tolist(),\n                'components': [],\n                'cable_savings': 0.0\n            }\n\n            # Assign components to zones\n            labels = kmeans.labels_\n            zone_components = [\n                comp for idx, comp in enumerate(self.sensors + self.actuators)\n                if labels[idx] == i\n            ]\n            zone['components'] = zone_components\n            zones.append(zone)\n\n        return zones\n\n    def _estimate_zone_count(self, positions, max_length):\n        \"\"\"Estimate optimal number of zones based on component density.\"\"\"\n        bbox = positions.max(axis=0) - positions.min(axis=0)\n        vehicle_length = bbox[0]\n        vehicle_width = bbox[1]\n\n        # Coverage area per zone (circle of radius max_length)\n        zone_coverage = np.pi * (max_length ** 2)\n        vehicle_area = vehicle_length * vehicle_width\n\n        return max(4, int(np.ceil(vehicle_area \u002F zone_coverage)))\n```\n\n#### Zone Controller Hardware Selection\n\n| Zone Type | Hardware Platform | Cost | Use Case |\n|-----------|------------------|------|----------|\n| **Low-cost Corner** | NXP S32K344 | $15-20 | Lighting, windows, mirrors |\n| **Standard Zone** | Renesas RH850\u002FU2A | $25-35 | Body control, HVAC, doors |\n| **Gateway\u002FCentral** | NXP S32G274A | $80-120 | Ethernet switch, firewall, routing |\n| **High-performance** | Infineon AURIX TC397 | $60-90 | ADAS integration, safety |\n\n**Selection Decision Tree:**\n```\nIs zone safety-critical (ASIL-C\u002FD)?\n├─ Yes → AURIX TC397 (lockstep cores, ECC RAM)\n└─ No → Does zone need Ethernet switching?\n    ├─ Yes → S32G274A (4x Gb Ethernet, TSN)\n    └─ No → Component count?\n        ├─ \u003C20 → S32K344 (low-cost)\n        └─ >20 → RH850\u002FU2A (more I\u002FO)\n```\n\n### 2. Cable Harness Reduction\n\n**Traditional Domain Architecture:**\n```\nTotal cable length: 4,500 meters\nTotal weight: 45 kg\nCost: $450 per vehicle\n```\n\n**Zonal Architecture Benefits:**\n```python\nclass CableHarnessAnalyzer:\n    def calculate_savings(self, domain_arch, zonal_arch):\n        \"\"\"\n        Calculate cable harness savings from domain-to-zonal migration.\n\n        Returns:\n            dict: Savings in length, weight, and cost\n        \"\"\"\n        # Domain architecture stats\n        domain_cables = {\n            'sensor_to_ecu': 2800,  # meters\n            'inter_ecu': 1200,\n            'power_distribution': 500\n        }\n\n        # Zonal architecture stats\n        zonal_cables = {\n            'sensor_to_zone': 1500,  # \u003C2m each, drastically shorter\n            'zone_to_gateway': 150,  # Ethernet backbone only\n            'power_distribution': 300  # Zonal PDUs\n        }\n\n        total_domain = sum(domain_cables.values())\n        total_zonal = sum(zonal_cables.values())\n\n        reduction_meters = total_domain - total_zonal\n        reduction_percent = (reduction_meters \u002F total_domain) * 100\n\n        # Weight savings (0.01 kg\u002Fmeter average)\n        weight_savings = reduction_meters * 0.01  # kg\n\n        # Cost savings ($0.10\u002Fmeter cable + installation)\n        cost_savings = reduction_meters * 0.15  # USD\n\n        return {\n            'cable_reduction_m': reduction_meters,\n            'cable_reduction_pct': reduction_percent,\n            'weight_savings_kg': weight_savings,\n            'cost_savings_usd': cost_savings\n        }\n\n# Example output:\n# {\n#     'cable_reduction_m': 2550,\n#     'cable_reduction_pct': 56.7%,\n#     'weight_savings_kg': 25.5 kg,\n#     'cost_savings_usd': $382.50\n# }\n```\n\n**Actual OEM Results:**\n- **VW MEB Platform**: 30% cable reduction\n- **Tesla Model 3**: 1.5 km total harness (vs 3 km traditional)\n- **Rivian R1T**: 40% weight reduction in harness\n\n### 3. Network Topology Design\n\n#### Topology Options\n\n**A. Star Topology (Recommended for Safety)**\n```\n                    ┌─────────────┐\n                    │   Gateway   │\n                    │   S32G274   │\n                    └──────┬──────┘\n                           │\n        ┌──────────────┬───┴───┬──────────────┐\n        │              │       │              │\n    ┌───┴───┐      ┌───┴───┐ ┌┴─────┐    ┌───┴───┐\n    │ FL ZCU│      │ FR ZCU│ │RC ZCU│    │ RL ZCU│\n    └───────┘      └───────┘ └──────┘    └───────┘\n\nPros:\n+ Direct gateway connection (low latency)\n+ Simple fault isolation\n+ Easy TSN configuration\n+ No cascading failures\n\nCons:\n- More cable to gateway\n- Single point of failure (mitigated with redundant gateway)\n```\n\n**B. Ring Topology (High Availability)**\n```\n    ┌─────────┐──────┐Gateway│──────┐─────────┐\n    │         │      └────────┘      │         │\n    │         │                      │         │\n┌───┴───┐ ┌───┴───┐              ┌───┴───┐ ┌───┴───┐\n│FL ZCU │ │FR ZCU │              │RR ZCU │ │RL ZCU │\n└───────┘ └───────┘              └───────┘ └───────┘\n\nPros:\n+ Redundant paths (fault tolerance)\n+ Load balancing possible\n+ Cable length optimization\n\nCons:\n- Complex TSN configuration\n- Potential for loops (need STP\u002FRSTP)\n```\n\n**C. Daisy Chain (Cost-Optimized)**\n```\n┌────────┐    ┌──────┐    ┌──────┐    ┌──────┐    ┌──────┐\n│Gateway │────│FL ZCU│────│FR ZCU│────│RR ZCU│────│RL ZCU│\n└────────┘    └──────┘    └──────┘    └──────┘    └──────┘\n\nPros:\n+ Minimal cable length\n+ Lowest cost\n\nCons:\n- Cascading failures\n- Higher latency for distant zones\n- Not suitable for safety-critical\n```\n\n#### Ethernet Physical Layer Selection\n\n```c\n\u002F\u002F 100BASE-T1 Configuration (Standard zones)\nstruct ethernet_phy_config {\n    uint8_t standard;        \u002F\u002F 100BASE-T1\n    uint16_t max_distance;   \u002F\u002F 15 meters\n    uint32_t bandwidth;      \u002F\u002F 100 Mbps\n    uint8_t pair_count;      \u002F\u002F 1 twisted pair\n    float cost_per_meter;    \u002F\u002F $0.50\n};\n\n\u002F\u002F 1000BASE-T1 Configuration (High-bandwidth zones - cameras, ADAS)\nstruct ethernet_phy_1g {\n    uint8_t standard;        \u002F\u002F 1000BASE-T1\n    uint16_t max_distance;   \u002F\u002F 40 meters\n    uint32_t bandwidth;      \u002F\u002F 1 Gbps\n    uint8_t pair_count;      \u002F\u002F 1 twisted pair\n    float cost_per_meter;    \u002F\u002F $0.80\n};\n\n\u002F\u002F 10BASE-T1S Configuration (Low-cost multidrop sensors)\nstruct ethernet_phy_10base {\n    uint8_t standard;        \u002F\u002F 10BASE-T1S\n    uint16_t max_distance;   \u002F\u002F 25 meters (multidrop bus)\n    uint32_t bandwidth;      \u002F\u002F 10 Mbps\n    uint8_t topology;        \u002F\u002F Multidrop (up to 8 nodes per segment)\n    float cost_per_meter;    \u002F\u002F $0.30\n};\n```\n\n### 4. Power Distribution Architecture\n\n**Zonal Power Distribution Units (PDUs):**\n\n```c\ntypedef struct {\n    char zone_id[16];\n    uint8_t num_power_rails;\n    float voltage_12v;\n    float voltage_5v;\n    float voltage_3v3;\n    uint8_t load_shedding_priority[8];  \u002F\u002F 0=critical, 7=lowest\n    bool intelligent_fusing;\n} ZonalPDU_Config_t;\n\n\u002F\u002F Example: Front-Left Zone PDU\nZonalPDU_Config_t fl_pdu = {\n    .zone_id = \"FL_ZONE\",\n    .num_power_rails = 8,\n    .voltage_12v = 12.0,\n    .voltage_5v = 5.0,\n    .voltage_3v3 = 3.3,\n    .load_shedding_priority = {\n        0,  \u002F\u002F Headlights (critical)\n        1,  \u002F\u002F Turn signals (safety)\n        2,  \u002F\u002F DRL (legal requirement)\n        5,  \u002F\u002F Fog lights\n        6,  \u002F\u002F Puddle lights\n        7,  \u002F\u002F Ambient lighting\n    },\n    .intelligent_fusing = true\n};\n\n\u002F\u002F Load shedding during low battery\nvoid perform_load_shedding(ZonalPDU_Config_t *pdu, uint8_t battery_soc) {\n    if (battery_soc \u003C 20) {\n        \u002F\u002F Shed priority 7 loads (ambient lighting)\n        disable_loads_by_priority(pdu, 7);\n    }\n    if (battery_soc \u003C 10) {\n        \u002F\u002F Shed priority 6 loads (puddle lights)\n        disable_loads_by_priority(pdu, 6);\n    }\n    if (battery_soc \u003C 5) {\n        \u002F\u002F Shed priority 5 loads (fog lights)\n        disable_loads_by_priority(pdu, 5);\n        \u002F\u002F Keep only priority 0-2 (critical\u002Fsafety)\n    }\n}\n```\n\n**Power Budget per Zone:**\n| Zone | Typical Power | Peak Power | Components |\n|------|--------------|-----------|------------|\n| FL Corner | 150W | 300W | Headlights, turn signals, window, mirror |\n| FR Corner | 150W | 300W | Headlights, turn signals, window, mirror |\n| RL Corner | 100W | 200W | Taillights, window |\n| RR Corner | 100W | 200W | Taillights, window |\n| Front Center | 200W | 400W | Wipers, HVAC blower, sensors |\n| Rear Center | 80W | 150W | Trunk, license plate light |\n\n### 5. Domain-to-Zonal Migration Strategy\n\n**Phase 1: Hybrid Architecture (18-24 months)**\n- Keep existing domain ECUs\n- Add zone controllers for new sensors\n- Use gateway to bridge domains and zones\n- Validate zonal concept\n\n**Phase 2: Partial Migration (24-36 months)**\n- Migrate body domain to zonal\n- Keep powertrain\u002FADAS domains\n- 40-50% cable reduction achieved\n\n**Phase 3: Full Zonal (36-48 months)**\n- All functions on zone controllers\n- Domain ECUs eliminated\n- 50-60% cable reduction\n- Central compute for ADAS\u002Finfotainment\n\n```python\nclass MigrationPlanner:\n    def create_migration_roadmap(self):\n        \"\"\"Generate phased migration from domain to zonal architecture.\"\"\"\n\n        phases = [\n            {\n                'phase': 1,\n                'name': 'Hybrid Introduction',\n                'duration_months': 18,\n                'zones_added': ['FL', 'FR'],\n                'functions_migrated': ['Lighting', 'Windows'],\n                'cable_reduction': '15%',\n                'cost': '$2M NRE',\n                'risk': 'Low'\n            },\n            {\n                'phase': 2,\n                'name': 'Body Domain Migration',\n                'duration_months': 24,\n                'zones_added': ['RL', 'RR', 'FC', 'RC'],\n                'functions_migrated': ['All body', 'HVAC', 'Doors'],\n                'cable_reduction': '45%',\n                'cost': '$5M NRE',\n                'risk': 'Medium'\n            },\n            {\n                'phase': 3,\n                'name': 'Full Zonal',\n                'duration_months': 36,\n                'zones_added': ['LC', 'RC'],\n                'functions_migrated': ['All functions'],\n                'cable_reduction': '60%',\n                'cost': '$8M NRE',\n                'risk': 'High',\n                'payback': '2.5 years at 100k units\u002Fyear'\n            }\n        ]\n\n        return phases\n```\n\n## ROI Calculation\n\n**Per-Vehicle Savings:**\n```\nCable harness reduction: $250\nWeight reduction (fuel economy): $50\u002Fvehicle lifetime\nAssembly time reduction: $100\nService diagnostics improvement: $30\n\nTotal savings: $430 per vehicle\n```\n\n**NRE Investment:**\n```\nZone controller development: $3M\nSoftware architecture: $2M\nTesting & validation: $2M\nProduction tooling: $1M\n\nTotal NRE: $8M\n```\n\n**Payback Period:**\n```\nAt 50,000 units\u002Fyear:\n$8M \u002F ($430 × 50,000) = 0.37 years (4.5 months)\n\nAt 100,000 units\u002Fyear:\nImmediate positive ROI\n```\n\n## Best Practices\n\n1. **Start with body domain** - Lowest safety criticality, highest cable savings\n2. **Use star topology** for safety-critical zones\n3. **Implement intelligent power management** - Load shedding, priority-based\n4. **Plan for redundancy** - Dual Ethernet links to gateway\n5. **Use TSN** for deterministic latency (\u003C10ms p99)\n6. **Leverage 10BASE-T1S** for low-cost sensors (multidrop)\n7. **Plan thermal management** - Zone controllers generate more heat than distributed ECUs\n\n## Tools & Frameworks\n\n- **Capital Harness Designer** - Cable routing and optimization\n- **PREEvision** - E\u002FE architecture design\n- **SystemDesk** - AUTOSAR Adaptive configuration\n- **Vector CANoe** - Network simulation and testing\n\n## References\n\n- VDA Recommendation on Zonal E\u002FE Architecture\n- IEEE 802.1 TSN Standards\n- AUTOSAR Adaptive Platform R22-11\n- SAE J3161 On-Board Ethernet Communication\n\n---\n\n## Zone Controller Development\n\n# Zone Controller Development\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in developing zone controller firmware and software for next-generation zonal E\u002FE architectures. Covers hardware platforms (NXP S32K3, Renesas RH850, Infineon AURIX), I\u002FO handling, sensor aggregation, actuator control, gateway functions, and AUTOSAR integration.\n\n## Core Competencies\n\n### 1. Zone Controller Hardware Platforms\n\n#### NXP S32K3 (Entry to Mid-Range)\n\n**S32K344 Specifications:**\n```c\n\u002F\u002F NXP S32K344 - Low-cost zone controller\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F ARM Cortex-M7\n        uint32_t frequency_mhz; \u002F\u002F 160 MHz\n        uint8_t cores;          \u002F\u002F 1\n        bool lockstep;          \u002F\u002F No (QM)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 4096 KB\n        uint32_t ram_kb;        \u002F\u002F 512 KB\n        bool ecc;               \u002F\u002F Optional\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 6x CAN-FD\n        uint8_t lin;            \u002F\u002F 3x LIN\n        uint8_t ethernet_100m;  \u002F\u002F 1x 100BASE-T1\n        uint8_t spi;            \u002F\u002F 4x SPI\n        uint8_t i2c;            \u002F\u002F 2x I2C\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 3x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 32x eMIOS PWM\n        uint8_t gpio;           \u002F\u002F 144 GPIO\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-B capable\n    float cost_usd;             \u002F\u002F $18-22\n} S32K344_Spec_t;\n```\n\n**Use Cases:**\n- Corner zones (FL, FR, RL, RR)\n- Lighting control\n- Window\u002Fmirror control\n- Low-complexity body functions\n\n#### Renesas RH850\u002FU2A (Mid-Range)\n\n**RH850\u002FU2A8 Specifications:**\n```c\n\u002F\u002F Renesas RH850\u002FU2A8 - Standard zone controller\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F RH850 G4MH\n        uint32_t frequency_mhz; \u002F\u002F 320 MHz\n        uint8_t cores;          \u002F\u002F 2 (lockstep option)\n        bool lockstep;          \u002F\u002F Yes (ASIL-D)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 8192 KB\n        uint32_t ram_kb;        \u002F\u002F 1024 KB\n        bool ecc;               \u002F\u002F Yes\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 8x CAN-FD\n        uint8_t lin;            \u002F\u002F 8x LIN\n        uint8_t ethernet_100m;  \u002F\u002F 2x 100BASE-T1\n        uint8_t flexray;        \u002F\u002F 2x FlexRay\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 4x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 48x PWM\n        uint8_t gpio;           \u002F\u002F 200+ GPIO\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-D\n    float cost_usd;             \u002F\u002F $28-35\n} RH850_U2A8_Spec_t;\n```\n\n**Use Cases:**\n- Front-center zone (HVAC, wipers)\n- Rear-center zone (trunk, tailgate)\n- Body domain consolidation\n- HVAC control\n\n#### Infineon AURIX TC397 (High-Performance)\n\n**TC397 Specifications:**\n```c\n\u002F\u002F Infineon AURIX TC397 - High-performance safety zone\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F TriCore 1.8\n        uint32_t frequency_mhz; \u002F\u002F 300 MHz\n        uint8_t cores;          \u002F\u002F 3 lockstep pairs (6 total)\n        bool lockstep;          \u002F\u002F Yes (all cores)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 16384 KB\n        uint32_t ram_kb;        \u002F\u002F 1536 KB\n        bool ecc;               \u002F\u002F Yes (all memories)\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 12x CAN-FD\n        uint8_t lin;            \u002F\u002F 4x LIN\n        uint8_t ethernet_1g;    \u002F\u002F 1x 1000BASE-T1\n        uint8_t flexray;        \u002F\u002F 2x FlexRay\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 8x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 64x GTM PWM\n        uint8_t gpio;           \u002F\u002F 300+ GPIO\n        bool hss_drivers;       \u002F\u002F High-side switches\n        bool lss_drivers;       \u002F\u002F Low-side switches\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-D\n    float cost_usd;             \u002F\u002F $65-90\n} TC397_Spec_t;\n```\n\n**Use Cases:**\n- Gateway\u002Fcentral controller\n- Safety-critical zones\n- ADAS integration point\n- Complex control algorithms\n\n### 2. Zone Controller Firmware Architecture\n\n```c\n\u002F\u002F Zone Controller Application Structure\ntypedef struct {\n    char zone_id[16];           \u002F\u002F \"FL_ZONE\", \"FR_ZONE\", etc.\n    uint8_t hardware_platform;  \u002F\u002F S32K3, RH850, AURIX\n    uint8_t asil_rating;        \u002F\u002F QM, ASIL-A\u002FB\u002FC\u002FD\n\n    \u002F\u002F I\u002FO Configuration\n    struct {\n        uint8_t num_digital_inputs;\n        uint8_t num_digital_outputs;\n        uint8_t num_analog_inputs;\n        uint8_t num_pwm_outputs;\n        uint8_t num_lin_slaves;\n    } io_config;\n\n    \u002F\u002F Communication\n    struct {\n        bool ethernet_enabled;\n        uint8_t can_channels;\n        uint8_t lin_channels;\n        uint16_t someip_port;\n    } comm_config;\n\n    \u002F\u002F Functions\n    void (*init)(void);\n    void (*cyclic_10ms)(void);\n    void (*cyclic_100ms)(void);\n    void (*handle_ethernet_rx)(uint8_t* data, uint16_t len);\n    void (*handle_lin_frame)(uint8_t node, uint8_t* data);\n} ZoneController_t;\n\n\u002F\u002F Example: Front-Left Zone Controller\nZoneController_t fl_zone = {\n    .zone_id = \"FL_ZONE\",\n    .hardware_platform = HW_S32K344,\n    .asil_rating = ASIL_B,\n\n    .io_config = {\n        .num_digital_inputs = 20,   \u002F\u002F Door switches, buttons\n        .num_digital_outputs = 12,  \u002F\u002F Relays, LEDs\n        .num_analog_inputs = 4,     \u002F\u002F Temperature sensors\n        .num_pwm_outputs = 8,       \u002F\u002F Headlight dimming, motor control\n        .num_lin_slaves = 4         \u002F\u002F Window motor, mirror motors\n    },\n\n    .comm_config = {\n        .ethernet_enabled = true,\n        .can_channels = 2,          \u002F\u002F CAN1: vehicle bus, CAN2: diagnostics\n        .lin_channels = 2,          \u002F\u002F LIN1: windows, LIN2: mirrors\n        .someip_port = 30500\n    },\n\n    .init = FL_Zone_Init,\n    .cyclic_10ms = FL_Zone_Cyclic10ms,\n    .cyclic_100ms = FL_Zone_Cyclic100ms,\n    .handle_ethernet_rx = FL_Zone_EthernetRx,\n    .handle_lin_frame = FL_Zone_LinRx\n};\n```\n\n### 3. Sensor Aggregation\n\n```c\n\u002F\u002F Sensor Aggregation for Zone Controller\ntypedef struct {\n    uint32_t timestamp_ms;\n    float value;\n    uint8_t quality;  \u002F\u002F 0=Invalid, 1=Questionable, 2=Good, 3=Excellent\n    uint8_t source;   \u002F\u002F Sensor ID\n} SensorValue_t;\n\ntypedef struct {\n    char sensor_name[32];\n    uint8_t num_sources;        \u002F\u002F Number of redundant sensors\n    SensorValue_t values[4];    \u002F\u002F Up to 4 redundant sources\n    float fused_value;          \u002F\u002F Fused result\n    uint8_t fusion_algorithm;   \u002F\u002F AVERAGE, MEDIAN, VOTER, KALMAN\n} SensorAggregator_t;\n\n\u002F\u002F Sensor fusion algorithms\nfloat sensor_fusion_average(SensorAggregator_t* agg) {\n    float sum = 0.0;\n    uint8_t count = 0;\n\n    for (uint8_t i = 0; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality >= 2) {  \u002F\u002F Good or Excellent\n            sum += agg->values[i].value;\n            count++;\n        }\n    }\n\n    return (count > 0) ? (sum \u002F count) : 0.0;\n}\n\nfloat sensor_fusion_median(SensorAggregator_t* agg) {\n    float sorted[4];\n    uint8_t count = 0;\n\n    \u002F\u002F Copy valid values\n    for (uint8_t i = 0; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality >= 2) {\n            sorted[count++] = agg->values[i].value;\n        }\n    }\n\n    if (count == 0) return 0.0;\n\n    \u002F\u002F Bubble sort\n    for (uint8_t i = 0; i \u003C count - 1; i++) {\n        for (uint8_t j = 0; j \u003C count - i - 1; j++) {\n            if (sorted[j] > sorted[j + 1]) {\n                float temp = sorted[j];\n                sorted[j] = sorted[j + 1];\n                sorted[j + 1] = temp;\n            }\n        }\n    }\n\n    \u002F\u002F Return median\n    if (count % 2 == 0) {\n        return (sorted[count \u002F 2 - 1] + sorted[count \u002F 2]) \u002F 2.0;\n    } else {\n        return sorted[count \u002F 2];\n    }\n}\n\n\u002F\u002F 2-out-of-3 voter\nfloat sensor_fusion_voter(SensorAggregator_t* agg) {\n    if (agg->num_sources \u003C 2) return agg->values[0].value;\n\n    \u002F\u002F Check if any two sensors agree within tolerance\n    const float tolerance = 0.05;  \u002F\u002F 5% tolerance\n\n    for (uint8_t i = 0; i \u003C agg->num_sources - 1; i++) {\n        for (uint8_t j = i + 1; j \u003C agg->num_sources; j++) {\n            float diff = fabs(agg->values[i].value - agg->values[j].value);\n            float avg = (agg->values[i].value + agg->values[j].value) \u002F 2.0;\n\n            if (diff \u002F avg \u003C tolerance) {\n                return avg;  \u002F\u002F Two sensors agree\n            }\n        }\n    }\n\n    \u002F\u002F No agreement - use sensor with best quality\n    uint8_t best_idx = 0;\n    for (uint8_t i = 1; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality > agg->values[best_idx].quality) {\n            best_idx = i;\n        }\n    }\n\n    return agg->values[best_idx].value;\n}\n\n\u002F\u002F Example: Temperature sensor aggregation\nSensorAggregator_t temp_sensor = {\n    .sensor_name = \"AmbientTemperature\",\n    .num_sources = 3,\n    .values = {\n        {.timestamp_ms = 1000, .value = 23.5, .quality = 3, .source = 1},\n        {.timestamp_ms = 1000, .value = 23.7, .quality = 3, .source = 2},\n        {.timestamp_ms = 1000, .value = 23.6, .quality = 2, .source = 3}\n    },\n    .fusion_algorithm = FUSION_MEDIAN\n};\n\n\u002F\u002F Perform fusion\ntemp_sensor.fused_value = sensor_fusion_median(&temp_sensor);\n\u002F\u002F Result: 23.6°C\n```\n\n### 4. Actuator Control\n\n```c\n\u002F\u002F PWM-based actuator control (e.g., headlight dimming)\ntypedef struct {\n    char actuator_name[32];\n    uint8_t pwm_channel;\n    uint16_t frequency_hz;      \u002F\u002F PWM frequency\n    uint8_t duty_cycle;         \u002F\u002F 0-100%\n    bool enabled;\n} PWM_Actuator_t;\n\nvoid set_headlight_brightness(PWM_Actuator_t* headlight, uint8_t brightness_pct) {\n    \u002F\u002F Limit to valid range\n    if (brightness_pct > 100) brightness_pct = 100;\n\n    headlight->duty_cycle = brightness_pct;\n\n    \u002F\u002F Update hardware PWM register (example for S32K3)\n    eMIOS_SetDutyCycle(headlight->pwm_channel, brightness_pct);\n}\n\n\u002F\u002F LIN-based actuator control (e.g., window motor)\ntypedef struct {\n    uint8_t lin_channel;\n    uint8_t node_address;\n    enum {\n        WINDOW_STOP = 0,\n        WINDOW_UP = 1,\n        WINDOW_DOWN = 2\n    } command;\n    uint8_t position_pct;       \u002F\u002F 0=closed, 100=fully open\n} LIN_WindowMotor_t;\n\nvoid control_window(LIN_WindowMotor_t* window, uint8_t target_position) {\n    uint8_t lin_frame[8];\n\n    \u002F\u002F Build LIN frame\n    lin_frame[0] = window->node_address;\n    lin_frame[1] = (target_position > window->position_pct) ? WINDOW_UP : WINDOW_DOWN;\n    lin_frame[2] = target_position;\n\n    \u002F\u002F Send LIN frame\n    LIN_SendFrame(window->lin_channel, lin_frame, 3);\n\n    \u002F\u002F Update state\n    window->position_pct = target_position;\n}\n```\n\n### 5. Gateway Functions\n\n```c\n\u002F\u002F Gateway functionality (message routing, filtering, security)\ntypedef struct {\n    uint8_t src_network;    \u002F\u002F CAN, LIN, Ethernet\n    uint8_t dst_network;\n    uint32_t msg_id;        \u002F\u002F CAN ID or SOME\u002FIP service ID\n    bool translate;         \u002F\u002F Needs translation (CAN\u003C->Ethernet)\n    bool secure;            \u002F\u002F Requires MACsec\u002Fauthentication\n} GatewayRoute_t;\n\n\u002F\u002F Routing table\nGatewayRoute_t routing_table[] = {\n    \u002F\u002F CAN → Ethernet\n    {.src_network = NET_CAN1, .dst_network = NET_ETH, .msg_id = 0x123, .translate = true, .secure = false},\n    \u002F\u002F Ethernet → CAN\n    {.src_network = NET_ETH, .dst_network = NET_CAN2, .msg_id = 0x12340001, .translate = true, .secure = true},\n    \u002F\u002F LIN → Ethernet\n    {.src_network = NET_LIN1, .dst_network = NET_ETH, .msg_id = 0x3C, .translate = true, .secure = false}\n};\n\nvoid gateway_route_message(uint8_t src_net, uint32_t msg_id, uint8_t* data, uint16_t len) {\n    \u002F\u002F Find routing rule\n    for (uint8_t i = 0; i \u003C sizeof(routing_table) \u002F sizeof(GatewayRoute_t); i++) {\n        if (routing_table[i].src_network == src_net &&\n            routing_table[i].msg_id == msg_id) {\n\n            if (routing_table[i].translate) {\n                \u002F\u002F Translate message format\n                if (src_net == NET_CAN1 && routing_table[i].dst_network == NET_ETH) {\n                    translate_can_to_someip(msg_id, data, len);\n                } else if (src_net == NET_ETH && routing_table[i].dst_network == NET_CAN1) {\n                    translate_someip_to_can(msg_id, data, len);\n                }\n            }\n\n            if (routing_table[i].secure) {\n                \u002F\u002F Apply security (MACsec, authentication)\n                apply_security(data, len);\n            }\n\n            \u002F\u002F Forward to destination network\n            forward_message(routing_table[i].dst_network, data, len);\n            break;\n        }\n    }\n}\n```\n\n### 6. AUTOSAR Integration\n\n```c\n\u002F\u002F AUTOSAR Classic BSW configuration for zone controller\n\u002F\u002F RTE (Runtime Environment) configuration\n\n\u002F\u002F Sender-Receiver Interface\nRte_Write_HeadlightBrightness(uint8_t brightness) {\n    \u002F\u002F Implemented by RTE generator\n    \u002F\u002F Routes to SOME\u002FIP or CAN\n}\n\nRte_Read_DoorStatus(boolean* isOpen) {\n    \u002F\u002F Read from sensor via RTE\n    *isOpen = gpio_read(DOOR_SWITCH_PIN);\n    return RTE_E_OK;\n}\n\n\u002F\u002F Cyclic runnable (10ms task)\nvoid Zone_Controller_10ms_Runnable(void) {\n    boolean door_open;\n    uint8_t brightness;\n\n    \u002F\u002F Read inputs\n    Rte_Read_DoorStatus(&door_open);\n\n    \u002F\u002F Control logic\n    if (door_open) {\n        brightness = 100;  \u002F\u002F Full brightness when door open\n    } else {\n        brightness = get_adaptive_brightness();  \u002F\u002F Adaptive based on ambient light\n    }\n\n    \u002F\u002F Write outputs\n    Rte_Write_HeadlightBrightness(brightness);\n}\n```\n\n## Performance Targets\n\n| Function | Cycle Time | CPU Load | Memory |\n|----------|-----------|----------|--------|\n| I\u002FO scan | 10 ms | \u003C5% | 10 KB |\n| Sensor aggregation | 100 ms | \u003C10% | 20 KB |\n| Gateway routing | \u003C1 ms | \u003C15% | 50 KB |\n| SOME\u002FIP handling | Event-driven | \u003C20% | 100 KB |\n| Safety monitoring | 10 ms | \u003C10% | 30 KB |\n\n## Tools & Development Environment\n\n- **NXP S32 Design Studio** - IDE for S32K3 development\n- **Renesas CS+ \u002F e² studio** - IDE for RH850 development\n- **Infineon AURIX Development Studio** - IDE for TC397\n- **Vector DaVinci Configurator** - AUTOSAR BSW configuration\n- **EB tresos Studio** - AUTOSAR configuration (Elektrobit)\n- **PCAN-View** - CAN\u002FLIN debugging\n- **Wireshark** - Ethernet debugging\n\n## References\n\n- NXP S32K3 Reference Manual\n- Renesas RH850\u002FU2A User's Manual\n- Infineon AURIX TC3xx User Manual\n- AUTOSAR Adaptive Platform R22-11\n- LIN Specification 2.2A\n","# Automotive Zonal\n\n## Automotive Ethernet\n\n# Automotive Ethernet - TSN & AVB\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in automotive Ethernet technologies including Time-Sensitive Networking (TSN), Audio Video Bridging (AVB), physical layer standards (100BASE-T1, 1000BASE-T1), switch configuration, VLAN management, and Quality of Service (QoS) for deterministic vehicle networks.\n\n## Core Competencies\n\n### 1. Physical Layer Standards\n\n#### 100BASE-T1 (IEEE 802.3bw)\n```c\n\u002F\u002F 100BASE-T1 PHY Configuration\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3bw\n    uint16_t data_rate_mbps;    \u002F\u002F 100 Mbps full-duplex\n    uint8_t wire_pairs;         \u002F\u002F 1 twisted pair\n    uint16_t max_length_m;      \u002F\u002F 15 meters (typ), 40m (max)\n    float voltage_p2p;          \u002F\u002F 2.4V peak-to-peak\n    uint8_t encoding;           \u002F\u002F PAM3 (3-level)\n    bool pma_master;            \u002F\u002F Master\u002FSlave negotiation\n} BASE100_T1_Config;\n\n\u002F\u002F Example configuration for zone controller\nBASE100_T1_Config zcu_phy = {\n    .standard = IEEE_802_3bw,\n    .data_rate_mbps = 100,\n    .wire_pairs = 1,\n    .max_length_m = 15,\n    .voltage_p2p = 2.4,\n    .encoding = PAM3,\n    .pma_master = true  \u002F\u002F Zone controller is master\n};\n```\n\n#### 1000BASE-T1 (IEEE 802.3bp)\n```c\n\u002F\u002F 1000BASE-T1 PHY Configuration (for cameras, ADAS)\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3bp\n    uint16_t data_rate_mbps;    \u002F\u002F 1000 Mbps full-duplex\n    uint8_t wire_pairs;         \u002F\u002F 1 unshielded twisted pair\n    uint16_t max_length_m;      \u002F\u002F 15m (standard), 40m (extended)\n    uint8_t encoding;           \u002F\u002F PAM3\n    bool automotive_grade;      \u002F\u002F AEC-Q100 qualified\n    float temp_range[2];        \u002F\u002F -40°C to +125°C\n} BASE1000_T1_Config;\n\n\u002F\u002F Camera link configuration\nBASE1000_T1_Config camera_phy = {\n    .standard = IEEE_802_3bp,\n    .data_rate_mbps = 1000,\n    .wire_pairs = 1,\n    .max_length_m = 15,\n    .encoding = PAM3,\n    .automotive_grade = true,\n    .temp_range = {-40.0, 125.0}\n};\n```\n\n#### 10BASE-T1S (IEEE 802.3cg) - Multidrop Bus\n```c\n\u002F\u002F 10BASE-T1S for low-cost sensor networks\ntypedef struct {\n    uint8_t standard;           \u002F\u002F IEEE 802.3cg\n    uint16_t data_rate_mbps;    \u002F\u002F 10 Mbps half-duplex\n    uint8_t topology;           \u002F\u002F Multidrop bus\n    uint8_t max_nodes;          \u002F\u002F 8 nodes per segment\n    uint16_t max_length_m;      \u002F\u002F 25 meters\n    uint8_t collision_detection; \u002F\u002F CSMA\u002FCD\n    bool plca_mode;             \u002F\u002F Physical Layer Collision Avoidance\n} BASE10_T1S_Config;\n\n\u002F\u002F Sensor bus configuration\nBASE10_T1S_Config sensor_bus = {\n    .standard = IEEE_802_3cg,\n    .data_rate_mbps = 10,\n    .topology = MULTIDROP_BUS,\n    .max_nodes = 8,\n    .max_length_m = 25,\n    .collision_detection = CSMA_CD,\n    .plca_mode = true  \u002F\u002F Enables deterministic access\n};\n```\n\n### 2. Time-Sensitive Networking (TSN)\n\n#### IEEE 802.1 TSN Standards\n\n**Key Standards:**\n- **802.1AS** - Precision Time Protocol (gPTP) for time synchronization\n- **802.1Qbv** - Time-Aware Shaper (TAS) for scheduled traffic\n- **802.1Qav** - Credit-Based Shaper (CBS) for AVB streams\n- **802.1Qbu** - Frame Preemption for low-latency\n- **802.1Qci** - Per-Stream Filtering and Policing\n- **802.1CB** - Frame Replication and Elimination for Reliability (FRER)\n\n```python\n# TSN Configuration Example\nclass TSNSwitchConfig:\n    def __init__(self):\n        self.gptp_domain = 0  # Time domain for sync\n        self.sync_interval_ms = 125  # gPTP sync every 125ms\n        self.time_aware_shaper = True\n        self.frame_preemption = True\n        self.stream_reservation = True\n\n    def configure_tas_schedule(self):\n        \"\"\"\n        Configure Time-Aware Shaper (802.1Qbv) for deterministic scheduling.\n        Divides time into repeating cycles with gates for each priority queue.\n        \"\"\"\n\n        # 1ms cycle time (1,000,000 ns)\n        cycle_time_ns = 1_000_000\n\n        schedule = {\n            'cycle_time_ns': cycle_time_ns,\n            'gates': [\n                # Time slot 0-100μs: Priority 7 (Safety-critical)\n                {\n                    'start_ns': 0,\n                    'duration_ns': 100_000,\n                    'open_gates': [7],  # Only priority 7 queue open\n                    'traffic_class': 'Safety'\n                },\n                # Time slot 100-300μs: Priority 6 (ADAS)\n                {\n                    'start_ns': 100_000,\n                    'duration_ns': 200_000,\n                    'open_gates': [6],\n                    'traffic_class': 'Control'\n                },\n                # Time slot 300-800μs: Priority 4-5 (Video streams)\n                {\n                    'start_ns': 300_000,\n                    'duration_ns': 500_000,\n                    'open_gates': [4, 5],\n                    'traffic_class': 'AVB'\n                },\n                # Time slot 800-1000μs: Priority 0-3 (Best effort)\n                {\n                    'start_ns': 800_000,\n                    'duration_ns': 200_000,\n                    'open_gates': [0, 1, 2, 3],\n                    'traffic_class': 'BestEffort'\n                }\n            ]\n        }\n\n        return schedule\n\n    def configure_stream_reservation(self, stream_id, bandwidth_mbps, latency_us):\n        \"\"\"\n        Configure stream reservation for AVB\u002FTSN streams (802.1Qat\u002FQcc).\n\n        Args:\n            stream_id: Unique stream identifier\n            bandwidth_mbps: Required bandwidth in Mbps\n            latency_us: Maximum latency in microseconds\n        \"\"\"\n\n        stream_config = {\n            'stream_id': stream_id,\n            'talker_mac': '00:11:22:33:44:55',\n            'listener_mac': ['00:11:22:33:44:66'],\n            'vlan_id': 100,\n            'priority': 6,  # SR Class A\n            'max_frame_size': 1522,\n            'max_interval_frames': 1,\n            'bandwidth_mbps': bandwidth_mbps,\n            'max_latency_us': latency_us,\n            'redundancy': 'FRER'  # Frame Replication\n        }\n\n        return stream_config\n```\n\n#### gPTP Time Synchronization (802.1AS)\n\n```c\n\u002F\u002F gPTP Time Synchronization Configuration\ntypedef struct {\n    uint8_t domain_number;           \u002F\u002F 0 for automotive\n    uint32_t sync_interval_ns;       \u002F\u002F 125ms = 125,000,000 ns\n    uint32_t pdelay_interval_ns;     \u002F\u002F Peer delay measurement\n    int8_t clock_class;              \u002F\u002F 248 for automotive grandmaster\n    int8_t clock_accuracy;           \u002F\u002F 0xFE (unknown)\n    uint16_t offset_scaled_log_var;  \u002F\u002F Variance of clock\n    uint8_t priority1;               \u002F\u002F 248\n    uint8_t priority2;               \u002F\u002F 248\n    bool as_capable;                 \u002F\u002F TSN-capable port\n} gPTP_Config_t;\n\n\u002F\u002F Grandmaster clock (gateway)\ngPTP_Config_t grandmaster = {\n    .domain_number = 0,\n    .sync_interval_ns = 125000000,  \u002F\u002F 125ms\n    .pdelay_interval_ns = 1000000000,  \u002F\u002F 1 second\n    .clock_class = 248,  \u002F\u002F Automotive default application-specific\n    .clock_accuracy = 0xFE,\n    .offset_scaled_log_var = 0x4E5D,\n    .priority1 = 248,\n    .priority2 = 248,\n    .as_capable = true\n};\n\n\u002F\u002F Typical time sync accuracy: ±500ns between nodes\n```\n\n### 3. VLAN Configuration\n\n```python\nclass VLANManager:\n    \"\"\"\n    Manage VLANs for traffic segregation in zonal architecture.\n    \"\"\"\n\n    def __init__(self):\n        self.vlans = {\n            100: {'name': 'Safety', 'priority': 7, 'color': 'RED'},\n            200: {'name': 'ADAS', 'priority': 6, 'color': 'ORANGE'},\n            300: {'name': 'Infotainment', 'priority': 5, 'color': 'YELLOW'},\n            400: {'name': 'Body', 'priority': 4, 'color': 'GREEN'},\n            500: {'name': 'Diagnostics', 'priority': 3, 'color': 'BLUE'},\n            999: {'name': 'Management', 'priority': 7, 'color': 'PURPLE'}\n        }\n\n    def configure_switch_ports(self):\n        \"\"\"\n        Configure switch ports with VLAN memberships.\n        \"\"\"\n\n        port_config = {\n            'port_1': {  # Gateway uplink\n                'mode': 'trunk',\n                'allowed_vlans': [100, 200, 300, 400, 500, 999],\n                'native_vlan': 999,\n                'pvid': 999\n            },\n            'port_2': {  # Front-left ZCU\n                'mode': 'trunk',\n                'allowed_vlans': [100, 400],  # Safety + Body\n                'native_vlan': 400,\n                'pvid': 400\n            },\n            'port_3': {  # Front camera (ADAS)\n                'mode': 'access',\n                'vlan': 200,  # ADAS VLAN only\n                'pvid': 200\n            },\n            'port_4': {  # Rear camera (infotainment)\n                'mode': 'access',\n                'vlan': 300,  # Infotainment VLAN\n                'pvid': 300\n            },\n            'port_5': {  # Diagnostic connector (OBD-II)\n                'mode': 'access',\n                'vlan': 500,\n                'pvid': 500\n            }\n        }\n\n        return port_config\n```\n\n### 4. Quality of Service (QoS)\n\n#### Priority Mapping (IEEE 802.1Q)\n\n```c\n\u002F\u002F 8 priority levels (0-7)\ntypedef enum {\n    PRIORITY_0_BEST_EFFORT = 0,     \u002F\u002F Background\n    PRIORITY_1_BACKGROUND = 1,      \u002F\u002F Backup data\n    PRIORITY_2_EXCELLENT_EFFORT = 2, \u002F\u002F Business-critical\n    PRIORITY_3_CRITICAL_APPS = 3,    \u002F\u002F Call signaling\n    PRIORITY_4_VIDEO = 4,            \u002F\u002F Streaming video\n    PRIORITY_5_VOICE = 5,            \u002F\u002F Interactive voice\u002Fvideo\n    PRIORITY_6_CONTROL = 6,          \u002F\u002F Control plane (ADAS)\n    PRIORITY_7_NETWORK_CONTROL = 7   \u002F\u002F Safety-critical\n} EthernetPriority_t;\n\n\u002F\u002F Traffic class mapping\ntypedef struct {\n    EthernetPriority_t priority;\n    uint8_t traffic_class;\n    uint16_t max_latency_us;\n    char description[32];\n} QoS_Mapping_t;\n\nQoS_Mapping_t qos_table[] = {\n    {PRIORITY_7_NETWORK_CONTROL, 7, 100, \"Safety (ABS, ESC)\"},\n    {PRIORITY_6_CONTROL, 6, 500, \"ADAS (Braking, Steering)\"},\n    {PRIORITY_5_VOICE, 5, 2000, \"Camera streams\"},\n    {PRIORITY_4_VIDEO, 4, 10000, \"Infotainment video\"},\n    {PRIORITY_3_CRITICAL_APPS, 3, 20000, \"Diagnostics\"},\n    {PRIORITY_2_EXCELLENT_EFFORT, 2, 50000, \"SW updates\"},\n    {PRIORITY_1_BACKGROUND, 1, 100000, \"Telemetry\"},\n    {PRIORITY_0_BEST_EFFORT, 0, 1000000, \"General data\"}\n};\n```\n\n#### Credit-Based Shaper (802.1Qav)\n\n```python\ndef configure_cbs(port, stream_class):\n    \"\"\"\n    Configure Credit-Based Shaper for AVB traffic (SR Class A\u002FB).\n\n    Args:\n        port: Ethernet port number\n        stream_class: 'A' for Class A (2ms), 'B' for Class B (50ms)\n    \"\"\"\n\n    if stream_class == 'A':\n        config = {\n            'idle_slope': 0x3FFF,      # 75% of link bandwidth\n            'send_slope': -0x2AAA,     # -25% of link bandwidth\n            'hi_credit': 0x186A0,      # 100,000 credits\n            'lo_credit': -0x186A0,     # -100,000 credits\n            'priority': 6\n        }\n    elif stream_class == 'B':\n        config = {\n            'idle_slope': 0x1FFF,      # 50% of link bandwidth\n            'send_slope': -0x1FFF,     # -50% of link bandwidth\n            'hi_credit': 0xC350,       # 50,000 credits\n            'lo_credit': -0xC350,      # -50,000 credits\n            'priority': 5\n        }\n\n    return config\n```\n\n### 5. Automotive Ethernet Switch Configuration\n\n```yaml\n# Example switch configuration (YAML)\nswitch:\n  model: \"NXP SJA1110\"\n  ports: 10\n  tsn_capable: true\n\n  global_config:\n    gptp_domain: 0\n    management_vlan: 999\n\n  port_1:  # Uplink to gateway\n    speed: \"1000BASE-T1\"\n    mode: \"trunk\"\n    vlans: [100, 200, 300, 400, 500, 999]\n    tsn:\n      tas_enabled: true\n      frame_preemption: true\n\n  port_2:  # Front-left zone controller\n    speed: \"100BASE-T1\"\n    mode: \"trunk\"\n    vlans: [100, 400]\n    tsn:\n      tas_enabled: true\n\n  port_3:  # Front camera\n    speed: \"1000BASE-T1\"\n    mode: \"access\"\n    vlan: 200\n    qos:\n      priority: 6\n      cbs_enabled: true\n      stream_reservation: true\n\n  port_4:  # Rear camera\n    speed: \"1000BASE-T1\"\n    mode: \"access\"\n    vlan: 200\n    qos:\n      priority: 6\n      cbs_enabled: true\n```\n\n## Network Performance Targets\n\n| Traffic Type | Priority | Max Latency | Jitter | Packet Loss |\n|--------------|----------|-------------|--------|-------------|\n| Safety (ABS, ESC) | 7 | \u003C100 μs | \u003C10 μs | 0% |\n| ADAS Control | 6 | \u003C500 μs | \u003C50 μs | \u003C10^-9 |\n| Camera Streams | 5-6 | \u003C2 ms | \u003C100 μs | \u003C10^-6 |\n| Infotainment | 4 | \u003C10 ms | \u003C1 ms | \u003C10^-4 |\n| Diagnostics | 3 | \u003C50 ms | N\u002FA | \u003C10^-3 |\n| Best Effort | 0-2 | \u003C1 s | N\u002FA | \u003C10^-2 |\n\n## Tools & Testing\n\n**Network Analyzers:**\n- **Vector VN5600** - TSN-capable network interface\n- **Wireshark with Automotive plugins** - Packet capture and analysis\n- **Ixia\u002FKeysight IxNetwork** - TSN traffic generation and testing\n\n**Configuration Tools:**\n- **NXP SJA1110 Config Tool** - Switch configuration\n- **Vector CANoe.Ethernet** - Network simulation\n- **Marvell TSN Studio** - TSN stream configuration\n\n## References\n\n- IEEE 802.1 TSN Task Group Standards\n- SAE J3161 On-Board Ethernet Communication\n- OPEN Alliance BroadR-Reach Specification\n- AUTOSAR Ethernet Communication Specification\n\n---\n\n## Network Security Zonal\n\n# Network Security for Zonal Architecture\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in securing automotive Ethernet networks in zonal architectures. Covers MACsec (IEEE 802.1AE), IPsec, firewall rules for zone controllers, intrusion detection systems (IDS), secure gateway design, and IDPS deployment for vehicle networks.\n\n## Core Competencies\n\n### 1. MACsec (IEEE 802.1AE) - Layer 2 Encryption\n\n```c\n\u002F\u002F MACsec Configuration for Automotive Ethernet\ntypedef struct {\n    uint8_t enabled;\n    uint8_t cipher_suite;       \u002F\u002F AES-GCM-128 or AES-GCM-256\n    uint8_t confidentiality;    \u002F\u002F Encrypt payload\n    uint8_t integrity;          \u002F\u002F ICV (Integrity Check Value)\n    uint32_t pn;                \u002F\u002F Packet Number (anti-replay)\n    uint8_t key[32];            \u002F\u002F 128-bit or 256-bit key\n    uint8_t sci[8];             \u002F\u002F Secure Channel Identifier\n} MACSec_Config_t;\n\n\u002F\u002F Example: MACsec between gateway and zone controller\nMACSec_Config_t macsec_link = {\n    .enabled = 1,\n    .cipher_suite = AES_GCM_256,\n    .confidentiality = 1,       \u002F\u002F Encrypt\n    .integrity = 1,             \u002F\u002F 16-byte ICV\n    .pn = 0x00000001,          \u002F\u002F Initial packet number\n    .key = {0x2b, 0x7e, 0x15, ...},  \u002F\u002F 256-bit key from key management\n    .sci = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}\n};\n```\n\n**MACsec Frame Structure:**\n```\n┌──────────────────────────────────────────────┐\n│ Ethernet Header (14 bytes)                   │\n├──────────────────────────────────────────────┤\n│ SecTAG (8 bytes)                             │\n│  - TCI\u002FAN (1 byte): Version, encrypted flag │\n│  - SL (1 byte): Short Length                │\n│  - PN (4 bytes): Packet Number              │\n│  - SCI (8 bytes): Secure Channel ID         │\n├──────────────────────────────────────────────┤\n│ Encrypted Payload                            │\n├──────────────────────────────────────────────┤\n│ ICV (16 bytes): Integrity Check Value        │\n└──────────────────────────────────────────────┘\n```\n\n**Performance Impact:**\n- Latency overhead: ~100-200 μs\n- Throughput reduction: ~5-10% (due to encryption)\n- CPU overhead: ~15% on zone controller\n\n### 2. IPsec for End-to-End Security\n\n```python\nclass IPsecTunnel:\n    \"\"\"\n    IPsec tunnel configuration for secure SOME\u002FIP communication.\n    \"\"\"\n\n    def __init__(self):\n        self.mode = 'ESP'  # Encapsulating Security Payload\n        self.encryption = 'AES-256-CBC'\n        self.authentication = 'HMAC-SHA256'\n        self.pfs = True  # Perfect Forward Secrecy\n\n    def configure_tunnel(self, local_ip, remote_ip):\n        \"\"\"\n        Configure IPsec tunnel between two ECUs.\n\n        Args:\n            local_ip: Local zone controller IP\n            remote_ip: Remote zone controller\u002Fgateway IP\n        \"\"\"\n\n        config = {\n            'src': local_ip,\n            'dst': remote_ip,\n            'protocol': 'ESP',  # ESP for encryption + auth\n            'spi': 0x1234,  # Security Parameter Index\n            'encryption': {\n                'algorithm': 'AES-256-CBC',\n                'key': self._generate_key(256)\n            },\n            'authentication': {\n                'algorithm': 'HMAC-SHA256',\n                'key': self._generate_key(256)\n            },\n            'lifetime': 3600,  # Rekey every hour\n            'anti_replay': True,\n            'window_size': 64\n        }\n\n        return config\n\n    def _generate_key(self, bits):\n        \"\"\"Generate cryptographic key (placeholder - use proper KMS).\"\"\"\n        import secrets\n        return secrets.token_bytes(bits \u002F\u002F 8)\n\n# Example: Secure tunnel from FL zone to gateway\ntunnel = IPsecTunnel()\nconfig = tunnel.configure_tunnel(\n    local_ip='192.168.1.10',   # FL Zone Controller\n    remote_ip='192.168.1.1'     # Gateway\n)\n```\n\n### 3. Firewall Rules for Zone Controllers\n\n```python\nclass ZonalFirewall:\n    \"\"\"\n    Stateful firewall for zone controller Ethernet interface.\n    \"\"\"\n\n    def __init__(self, zone_id):\n        self.zone_id = zone_id\n        self.rules = []\n        self.default_policy = 'DROP'  # Deny by default\n\n    def add_rule(self, rule):\n        \"\"\"\n        Add firewall rule.\n\n        Rule format:\n        {\n            'src_ip': '192.168.1.0\u002F24',\n            'dst_ip': '192.168.2.10',\n            'protocol': 'UDP',\n            'dst_port': 30500,\n            'action': 'ALLOW'\u002F'DROP'\u002F'REJECT',\n            'priority': 100\n        }\n        \"\"\"\n        self.rules.append(rule)\n        # Sort by priority\n        self.rules.sort(key=lambda x: x['priority'])\n\n    def evaluate_packet(self, packet):\n        \"\"\"\n        Evaluate packet against firewall rules.\n\n        Returns:\n            'ALLOW', 'DROP', or 'REJECT'\n        \"\"\"\n\n        for rule in self.rules:\n            if self._match_rule(packet, rule):\n                return rule['action']\n\n        return self.default_policy\n\n    def _match_rule(self, packet, rule):\n        \"\"\"Check if packet matches rule.\"\"\"\n        # Check source IP\n        if not self._ip_in_subnet(packet['src_ip'], rule.get('src_ip', 'any')):\n            return False\n\n        # Check destination IP\n        if not self._ip_in_subnet(packet['dst_ip'], rule.get('dst_ip', 'any')):\n            return False\n\n        # Check protocol\n        if rule.get('protocol', 'any') != 'any' and packet['protocol'] != rule['protocol']:\n            return False\n\n        # Check port\n        if rule.get('dst_port') and packet.get('dst_port') != rule['dst_port']:\n            return False\n\n        return True\n\n# Example: Firewall rules for FL Zone Controller\nfw = ZonalFirewall(zone_id='FL_ZONE')\n\n# Allow SOME\u002FIP from gateway\nfw.add_rule({\n    'src_ip': '192.168.1.1',     # Gateway\n    'dst_ip': '192.168.1.10',     # FL Zone\n    'protocol': 'UDP',\n    'dst_port': 30500,            # SOME\u002FIP service port\n    'action': 'ALLOW',\n    'priority': 100\n})\n\n# Allow diagnostic access (DoIP)\nfw.add_rule({\n    'src_ip': '192.168.5.0\u002F24',   # Diagnostic VLAN\n    'dst_ip': '192.168.1.10',\n    'protocol': 'TCP',\n    'dst_port': 13400,            # DoIP port\n    'action': 'ALLOW',\n    'priority': 200\n})\n\n# Block all other incoming traffic\nfw.add_rule({\n    'src_ip': 'any',\n    'dst_ip': '192.168.1.10',\n    'action': 'DROP',\n    'priority': 1000\n})\n```\n\n### 4. Intrusion Detection System (IDS)\n\n```python\nclass AutomotiveIDS:\n    \"\"\"\n    Intrusion Detection System for automotive Ethernet networks.\n    Detects anomalies and attacks specific to vehicle networks.\n    \"\"\"\n\n    def __init__(self):\n        self.baseline = {}  # Normal traffic patterns\n        self.alerts = []\n\n    def detect_anomalies(self, traffic_sample):\n        \"\"\"\n        Detect network anomalies.\n\n        Detection methods:\n        - Signature-based: Known attack patterns\n        - Anomaly-based: Deviation from baseline\n        - Behavior-based: Unusual communication patterns\n        \"\"\"\n\n        alerts = []\n\n        # 1. Port scan detection\n        if self._detect_port_scan(traffic_sample):\n            alerts.append({\n                'type': 'PORT_SCAN',\n                'severity': 'HIGH',\n                'description': 'Port scan detected from ' + traffic_sample['src_ip']\n            })\n\n        # 2. DoS detection (flooding)\n        if self._detect_dos(traffic_sample):\n            alerts.append({\n                'type': 'DOS_ATTACK',\n                'severity': 'CRITICAL',\n                'description': 'Potential DoS attack detected'\n            })\n\n        # 3. Unusual SOME\u002FIP service access\n        if self._detect_unauthorized_service_access(traffic_sample):\n            alerts.append({\n                'type': 'UNAUTHORIZED_ACCESS',\n                'severity': 'HIGH',\n                'description': 'Unauthorized SOME\u002FIP service access'\n            })\n\n        # 4. ARP spoofing detection\n        if self._detect_arp_spoofing(traffic_sample):\n            alerts.append({\n                'type': 'ARP_SPOOFING',\n                'severity': 'CRITICAL',\n                'description': 'ARP spoofing detected'\n            })\n\n        # 5. Replay attack detection (abnormal packet rate)\n        if self._detect_replay(traffic_sample):\n            alerts.append({\n                'type': 'REPLAY_ATTACK',\n                'severity': 'MEDIUM',\n                'description': 'Potential replay attack detected'\n            })\n\n        return alerts\n\n    def _detect_port_scan(self, traffic):\n        \"\"\"\n        Detect port scanning:\n        - Multiple connection attempts to different ports\n        - From same source IP in short time window\n        \"\"\"\n\n        src_ip = traffic.get('src_ip')\n        unique_ports = traffic.get('unique_dst_ports', [])\n        time_window = traffic.get('time_window_sec', 0)\n\n        # More than 20 ports in 10 seconds = port scan\n        if len(unique_ports) > 20 and time_window \u003C 10:\n            return True\n\n        return False\n\n    def _detect_dos(self, traffic):\n        \"\"\"\n        Detect Denial of Service:\n        - Packet rate > 10x baseline\n        - Same message repeated at high rate\n        \"\"\"\n\n        pkt_rate = traffic.get('packets_per_second', 0)\n        baseline_rate = self.baseline.get('avg_pkt_rate', 100)\n\n        if pkt_rate > baseline_rate * 10:\n            return True\n\n        return False\n\n    def _detect_unauthorized_service_access(self, traffic):\n        \"\"\"\n        Detect unauthorized SOME\u002FIP service access:\n        - Access to service not in whitelist\n        - Access from unauthorized client\n        \"\"\"\n\n        service_id = traffic.get('someip_service_id')\n        client_ip = traffic.get('src_ip')\n\n        authorized_services = {\n            0x1234: ['192.168.1.1'],  # Battery service - gateway only\n            0x5678: ['192.168.1.1', '192.168.1.10']  # Body service - gateway + FL zone\n        }\n\n        if service_id in authorized_services:\n            if client_ip not in authorized_services[service_id]:\n                return True\n\n        return False\n\n    def _detect_arp_spoofing(self, traffic):\n        \"\"\"\n        Detect ARP spoofing:\n        - Different MAC for same IP\n        - Gratuitous ARP with conflicting info\n        \"\"\"\n\n        if traffic.get('protocol') == 'ARP':\n            ip = traffic.get('ip')\n            mac = traffic.get('mac')\n\n            known_mac = self.baseline.get('ip_to_mac', {}).get(ip)\n\n            if known_mac and known_mac != mac:\n                return True  # MAC changed for this IP\n\n        return False\n\n    def _detect_replay(self, traffic):\n        \"\"\"\n        Detect replay attacks:\n        - Same packet repeated (duplicate sequence numbers)\n        - Packet rate anomaly for specific message\n        \"\"\"\n\n        msg_id = traffic.get('msg_id')\n        pkt_count = traffic.get('pkt_count', 0)\n        baseline_count = self.baseline.get('msg_counts', {}).get(msg_id, 1)\n\n        if pkt_count > baseline_count * 5:\n            return True\n\n        return False\n```\n\n### 5. Secure Gateway Design\n\n```c\n\u002F\u002F Secure gateway functionality\ntypedef struct {\n    uint8_t zone_count;\n    struct {\n        uint8_t zone_id;\n        uint32_t ip_address;\n        uint8_t vlan_id;\n        bool macsec_enabled;\n        bool ipsec_enabled;\n        bool firewall_enabled;\n    } zones[8];\n\n    struct {\n        bool ids_enabled;\n        bool ips_enabled;           \u002F\u002F Intrusion Prevention\n        uint16_t alert_threshold;\n        char siem_server[64];       \u002F\u002F SIEM logging\n    } security;\n\n} SecureGateway_t;\n\n\u002F\u002F Example gateway configuration\nSecureGateway_t gateway = {\n    .zone_count = 4,\n    .zones = {\n        {.zone_id = 1, .ip_address = 0xC0A80110, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true},  \u002F\u002F FL Zone\n        {.zone_id = 2, .ip_address = 0xC0A80120, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true},  \u002F\u002F FR Zone\n        {.zone_id = 3, .ip_address = 0xC0A80130, .vlan_id = 200, .macsec_enabled = true, .ipsec_enabled = true, .firewall_enabled = true},   \u002F\u002F ADAS Zone (extra IPsec)\n        {.zone_id = 4, .ip_address = 0xC0A80140, .vlan_id = 100, .macsec_enabled = true, .ipsec_enabled = false, .firewall_enabled = true}   \u002F\u002F RL Zone\n    },\n\n    .security = {\n        .ids_enabled = true,\n        .ips_enabled = true,        \u002F\u002F Block detected attacks automatically\n        .alert_threshold = 10,      \u002F\u002F Alert after 10 suspicious events\n        .siem_server = \"192.168.99.10\"\n    }\n};\n```\n\n## Security Architecture Layers\n\n```\n┌────────────────────────────────────────────┐\n│  Layer 7: Application Security            │\n│  - SOME\u002FIP authentication                 │\n│  - Service access control                 │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 4-6: Transport\u002FSession Security    │\n│  - IPsec (ESP): End-to-end encryption     │\n│  - TLS 1.3: For diagnostic protocols      │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 3: Network Security                │\n│  - Firewall: Packet filtering             │\n│  - IDS\u002FIPS: Anomaly detection             │\n└────────────────────────────────────────────┘\n┌────────────────────────────────────────────┐\n│  Layer 2: Data Link Security              │\n│  - MACsec (IEEE 802.1AE): Link encryption │\n│  - 802.1X: Port-based authentication      │\n└────────────────────────────────────────────┘\n```\n\n## Key Management\n\n```python\nclass VehicleKeyManagement:\n    \"\"\"\n    Key management for MACsec and IPsec.\n    Supports both static provisioning and dynamic key exchange.\n    \"\"\"\n\n    def __init__(self):\n        self.keys = {}\n        self.key_lifetime_hours = 24  # Rotate every 24 hours\n\n    def provision_static_key(self, zone_id, key_type, key_material):\n        \"\"\"\n        Provision static key during manufacturing.\n\n        Args:\n            zone_id: Zone controller ID\n            key_type: 'MACSEC' or 'IPSEC'\n            key_material: 256-bit key\n        \"\"\"\n\n        self.keys[zone_id] = {\n            'type': key_type,\n            'key': key_material,\n            'provisioned_at': time.time(),\n            'valid_until': time.time() + (self.key_lifetime_hours * 3600)\n        }\n\n    def rotate_keys(self):\n        \"\"\"\n        Automatic key rotation every 24 hours.\n        Uses Diffie-Hellman key exchange for new keys.\n        \"\"\"\n\n        for zone_id, key_info in self.keys.items():\n            if time.time() > key_info['valid_until']:\n                # Generate new key\n                new_key = self._dh_key_exchange(zone_id)\n                self.keys[zone_id]['key'] = new_key\n                self.keys[zone_id]['valid_until'] = time.time() + (self.key_lifetime_hours * 3600)\n\n    def _dh_key_exchange(self, zone_id):\n        \"\"\"Diffie-Hellman key exchange (simplified).\"\"\"\n        # In production, use proper DH or ECDH\n        import secrets\n        return secrets.token_bytes(32)  # 256-bit key\n```\n\n## Performance Impact\n\n| Security Feature | Latency Overhead | CPU Overhead | Throughput Impact |\n|------------------|------------------|--------------|-------------------|\n| MACsec (AES-128) | +100 μs | +10% | -5% |\n| MACsec (AES-256) | +150 μs | +15% | -8% |\n| IPsec (ESP) | +200 μs | +20% | -10% |\n| Firewall | +50 μs | +5% | -2% |\n| IDS (passive) | +10 μs | +8% | 0% |\n| IPS (active) | +100 μs | +15% | -5% |\n\n## Tools & Testing\n\n- **Wireshark with MACsec plugin** - Decrypt and analyze MACsec traffic\n- **Scapy** - Craft attack packets for security testing\n- **Suricata** - Open-source IDS\u002FIPS engine\n- **Kali Linux** - Penetration testing toolkit\n- **CANalyze** - Automotive-specific security testing\n\n## References\n\n- IEEE 802.1AE (MACsec) Standard\n- ISO\u002FSAE 21434 Cybersecurity Engineering\n- UNECE R155 Cybersecurity Regulation\n- AUTOSAR Secure Communication Specification\n\n---\n\n## Service Oriented Communication\n\n# Service-Oriented Communication - SOME\u002FIP & DDS\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in service-oriented middleware for automotive zonal architectures. Covers SOME\u002FIP (Scalable Service-Oriented Middleware over IP), DDS (Data Distribution Service), service discovery, publish-subscribe patterns, event-driven architecture, and method invocations over Ethernet.\n\n## Core Competencies\n\n### 1. SOME\u002FIP (AUTOSAR Standard)\n\n#### Protocol Overview\n\n**SOME\u002FIP = Scalable Service-Oriented Middleware over IP**\n- Used in AUTOSAR Adaptive Platform\n- Transport: UDP or TCP over IPv4\u002FIPv6\n- Serialization: SOME\u002FIP binary format\n- Discovery: SOME\u002FIP-SD (Service Discovery)\n\n```c\n\u002F\u002F SOME\u002FIP Message Header (16 bytes)\ntypedef struct __attribute__((packed)) {\n    uint32_t message_id;      \u002F\u002F Service ID (16 bits) + Method ID (16 bits)\n    uint32_t length;          \u002F\u002F Payload length + 8\n    uint32_t request_id;      \u002F\u002F Client ID (16 bits) + Session ID (16 bits)\n    uint8_t  protocol_version; \u002F\u002F 0x01\n    uint8_t  interface_version; \u002F\u002F Service interface version\n    uint8_t  message_type;    \u002F\u002F REQUEST=0x00, RESPONSE=0x80, ERROR=0x81, NOTIFICATION=0x02\n    uint8_t  return_code;     \u002F\u002F E_OK=0x00, E_NOT_OK=0x01, etc.\n} SOMEIP_Header_t;\n\n\u002F\u002F Example: Request message\nSOMEIP_Header_t request = {\n    .message_id = 0x12340001,  \u002F\u002F Service 0x1234, Method 0x0001\n    .length = 24,              \u002F\u002F Header (16) + Payload (8)\n    .request_id = 0x00010001,  \u002F\u002F Client 0x0001, Session 0x0001\n    .protocol_version = 0x01,\n    .interface_version = 0x01,\n    .message_type = 0x00,      \u002F\u002F REQUEST\n    .return_code = 0x00        \u002F\u002F E_OK\n};\n```\n\n#### Service Definition (FIDL)\n\n```fidl\n\u002F\u002F Franca IDL (FIDL) - SOME\u002FIP Service Definition\npackage org.genivi.battery\n\ninterface BatteryManagementService {\n    version { major 1 minor 0 }\n\n    \u002F\u002F Methods (Request\u002FResponse)\n    method GetBatteryStatus {\n        out {\n            UInt8 stateOfCharge    \u002F\u002F 0-100%\n            Float voltage           \u002F\u002F Volts\n            Float current           \u002F\u002F Amps\n            Int8 temperature        \u002F\u002F Celsius\n        }\n    }\n\n    method SetChargingLimit {\n        in {\n            UInt8 targetSoC        \u002F\u002F Target SOC %\n        }\n        out {\n            Boolean success\n        }\n    }\n\n    \u002F\u002F Events (Notifications)\n    broadcast BatteryAlarm {\n        out {\n            UInt16 alarmCode\n            String description\n        }\n    }\n\n    \u002F\u002F Attributes (Getter\u002FSetter\u002FNotification)\n    attribute UInt8 stateOfCharge readonly\n\n    \u002F\u002F Error codes\n    enumeration BatteryError {\n        OK = 0\n        INVALID_PARAMETER = 1\n        HARDWARE_FAULT = 2\n        COMMUNICATION_ERROR = 3\n    }\n}\n```\n\n#### SOME\u002FIP Service Implementation\n\n```cpp\n#include \u003CCommonAPI\u002FCommonAPI.hpp>\n#include \u003Cv1\u002Forg\u002Fgenivi\u002Fbattery\u002FBatteryManagementServiceProxy.hpp>\n\nusing namespace v1::org::genivi::battery;\n\nclass BatteryClient {\npublic:\n    BatteryClient() {\n        runtime_ = CommonAPI::Runtime::get();\n        proxy_ = runtime_->buildProxy\u003CBatteryManagementServiceProxy>(\n            \"local\", \"BatteryService\");\n\n        \u002F\u002F Wait for service availability\n        while (!proxy_->isAvailable()) {\n            std::this_thread::sleep_for(std::chrono::milliseconds(100));\n        }\n\n        \u002F\u002F Subscribe to battery alarms\n        proxy_->getBatteryAlarmEvent().subscribe(\n            [](uint16_t alarmCode, std::string description) {\n                std::cout \u003C\u003C \"Alarm \" \u003C\u003C alarmCode \u003C\u003C \": \"\n                          \u003C\u003C description \u003C\u003C std::endl;\n            });\n    }\n\n    void getBatteryStatus() {\n        \u002F\u002F Synchronous method call\n        CommonAPI::CallStatus callStatus;\n        uint8_t soc;\n        float voltage, current;\n        int8_t temperature;\n\n        proxy_->GetBatteryStatus(callStatus, soc, voltage, current, temperature);\n\n        if (callStatus == CommonAPI::CallStatus::SUCCESS) {\n            std::cout \u003C\u003C \"SOC: \" \u003C\u003C (int)soc \u003C\u003C \"%\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Voltage: \" \u003C\u003C voltage \u003C\u003C \"V\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Current: \" \u003C\u003C current \u003C\u003C \"A\" \u003C\u003C std::endl;\n            std::cout \u003C\u003C \"Temperature: \" \u003C\u003C (int)temperature \u003C\u003C \"°C\" \u003C\u003C std::endl;\n        }\n    }\n\n    void setChargingLimit(uint8_t targetSoC) {\n        \u002F\u002F Asynchronous method call with callback\n        proxy_->SetChargingLimitAsync(\n            targetSoC,\n            [](const CommonAPI::CallStatus& status, bool success) {\n                if (status == CommonAPI::CallStatus::SUCCESS && success) {\n                    std::cout \u003C\u003C \"Charging limit set successfully\" \u003C\u003C std::endl;\n                }\n            });\n    }\n\nprivate:\n    std::shared_ptr\u003CCommonAPI::Runtime> runtime_;\n    std::shared_ptr\u003CBatteryManagementServiceProxy\u003C>> proxy_;\n};\n```\n\n#### SOME\u002FIP-SD (Service Discovery)\n\n```python\nclass SOMEIPServiceDiscovery:\n    \"\"\"\n    SOME\u002FIP Service Discovery (SOME\u002FIP-SD) implementation.\n    Uses UDP multicast (224.244.224.245:30490) for service advertisement.\n    \"\"\"\n\n    def __init__(self):\n        self.multicast_group = '224.244.224.245'\n        self.multicast_port = 30490\n        self.services = {}\n\n    def offer_service(self, service_id, instance_id, endpoint):\n        \"\"\"\n        Offer a service via SOME\u002FIP-SD.\n\n        Args:\n            service_id: Service identifier (16-bit)\n            instance_id: Instance identifier (16-bit)\n            endpoint: (IP, port, protocol)  protocol='UDP' or 'TCP'\n        \"\"\"\n\n        offer_message = {\n            'message_type': 'OfferService',\n            'service_id': service_id,\n            'instance_id': instance_id,\n            'major_version': 1,\n            'minor_version': 0,\n            'ttl': 3,  # Time-to-live in seconds (0xFFFFFF = infinite)\n            'endpoint': {\n                'ipv4': endpoint[0],\n                'port': endpoint[1],\n                'protocol': endpoint[2]  # UDP or TCP\n            }\n        }\n\n        # Send cyclic offers (every 1 second)\n        # Until service is stopped\n        return offer_message\n\n    def find_service(self, service_id, instance_id=None):\n        \"\"\"\n        Find a service via SOME\u002FIP-SD.\n\n        Args:\n            service_id: Service to find\n            instance_id: Specific instance (None = any)\n\n        Returns:\n            List of available service endpoints\n        \"\"\"\n\n        find_message = {\n            'message_type': 'FindService',\n            'service_id': service_id,\n            'instance_id': instance_id if instance_id else 0xFFFF,  # ANY\n            'major_version': 0xFF,  # ANY\n            'minor_version': 0xFFFFFFFF  # ANY\n        }\n\n        # Wait for OfferService responses\n        # Return list of endpoints\n        return []\n\n# Example usage:\nsd = SOMEIPServiceDiscovery()\n\n# Offer battery service\nsd.offer_service(\n    service_id=0x1234,\n    instance_id=0x0001,\n    endpoint=('192.168.1.10', 30500, 'UDP')\n)\n\n# Find battery service\nendpoints = sd.find_service(service_id=0x1234)\n```\n\n### 2. DDS (Data Distribution Service)\n\n#### DDS Quality of Service (QoS)\n\n```python\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nclass ReliabilityKind(Enum):\n    BEST_EFFORT = 0  # UDP-like, lossy\n    RELIABLE = 1      # TCP-like, guaranteed delivery\n\nclass DurabilityKind(Enum):\n    VOLATILE = 0          # Only for live data\n    TRANSIENT_LOCAL = 1   # Store last value for late joiners\n    TRANSIENT = 2         # Persist across processes\n    PERSISTENT = 3        # Persist to disk\n\n@dataclass\nclass DDSQoS:\n    \"\"\"DDS Quality of Service configuration.\"\"\"\n\n    reliability: ReliabilityKind\n    durability: DurabilityKind\n    history_depth: int  # Number of samples to keep\n    max_blocking_time_ms: int  # Max time to block writer\n    latency_budget_ms: int  # Hint for latency optimization\n    lifespan_ms: int  # Sample validity duration\n\n# Example QoS profiles for different use cases\n\n# Safety-critical real-time data (ESC, ABS)\nSAFETY_QOS = DDSQoS(\n    reliability=ReliabilityKind.RELIABLE,\n    durability=DurabilityKind.VOLATILE,\n    history_depth=1,  # Only latest value matters\n    max_blocking_time_ms=10,\n    latency_budget_ms=5,\n    lifespan_ms=100\n)\n\n# Sensor data (high-rate, best-effort)\nSENSOR_QOS = DDSQoS(\n    reliability=ReliabilityKind.BEST_EFFORT,\n    durability=DurabilityKind.VOLATILE,\n    history_depth=5,\n    max_blocking_time_ms=0,  # Non-blocking\n    latency_budget_ms=1,\n    lifespan_ms=50\n)\n\n# Configuration data (late-joiner support)\nCONFIG_QOS = DDSQoS(\n    reliability=ReliabilityKind.RELIABLE,\n    durability=DurabilityKind.TRANSIENT_LOCAL,\n    history_depth=1,\n    max_blocking_time_ms=1000,\n    latency_budget_ms=100,\n    lifespan_ms=0  # No expiration\n)\n```\n\n#### DDS Topic Definition (IDL)\n\n```idl\n\u002F\u002F OMG IDL for DDS topics\nmodule automotive {\n    module battery {\n\n        struct BatteryStatus {\n            unsigned long timestamp;    \u002F\u002F Unix timestamp (ms)\n            octet stateOfCharge;        \u002F\u002F 0-100%\n            float voltage;              \u002F\u002F Volts\n            float current;              \u002F\u002F Amps\n            char temperature;           \u002F\u002F Celsius\n            boolean charging;\n        };\n\n        struct BatteryAlarm {\n            unsigned long timestamp;\n            unsigned short alarmCode;\n            string\u003C256> description;\n            octet severity;  \u002F\u002F 0=Info, 1=Warning, 2=Error, 3=Critical\n        };\n\n    };\n};\n```\n\n#### DDS Publisher\u002FSubscriber (C++)\n\n```cpp\n#include \u003Cdds\u002Fdds.hpp>\n#include \"BatteryStatus.hpp\"\n\nusing namespace automotive::battery;\n\nclass BatteryPublisher {\npublic:\n    BatteryPublisher() {\n        \u002F\u002F Create DDS participant (one per application)\n        participant_ = dds::domain::DomainParticipant(0);\n\n        \u002F\u002F Create topic\n        topic_ = dds::topic::Topic\u003CBatteryStatus>(\n            participant_, \"BatteryStatusTopic\");\n\n        \u002F\u002F Create publisher with QoS\n        dds::pub::qos::PublisherQos pub_qos;\n        publisher_ = dds::pub::Publisher(participant_, pub_qos);\n\n        \u002F\u002F Create data writer\n        dds::pub::qos::DataWriterQos writer_qos;\n        writer_qos \u003C\u003C SAFETY_QOS;  \u002F\u002F Use safety QoS profile\n        writer_ = dds::pub::DataWriter\u003CBatteryStatus>(publisher_, topic_, writer_qos);\n    }\n\n    void publishStatus(uint8_t soc, float voltage, float current, int8_t temp) {\n        BatteryStatus status;\n        status.timestamp(std::chrono::system_clock::now().time_since_epoch().count());\n        status.stateOfCharge(soc);\n        status.voltage(voltage);\n        status.current(current);\n        status.temperature(temp);\n        status.charging(current > 0);\n\n        writer_.write(status);\n    }\n\nprivate:\n    dds::domain::DomainParticipant participant_;\n    dds::topic::Topic\u003CBatteryStatus> topic_;\n    dds::pub::Publisher publisher_;\n    dds::pub::DataWriter\u003CBatteryStatus> writer_;\n};\n\nclass BatterySubscriber {\npublic:\n    BatterySubscriber() {\n        participant_ = dds::domain::DomainParticipant(0);\n        topic_ = dds::topic::Topic\u003CBatteryStatus>(\n            participant_, \"BatteryStatusTopic\");\n\n        dds::sub::qos::SubscriberQos sub_qos;\n        subscriber_ = dds::sub::Subscriber(participant_, sub_qos);\n\n        dds::sub::qos::DataReaderQos reader_qos;\n        reader_qos \u003C\u003C SAFETY_QOS;\n        reader_ = dds::sub::DataReader\u003CBatteryStatus>(subscriber_, topic_, reader_qos);\n\n        \u002F\u002F Register listener for data arrival\n        reader_.listener(\n            new BatteryStatusListener(),\n            dds::core::status::StatusMask::data_available());\n    }\n\nprivate:\n    class BatteryStatusListener : public dds::sub::NoOpDataReaderListener\u003CBatteryStatus> {\n    public:\n        void on_data_available(dds::sub::DataReader\u003CBatteryStatus>& reader) override {\n            auto samples = reader.take();\n            for (const auto& sample : samples) {\n                if (sample.info().valid()) {\n                    std::cout \u003C\u003C \"SOC: \" \u003C\u003C (int)sample.data().stateOfCharge() \u003C\u003C \"%\"\n                              \u003C\u003C \" Voltage: \" \u003C\u003C sample.data().voltage() \u003C\u003C \"V\"\n                              \u003C\u003C std::endl;\n                }\n            }\n        }\n    };\n\n    dds::domain::DomainParticipant participant_;\n    dds::topic::Topic\u003CBatteryStatus> topic_;\n    dds::sub::Subscriber subscriber_;\n    dds::sub::DataReader\u003CBatteryStatus> reader_;\n};\n```\n\n### 3. Service Discovery Mechanisms\n\n#### Comparison\n\n| Feature | SOME\u002FIP-SD | DDS Discovery |\n|---------|-----------|---------------|\n| Transport | UDP multicast | UDP\u002FTCP multicast + unicast |\n| Discovery time | 1-3 seconds | \u003C100ms |\n| Overhead | Low (periodic offers) | Medium (SPDP + SEDP) |\n| Dynamic reconfiguration | Yes | Yes |\n| QoS negotiation | Limited | Extensive |\n| Best for | AUTOSAR Adaptive | Complex data flows |\n\n### 4. Event-Driven Architecture Patterns\n\n```python\nclass EventBus:\n    \"\"\"\n    Automotive event bus for service-oriented communication.\n    Supports both SOME\u002FIP and DDS backends.\n    \"\"\"\n\n    def __init__(self, backend='someip'):\n        self.backend = backend\n        self.subscribers = {}\n\n    def publish(self, topic, data, qos='reliable'):\n        \"\"\"\n        Publish event to topic.\n\n        Args:\n            topic: Event topic name\n            data: Event payload\n            qos: 'reliable' or 'best_effort'\n        \"\"\"\n\n        if self.backend == 'someip':\n            # SOME\u002FIP notification\n            self._someip_notify(topic, data)\n        elif self.backend == 'dds':\n            # DDS publish\n            self._dds_publish(topic, data, qos)\n\n    def subscribe(self, topic, callback, qos='reliable'):\n        \"\"\"\n        Subscribe to topic with callback.\n\n        Args:\n            topic: Topic name\n            callback: Function to call on event\n            qos: QoS requirements\n        \"\"\"\n\n        if topic not in self.subscribers:\n            self.subscribers[topic] = []\n\n        self.subscribers[topic].append({\n            'callback': callback,\n            'qos': qos\n        })\n\n        if self.backend == 'someip':\n            self._someip_subscribe(topic)\n        elif self.backend == 'dds':\n            self._dds_subscribe(topic, qos)\n\n# Usage example:\nbus = EventBus(backend='someip')\n\n# Subscribe to battery alarms\nbus.subscribe('battery\u002Falarm', lambda alarm: print(f\"Alarm: {alarm}\"))\n\n# Publish alarm event\nbus.publish('battery\u002Falarm', {\n    'code': 0x1234,\n    'severity': 'critical',\n    'description': 'Over-temperature detected'\n})\n```\n\n## Performance Characteristics\n\n### SOME\u002FIP\n- **Latency**: 1-5ms (local), 10-50ms (remote)\n- **Throughput**: Up to 100 Mbps per service\n- **Overhead**: ~16 bytes header per message\n- **Discovery time**: 1-3 seconds (configurable)\n\n### DDS\n- **Latency**: \u003C1ms (local), 5-20ms (remote)\n- **Throughput**: Up to 1 Gbps aggregate\n- **Overhead**: ~20 bytes RTPS header\n- **Discovery time**: \u003C100ms\n\n## Best Practices\n\n1. **Use SOME\u002FIP** for AUTOSAR Adaptive services, ECU-to-ECU communication\n2. **Use DDS** for high-throughput sensor data, complex QoS requirements\n3. **Choose UDP** for time-critical best-effort data (sensors)\n4. **Choose TCP** for reliable control commands, configuration\n5. **Minimize service interfaces** - Fewer, richer services better than many small ones\n6. **Use service versioning** - Major version in service ID, minor in header\n\n## Tools\n\n- **Vector MICROSAR** - SOME\u002FIP stack for AUTOSAR Classic\u002FAdaptive\n- **RTI Connext DDS** - High-performance DDS implementation\n- **Eclipse Cyclone DDS** - Open-source DDS (used in ROS 2)\n- **vsomeip** - Open-source SOME\u002FIP implementation (BMW\u002FGENIVI)\n- **CommonAPI** - Language bindings for SOME\u002FIP and DDS\n\n## References\n\n- AUTOSAR Specification of SOME\u002FIP Protocol (PRS_SOMEIPPROTOCOL)\n- OMG Data Distribution Service (DDS) Specification v1.4\n- AUTOSAR Adaptive Platform R22-11\n- SOME\u002FIP Protocol Specification v1.3.0\n\n---\n\n## Zonal Architecture Design\n\n# Zonal Architecture Design\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in designing next-generation vehicle E\u002FE zonal architectures. Covers zone controller placement, domain consolidation, topology optimization, cable harness reduction strategies, and migration from traditional domain architectures to zonal designs.\n\n## Core Competencies\n\n### 1. Zone Controller Placement Strategy\n\n#### Optimal Zone Count\nTypical modern vehicles use **4-8 zones**:\n- **4 zones**: Entry-level vehicles (FL, FR, RL, RR corners)\n- **6 zones**: Mid-range (4 corners + front-center + rear-center)\n- **8 zones**: Premium (4 corners + FC, RC, left-center, right-center)\n\n**Placement Criteria:**\n```python\nclass ZonePlacementOptimizer:\n    def __init__(self, vehicle_model):\n        self.vehicle = vehicle_model\n        self.sensors = []\n        self.actuators = []\n\n    def optimize_zones(self, max_cable_length=2.0):\n        \"\"\"\n        Optimize zone placement to minimize cable length.\n\n        Args:\n            max_cable_length: Maximum cable run in meters (default 2m)\n\n        Returns:\n            List of zone controller locations\n        \"\"\"\n        from sklearn.cluster import KMeans\n        import numpy as np\n\n        # Get all sensor\u002Factuator positions\n        positions = np.array([\n            [comp.x, comp.y, comp.z]\n            for comp in self.sensors + self.actuators\n        ])\n\n        # Cluster to find optimal zone centers\n        n_zones = self._estimate_zone_count(positions, max_cable_length)\n        kmeans = KMeans(n_clusters=n_zones, random_state=42)\n        kmeans.fit(positions)\n\n        zones = []\n        for i, center in enumerate(kmeans.cluster_centers_):\n            zone = {\n                'id': f'ZCU_{i+1}',\n                'location': center.tolist(),\n                'components': [],\n                'cable_savings': 0.0\n            }\n\n            # Assign components to zones\n            labels = kmeans.labels_\n            zone_components = [\n                comp for idx, comp in enumerate(self.sensors + self.actuators)\n                if labels[idx] == i\n            ]\n            zone['components'] = zone_components\n            zones.append(zone)\n\n        return zones\n\n    def _estimate_zone_count(self, positions, max_length):\n        \"\"\"Estimate optimal number of zones based on component density.\"\"\"\n        bbox = positions.max(axis=0) - positions.min(axis=0)\n        vehicle_length = bbox[0]\n        vehicle_width = bbox[1]\n\n        # Coverage area per zone (circle of radius max_length)\n        zone_coverage = np.pi * (max_length ** 2)\n        vehicle_area = vehicle_length * vehicle_width\n\n        return max(4, int(np.ceil(vehicle_area \u002F zone_coverage)))\n```\n\n#### Zone Controller Hardware Selection\n\n| Zone Type | Hardware Platform | Cost | Use Case |\n|-----------|------------------|------|----------|\n| **Low-cost Corner** | NXP S32K344 | $15-20 | Lighting, windows, mirrors |\n| **Standard Zone** | Renesas RH850\u002FU2A | $25-35 | Body control, HVAC, doors |\n| **Gateway\u002FCentral** | NXP S32G274A | $80-120 | Ethernet switch, firewall, routing |\n| **High-performance** | Infineon AURIX TC397 | $60-90 | ADAS integration, safety |\n\n**Selection Decision Tree:**\n```\nIs zone safety-critical (ASIL-C\u002FD)?\n├─ Yes → AURIX TC397 (lockstep cores, ECC RAM)\n└─ No → Does zone need Ethernet switching?\n    ├─ Yes → S32G274A (4x Gb Ethernet, TSN)\n    └─ No → Component count?\n        ├─ \u003C20 → S32K344 (low-cost)\n        └─ >20 → RH850\u002FU2A (more I\u002FO)\n```\n\n### 2. Cable Harness Reduction\n\n**Traditional Domain Architecture:**\n```\nTotal cable length: 4,500 meters\nTotal weight: 45 kg\nCost: $450 per vehicle\n```\n\n**Zonal Architecture Benefits:**\n```python\nclass CableHarnessAnalyzer:\n    def calculate_savings(self, domain_arch, zonal_arch):\n        \"\"\"\n        Calculate cable harness savings from domain-to-zonal migration.\n\n        Returns:\n            dict: Savings in length, weight, and cost\n        \"\"\"\n        # Domain architecture stats\n        domain_cables = {\n            'sensor_to_ecu': 2800,  # meters\n            'inter_ecu': 1200,\n            'power_distribution': 500\n        }\n\n        # Zonal architecture stats\n        zonal_cables = {\n            'sensor_to_zone': 1500,  # \u003C2m each, drastically shorter\n            'zone_to_gateway': 150,  # Ethernet backbone only\n            'power_distribution': 300  # Zonal PDUs\n        }\n\n        total_domain = sum(domain_cables.values())\n        total_zonal = sum(zonal_cables.values())\n\n        reduction_meters = total_domain - total_zonal\n        reduction_percent = (reduction_meters \u002F total_domain) * 100\n\n        # Weight savings (0.01 kg\u002Fmeter average)\n        weight_savings = reduction_meters * 0.01  # kg\n\n        # Cost savings ($0.10\u002Fmeter cable + installation)\n        cost_savings = reduction_meters * 0.15  # USD\n\n        return {\n            'cable_reduction_m': reduction_meters,\n            'cable_reduction_pct': reduction_percent,\n            'weight_savings_kg': weight_savings,\n            'cost_savings_usd': cost_savings\n        }\n\n# Example output:\n# {\n#     'cable_reduction_m': 2550,\n#     'cable_reduction_pct': 56.7%,\n#     'weight_savings_kg': 25.5 kg,\n#     'cost_savings_usd': $382.50\n# }\n```\n\n**Actual OEM Results:**\n- **VW MEB Platform**: 30% cable reduction\n- **Tesla Model 3**: 1.5 km total harness (vs 3 km traditional)\n- **Rivian R1T**: 40% weight reduction in harness\n\n### 3. Network Topology Design\n\n#### Topology Options\n\n**A. Star Topology (Recommended for Safety)**\n```\n                    ┌─────────────┐\n                    │   Gateway   │\n                    │   S32G274   │\n                    └──────┬──────┘\n                           │\n        ┌──────────────┬───┴───┬──────────────┐\n        │              │       │              │\n    ┌───┴───┐      ┌───┴───┐ ┌┴─────┐    ┌───┴───┐\n    │ FL ZCU│      │ FR ZCU│ │RC ZCU│    │ RL ZCU│\n    └───────┘      └───────┘ └──────┘    └───────┘\n\nPros:\n+ Direct gateway connection (low latency)\n+ Simple fault isolation\n+ Easy TSN configuration\n+ No cascading failures\n\nCons:\n- More cable to gateway\n- Single point of failure (mitigated with redundant gateway)\n```\n\n**B. Ring Topology (High Availability)**\n```\n    ┌─────────┐──────┐Gateway│──────┐─────────┐\n    │         │      └────────┘      │         │\n    │         │                      │         │\n┌───┴───┐ ┌───┴───┐              ┌───┴───┐ ┌───┴───┐\n│FL ZCU │ │FR ZCU │              │RR ZCU │ │RL ZCU │\n└───────┘ └───────┘              └───────┘ └───────┘\n\nPros:\n+ Redundant paths (fault tolerance)\n+ Load balancing possible\n+ Cable length optimization\n\nCons:\n- Complex TSN configuration\n- Potential for loops (need STP\u002FRSTP)\n```\n\n**C. Daisy Chain (Cost-Optimized)**\n```\n┌────────┐    ┌──────┐    ┌──────┐    ┌──────┐    ┌──────┐\n│Gateway │────│FL ZCU│────│FR ZCU│────│RR ZCU│────│RL ZCU│\n└────────┘    └──────┘    └──────┘    └──────┘    └──────┘\n\nPros:\n+ Minimal cable length\n+ Lowest cost\n\nCons:\n- Cascading failures\n- Higher latency for distant zones\n- Not suitable for safety-critical\n```\n\n#### Ethernet Physical Layer Selection\n\n```c\n\u002F\u002F 100BASE-T1 Configuration (Standard zones)\nstruct ethernet_phy_config {\n    uint8_t standard;        \u002F\u002F 100BASE-T1\n    uint16_t max_distance;   \u002F\u002F 15 meters\n    uint32_t bandwidth;      \u002F\u002F 100 Mbps\n    uint8_t pair_count;      \u002F\u002F 1 twisted pair\n    float cost_per_meter;    \u002F\u002F $0.50\n};\n\n\u002F\u002F 1000BASE-T1 Configuration (High-bandwidth zones - cameras, ADAS)\nstruct ethernet_phy_1g {\n    uint8_t standard;        \u002F\u002F 1000BASE-T1\n    uint16_t max_distance;   \u002F\u002F 40 meters\n    uint32_t bandwidth;      \u002F\u002F 1 Gbps\n    uint8_t pair_count;      \u002F\u002F 1 twisted pair\n    float cost_per_meter;    \u002F\u002F $0.80\n};\n\n\u002F\u002F 10BASE-T1S Configuration (Low-cost multidrop sensors)\nstruct ethernet_phy_10base {\n    uint8_t standard;        \u002F\u002F 10BASE-T1S\n    uint16_t max_distance;   \u002F\u002F 25 meters (multidrop bus)\n    uint32_t bandwidth;      \u002F\u002F 10 Mbps\n    uint8_t topology;        \u002F\u002F Multidrop (up to 8 nodes per segment)\n    float cost_per_meter;    \u002F\u002F $0.30\n};\n```\n\n### 4. Power Distribution Architecture\n\n**Zonal Power Distribution Units (PDUs):**\n\n```c\ntypedef struct {\n    char zone_id[16];\n    uint8_t num_power_rails;\n    float voltage_12v;\n    float voltage_5v;\n    float voltage_3v3;\n    uint8_t load_shedding_priority[8];  \u002F\u002F 0=critical, 7=lowest\n    bool intelligent_fusing;\n} ZonalPDU_Config_t;\n\n\u002F\u002F Example: Front-Left Zone PDU\nZonalPDU_Config_t fl_pdu = {\n    .zone_id = \"FL_ZONE\",\n    .num_power_rails = 8,\n    .voltage_12v = 12.0,\n    .voltage_5v = 5.0,\n    .voltage_3v3 = 3.3,\n    .load_shedding_priority = {\n        0,  \u002F\u002F Headlights (critical)\n        1,  \u002F\u002F Turn signals (safety)\n        2,  \u002F\u002F DRL (legal requirement)\n        5,  \u002F\u002F Fog lights\n        6,  \u002F\u002F Puddle lights\n        7,  \u002F\u002F Ambient lighting\n    },\n    .intelligent_fusing = true\n};\n\n\u002F\u002F Load shedding during low battery\nvoid perform_load_shedding(ZonalPDU_Config_t *pdu, uint8_t battery_soc) {\n    if (battery_soc \u003C 20) {\n        \u002F\u002F Shed priority 7 loads (ambient lighting)\n        disable_loads_by_priority(pdu, 7);\n    }\n    if (battery_soc \u003C 10) {\n        \u002F\u002F Shed priority 6 loads (puddle lights)\n        disable_loads_by_priority(pdu, 6);\n    }\n    if (battery_soc \u003C 5) {\n        \u002F\u002F Shed priority 5 loads (fog lights)\n        disable_loads_by_priority(pdu, 5);\n        \u002F\u002F Keep only priority 0-2 (critical\u002Fsafety)\n    }\n}\n```\n\n**Power Budget per Zone:**\n| Zone | Typical Power | Peak Power | Components |\n|------|--------------|-----------|------------|\n| FL Corner | 150W | 300W | Headlights, turn signals, window, mirror |\n| FR Corner | 150W | 300W | Headlights, turn signals, window, mirror |\n| RL Corner | 100W | 200W | Taillights, window |\n| RR Corner | 100W | 200W | Taillights, window |\n| Front Center | 200W | 400W | Wipers, HVAC blower, sensors |\n| Rear Center | 80W | 150W | Trunk, license plate light |\n\n### 5. Domain-to-Zonal Migration Strategy\n\n**Phase 1: Hybrid Architecture (18-24 months)**\n- Keep existing domain ECUs\n- Add zone controllers for new sensors\n- Use gateway to bridge domains and zones\n- Validate zonal concept\n\n**Phase 2: Partial Migration (24-36 months)**\n- Migrate body domain to zonal\n- Keep powertrain\u002FADAS domains\n- 40-50% cable reduction achieved\n\n**Phase 3: Full Zonal (36-48 months)**\n- All functions on zone controllers\n- Domain ECUs eliminated\n- 50-60% cable reduction\n- Central compute for ADAS\u002Finfotainment\n\n```python\nclass MigrationPlanner:\n    def create_migration_roadmap(self):\n        \"\"\"Generate phased migration from domain to zonal architecture.\"\"\"\n\n        phases = [\n            {\n                'phase': 1,\n                'name': 'Hybrid Introduction',\n                'duration_months': 18,\n                'zones_added': ['FL', 'FR'],\n                'functions_migrated': ['Lighting', 'Windows'],\n                'cable_reduction': '15%',\n                'cost': '$2M NRE',\n                'risk': 'Low'\n            },\n            {\n                'phase': 2,\n                'name': 'Body Domain Migration',\n                'duration_months': 24,\n                'zones_added': ['RL', 'RR', 'FC', 'RC'],\n                'functions_migrated': ['All body', 'HVAC', 'Doors'],\n                'cable_reduction': '45%',\n                'cost': '$5M NRE',\n                'risk': 'Medium'\n            },\n            {\n                'phase': 3,\n                'name': 'Full Zonal',\n                'duration_months': 36,\n                'zones_added': ['LC', 'RC'],\n                'functions_migrated': ['All functions'],\n                'cable_reduction': '60%',\n                'cost': '$8M NRE',\n                'risk': 'High',\n                'payback': '2.5 years at 100k units\u002Fyear'\n            }\n        ]\n\n        return phases\n```\n\n## ROI Calculation\n\n**Per-Vehicle Savings:**\n```\nCable harness reduction: $250\nWeight reduction (fuel economy): $50\u002Fvehicle lifetime\nAssembly time reduction: $100\nService diagnostics improvement: $30\n\nTotal savings: $430 per vehicle\n```\n\n**NRE Investment:**\n```\nZone controller development: $3M\nSoftware architecture: $2M\nTesting & validation: $2M\nProduction tooling: $1M\n\nTotal NRE: $8M\n```\n\n**Payback Period:**\n```\nAt 50,000 units\u002Fyear:\n$8M \u002F ($430 × 50,000) = 0.37 years (4.5 months)\n\nAt 100,000 units\u002Fyear:\nImmediate positive ROI\n```\n\n## Best Practices\n\n1. **Start with body domain** - Lowest safety criticality, highest cable savings\n2. **Use star topology** for safety-critical zones\n3. **Implement intelligent power management** - Load shedding, priority-based\n4. **Plan for redundancy** - Dual Ethernet links to gateway\n5. **Use TSN** for deterministic latency (\u003C10ms p99)\n6. **Leverage 10BASE-T1S** for low-cost sensors (multidrop)\n7. **Plan thermal management** - Zone controllers generate more heat than distributed ECUs\n\n## Tools & Frameworks\n\n- **Capital Harness Designer** - Cable routing and optimization\n- **PREEvision** - E\u002FE architecture design\n- **SystemDesk** - AUTOSAR Adaptive configuration\n- **Vector CANoe** - Network simulation and testing\n\n## References\n\n- VDA Recommendation on Zonal E\u002FE Architecture\n- IEEE 802.1 TSN Standards\n- AUTOSAR Adaptive Platform R22-11\n- SAE J3161 On-Board Ethernet Communication\n\n---\n\n## Zone Controller Development\n\n# Zone Controller Development\n\n**Category:** automotive-zonal\n**Version:** 1.0.0\n**Maturity:** production\n**Complexity:** advanced\n\n## Overview\n\nExpert knowledge in developing zone controller firmware and software for next-generation zonal E\u002FE architectures. Covers hardware platforms (NXP S32K3, Renesas RH850, Infineon AURIX), I\u002FO handling, sensor aggregation, actuator control, gateway functions, and AUTOSAR integration.\n\n## Core Competencies\n\n### 1. Zone Controller Hardware Platforms\n\n#### NXP S32K3 (Entry to Mid-Range)\n\n**S32K344 Specifications:**\n```c\n\u002F\u002F NXP S32K344 - Low-cost zone controller\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F ARM Cortex-M7\n        uint32_t frequency_mhz; \u002F\u002F 160 MHz\n        uint8_t cores;          \u002F\u002F 1\n        bool lockstep;          \u002F\u002F No (QM)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 4096 KB\n        uint32_t ram_kb;        \u002F\u002F 512 KB\n        bool ecc;               \u002F\u002F Optional\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 6x CAN-FD\n        uint8_t lin;            \u002F\u002F 3x LIN\n        uint8_t ethernet_100m;  \u002F\u002F 1x 100BASE-T1\n        uint8_t spi;            \u002F\u002F 4x SPI\n        uint8_t i2c;            \u002F\u002F 2x I2C\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 3x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 32x eMIOS PWM\n        uint8_t gpio;           \u002F\u002F 144 GPIO\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-B capable\n    float cost_usd;             \u002F\u002F $18-22\n} S32K344_Spec_t;\n```\n\n**Use Cases:**\n- Corner zones (FL, FR, RL, RR)\n- Lighting control\n- Window\u002Fmirror control\n- Low-complexity body functions\n\n#### Renesas RH850\u002FU2A (Mid-Range)\n\n**RH850\u002FU2A8 Specifications:**\n```c\n\u002F\u002F Renesas RH850\u002FU2A8 - Standard zone controller\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F RH850 G4MH\n        uint32_t frequency_mhz; \u002F\u002F 320 MHz\n        uint8_t cores;          \u002F\u002F 2 (lockstep option)\n        bool lockstep;          \u002F\u002F Yes (ASIL-D)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 8192 KB\n        uint32_t ram_kb;        \u002F\u002F 1024 KB\n        bool ecc;               \u002F\u002F Yes\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 8x CAN-FD\n        uint8_t lin;            \u002F\u002F 8x LIN\n        uint8_t ethernet_100m;  \u002F\u002F 2x 100BASE-T1\n        uint8_t flexray;        \u002F\u002F 2x FlexRay\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 4x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 48x PWM\n        uint8_t gpio;           \u002F\u002F 200+ GPIO\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-D\n    float cost_usd;             \u002F\u002F $28-35\n} RH850_U2A8_Spec_t;\n```\n\n**Use Cases:**\n- Front-center zone (HVAC, wipers)\n- Rear-center zone (trunk, tailgate)\n- Body domain consolidation\n- HVAC control\n\n#### Infineon AURIX TC397 (High-Performance)\n\n**TC397 Specifications:**\n```c\n\u002F\u002F Infineon AURIX TC397 - High-performance safety zone\ntypedef struct {\n    char model[32];\n    struct {\n        char core[16];          \u002F\u002F TriCore 1.8\n        uint32_t frequency_mhz; \u002F\u002F 300 MHz\n        uint8_t cores;          \u002F\u002F 3 lockstep pairs (6 total)\n        bool lockstep;          \u002F\u002F Yes (all cores)\n    } cpu;\n\n    struct {\n        uint32_t flash_kb;      \u002F\u002F 16384 KB\n        uint32_t ram_kb;        \u002F\u002F 1536 KB\n        bool ecc;               \u002F\u002F Yes (all memories)\n    } memory;\n\n    struct {\n        uint8_t can_fd;         \u002F\u002F 12x CAN-FD\n        uint8_t lin;            \u002F\u002F 4x LIN\n        uint8_t ethernet_1g;    \u002F\u002F 1x 1000BASE-T1\n        uint8_t flexray;        \u002F\u002F 2x FlexRay\n    } communication;\n\n    struct {\n        uint8_t adc_12bit;      \u002F\u002F 8x ADC (12-bit)\n        uint8_t pwm_channels;   \u002F\u002F 64x GTM PWM\n        uint8_t gpio;           \u002F\u002F 300+ GPIO\n        bool hss_drivers;       \u002F\u002F High-side switches\n        bool lss_drivers;       \u002F\u002F Low-side switches\n    } io;\n\n    uint8_t asil_rating;        \u002F\u002F ASIL-D\n    float cost_usd;             \u002F\u002F $65-90\n} TC397_Spec_t;\n```\n\n**Use Cases:**\n- Gateway\u002Fcentral controller\n- Safety-critical zones\n- ADAS integration point\n- Complex control algorithms\n\n### 2. Zone Controller Firmware Architecture\n\n```c\n\u002F\u002F Zone Controller Application Structure\ntypedef struct {\n    char zone_id[16];           \u002F\u002F \"FL_ZONE\", \"FR_ZONE\", etc.\n    uint8_t hardware_platform;  \u002F\u002F S32K3, RH850, AURIX\n    uint8_t asil_rating;        \u002F\u002F QM, ASIL-A\u002FB\u002FC\u002FD\n\n    \u002F\u002F I\u002FO Configuration\n    struct {\n        uint8_t num_digital_inputs;\n        uint8_t num_digital_outputs;\n        uint8_t num_analog_inputs;\n        uint8_t num_pwm_outputs;\n        uint8_t num_lin_slaves;\n    } io_config;\n\n    \u002F\u002F Communication\n    struct {\n        bool ethernet_enabled;\n        uint8_t can_channels;\n        uint8_t lin_channels;\n        uint16_t someip_port;\n    } comm_config;\n\n    \u002F\u002F Functions\n    void (*init)(void);\n    void (*cyclic_10ms)(void);\n    void (*cyclic_100ms)(void);\n    void (*handle_ethernet_rx)(uint8_t* data, uint16_t len);\n    void (*handle_lin_frame)(uint8_t node, uint8_t* data);\n} ZoneController_t;\n\n\u002F\u002F Example: Front-Left Zone Controller\nZoneController_t fl_zone = {\n    .zone_id = \"FL_ZONE\",\n    .hardware_platform = HW_S32K344,\n    .asil_rating = ASIL_B,\n\n    .io_config = {\n        .num_digital_inputs = 20,   \u002F\u002F Door switches, buttons\n        .num_digital_outputs = 12,  \u002F\u002F Relays, LEDs\n        .num_analog_inputs = 4,     \u002F\u002F Temperature sensors\n        .num_pwm_outputs = 8,       \u002F\u002F Headlight dimming, motor control\n        .num_lin_slaves = 4         \u002F\u002F Window motor, mirror motors\n    },\n\n    .comm_config = {\n        .ethernet_enabled = true,\n        .can_channels = 2,          \u002F\u002F CAN1: vehicle bus, CAN2: diagnostics\n        .lin_channels = 2,          \u002F\u002F LIN1: windows, LIN2: mirrors\n        .someip_port = 30500\n    },\n\n    .init = FL_Zone_Init,\n    .cyclic_10ms = FL_Zone_Cyclic10ms,\n    .cyclic_100ms = FL_Zone_Cyclic100ms,\n    .handle_ethernet_rx = FL_Zone_EthernetRx,\n    .handle_lin_frame = FL_Zone_LinRx\n};\n```\n\n### 3. Sensor Aggregation\n\n```c\n\u002F\u002F Sensor Aggregation for Zone Controller\ntypedef struct {\n    uint32_t timestamp_ms;\n    float value;\n    uint8_t quality;  \u002F\u002F 0=Invalid, 1=Questionable, 2=Good, 3=Excellent\n    uint8_t source;   \u002F\u002F Sensor ID\n} SensorValue_t;\n\ntypedef struct {\n    char sensor_name[32];\n    uint8_t num_sources;        \u002F\u002F Number of redundant sensors\n    SensorValue_t values[4];    \u002F\u002F Up to 4 redundant sources\n    float fused_value;          \u002F\u002F Fused result\n    uint8_t fusion_algorithm;   \u002F\u002F AVERAGE, MEDIAN, VOTER, KALMAN\n} SensorAggregator_t;\n\n\u002F\u002F Sensor fusion algorithms\nfloat sensor_fusion_average(SensorAggregator_t* agg) {\n    float sum = 0.0;\n    uint8_t count = 0;\n\n    for (uint8_t i = 0; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality >= 2) {  \u002F\u002F Good or Excellent\n            sum += agg->values[i].value;\n            count++;\n        }\n    }\n\n    return (count > 0) ? (sum \u002F count) : 0.0;\n}\n\nfloat sensor_fusion_median(SensorAggregator_t* agg) {\n    float sorted[4];\n    uint8_t count = 0;\n\n    \u002F\u002F Copy valid values\n    for (uint8_t i = 0; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality >= 2) {\n            sorted[count++] = agg->values[i].value;\n        }\n    }\n\n    if (count == 0) return 0.0;\n\n    \u002F\u002F Bubble sort\n    for (uint8_t i = 0; i \u003C count - 1; i++) {\n        for (uint8_t j = 0; j \u003C count - i - 1; j++) {\n            if (sorted[j] > sorted[j + 1]) {\n                float temp = sorted[j];\n                sorted[j] = sorted[j + 1];\n                sorted[j + 1] = temp;\n            }\n        }\n    }\n\n    \u002F\u002F Return median\n    if (count % 2 == 0) {\n        return (sorted[count \u002F 2 - 1] + sorted[count \u002F 2]) \u002F 2.0;\n    } else {\n        return sorted[count \u002F 2];\n    }\n}\n\n\u002F\u002F 2-out-of-3 voter\nfloat sensor_fusion_voter(SensorAggregator_t* agg) {\n    if (agg->num_sources \u003C 2) return agg->values[0].value;\n\n    \u002F\u002F Check if any two sensors agree within tolerance\n    const float tolerance = 0.05;  \u002F\u002F 5% tolerance\n\n    for (uint8_t i = 0; i \u003C agg->num_sources - 1; i++) {\n        for (uint8_t j = i + 1; j \u003C agg->num_sources; j++) {\n            float diff = fabs(agg->values[i].value - agg->values[j].value);\n            float avg = (agg->values[i].value + agg->values[j].value) \u002F 2.0;\n\n            if (diff \u002F avg \u003C tolerance) {\n                return avg;  \u002F\u002F Two sensors agree\n            }\n        }\n    }\n\n    \u002F\u002F No agreement - use sensor with best quality\n    uint8_t best_idx = 0;\n    for (uint8_t i = 1; i \u003C agg->num_sources; i++) {\n        if (agg->values[i].quality > agg->values[best_idx].quality) {\n            best_idx = i;\n        }\n    }\n\n    return agg->values[best_idx].value;\n}\n\n\u002F\u002F Example: Temperature sensor aggregation\nSensorAggregator_t temp_sensor = {\n    .sensor_name = \"AmbientTemperature\",\n    .num_sources = 3,\n    .values = {\n        {.timestamp_ms = 1000, .value = 23.5, .quality = 3, .source = 1},\n        {.timestamp_ms = 1000, .value = 23.7, .quality = 3, .source = 2},\n        {.timestamp_ms = 1000, .value = 23.6, .quality = 2, .source = 3}\n    },\n    .fusion_algorithm = FUSION_MEDIAN\n};\n\n\u002F\u002F Perform fusion\ntemp_sensor.fused_value = sensor_fusion_median(&temp_sensor);\n\u002F\u002F Result: 23.6°C\n```\n\n### 4. Actuator Control\n\n```c\n\u002F\u002F PWM-based actuator control (e.g., headlight dimming)\ntypedef struct {\n    char actuator_name[32];\n    uint8_t pwm_channel;\n    uint16_t frequency_hz;      \u002F\u002F PWM frequency\n    uint8_t duty_cycle;         \u002F\u002F 0-100%\n    bool enabled;\n} PWM_Actuator_t;\n\nvoid set_headlight_brightness(PWM_Actuator_t* headlight, uint8_t brightness_pct) {\n    \u002F\u002F Limit to valid range\n    if (brightness_pct > 100) brightness_pct = 100;\n\n    headlight->duty_cycle = brightness_pct;\n\n    \u002F\u002F Update hardware PWM register (example for S32K3)\n    eMIOS_SetDutyCycle(headlight->pwm_channel, brightness_pct);\n}\n\n\u002F\u002F LIN-based actuator control (e.g., window motor)\ntypedef struct {\n    uint8_t lin_channel;\n    uint8_t node_address;\n    enum {\n        WINDOW_STOP = 0,\n        WINDOW_UP = 1,\n        WINDOW_DOWN = 2\n    } command;\n    uint8_t position_pct;       \u002F\u002F 0=closed, 100=fully open\n} LIN_WindowMotor_t;\n\nvoid control_window(LIN_WindowMotor_t* window, uint8_t target_position) {\n    uint8_t lin_frame[8];\n\n    \u002F\u002F Build LIN frame\n    lin_frame[0] = window->node_address;\n    lin_frame[1] = (target_position > window->position_pct) ? WINDOW_UP : WINDOW_DOWN;\n    lin_frame[2] = target_position;\n\n    \u002F\u002F Send LIN frame\n    LIN_SendFrame(window->lin_channel, lin_frame, 3);\n\n    \u002F\u002F Update state\n    window->position_pct = target_position;\n}\n```\n\n### 5. Gateway Functions\n\n```c\n\u002F\u002F Gateway functionality (message routing, filtering, security)\ntypedef struct {\n    uint8_t src_network;    \u002F\u002F CAN, LIN, Ethernet\n    uint8_t dst_network;\n    uint32_t msg_id;        \u002F\u002F CAN ID or SOME\u002FIP service ID\n    bool translate;         \u002F\u002F Needs translation (CAN\u003C->Ethernet)\n    bool secure;            \u002F\u002F Requires MACsec\u002Fauthentication\n} GatewayRoute_t;\n\n\u002F\u002F Routing table\nGatewayRoute_t routing_table[] = {\n    \u002F\u002F CAN → Ethernet\n    {.src_network = NET_CAN1, .dst_network = NET_ETH, .msg_id = 0x123, .translate = true, .secure = false},\n    \u002F\u002F Ethernet → CAN\n    {.src_network = NET_ETH, .dst_network = NET_CAN2, .msg_id = 0x12340001, .translate = true, .secure = true},\n    \u002F\u002F LIN → Ethernet\n    {.src_network = NET_LIN1, .dst_network = NET_ETH, .msg_id = 0x3C, .translate = true, .secure = false}\n};\n\nvoid gateway_route_message(uint8_t src_net, uint32_t msg_id, uint8_t* data, uint16_t len) {\n    \u002F\u002F Find routing rule\n    for (uint8_t i = 0; i \u003C sizeof(routing_table) \u002F sizeof(GatewayRoute_t); i++) {\n        if (routing_table[i].src_network == src_net &&\n            routing_table[i].msg_id == msg_id) {\n\n            if (routing_table[i].translate) {\n                \u002F\u002F Translate message format\n                if (src_net == NET_CAN1 && routing_table[i].dst_network == NET_ETH) {\n                    translate_can_to_someip(msg_id, data, len);\n                } else if (src_net == NET_ETH && routing_table[i].dst_network == NET_CAN1) {\n                    translate_someip_to_can(msg_id, data, len);\n                }\n            }\n\n            if (routing_table[i].secure) {\n                \u002F\u002F Apply security (MACsec, authentication)\n                apply_security(data, len);\n            }\n\n            \u002F\u002F Forward to destination network\n            forward_message(routing_table[i].dst_network, data, len);\n            break;\n        }\n    }\n}\n```\n\n### 6. AUTOSAR Integration\n\n```c\n\u002F\u002F AUTOSAR Classic BSW configuration for zone controller\n\u002F\u002F RTE (Runtime Environment) configuration\n\n\u002F\u002F Sender-Receiver Interface\nRte_Write_HeadlightBrightness(uint8_t brightness) {\n    \u002F\u002F Implemented by RTE generator\n    \u002F\u002F Routes to SOME\u002FIP or CAN\n}\n\nRte_Read_DoorStatus(boolean* isOpen) {\n    \u002F\u002F Read from sensor via RTE\n    *isOpen = gpio_read(DOOR_SWITCH_PIN);\n    return RTE_E_OK;\n}\n\n\u002F\u002F Cyclic runnable (10ms task)\nvoid Zone_Controller_10ms_Runnable(void) {\n    boolean door_open;\n    uint8_t brightness;\n\n    \u002F\u002F Read inputs\n    Rte_Read_DoorStatus(&door_open);\n\n    \u002F\u002F Control logic\n    if (door_open) {\n        brightness = 100;  \u002F\u002F Full brightness when door open\n    } else {\n        brightness = get_adaptive_brightness();  \u002F\u002F Adaptive based on ambient light\n    }\n\n    \u002F\u002F Write outputs\n    Rte_Write_HeadlightBrightness(brightness);\n}\n```\n\n## Performance Targets\n\n| Function | Cycle Time | CPU Load | Memory |\n|----------|-----------|----------|--------|\n| I\u002FO scan | 10 ms | \u003C5% | 10 KB |\n| Sensor aggregation | 100 ms | \u003C10% | 20 KB |\n| Gateway routing | \u003C1 ms | \u003C15% | 50 KB |\n| SOME\u002FIP handling | Event-driven | \u003C20% | 100 KB |\n| Safety monitoring | 10 ms | \u003C10% | 30 KB |\n\n## Tools & Development Environment\n\n- **NXP S32 Design Studio** - IDE for S32K3 development\n- **Renesas CS+ \u002F e² studio** - IDE for RH850 development\n- **Infineon AURIX Development Studio** - IDE for TC397\n- **Vector DaVinci Configurator** - AUTOSAR BSW configuration\n- **EB tresos Studio** - AUTOSAR configuration (Elektrobit)\n- **PCAN-View** - CAN\u002FLIN debugging\n- **Wireshark** - Ethernet debugging\n\n## References\n\n- NXP S32K3 Reference Manual\n- Renesas RH850\u002FU2A User's Manual\n- Infineon AURIX TC3xx User Manual\n- AUTOSAR Adaptive Platform R22-11\n- LIN Specification 2.2A\n",{"name":5,"tags":23,"description":25},[24,5],"automotive","Automotive Zonal expertise. Covers 5 topics: Automotive Ethernet, Network Security Zonal, Service Oriented Communication, Zonal Architecture Design, Zone Controller Development.\n","main","764e05645935fe0d4c219ab3786883289700a063","skills\u002Fautomotive-zonal",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-zonal",{"tool":39,"command":40},"bunx","bunx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-zonal",{"tool":42,"command":43},"pnpm","pnpm dlx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-zonal","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-zonal\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",[],[]]