[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735WVXP30FS6Y9DV9HAFQC2":3,"skill-same:01M735WVXP30FS6Y9DV9HAFQC2":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},"01M735WVXP30FS6Y9DV9HAFQC2","automotive-sdv",null,"Automotive Sdv expertise. Covers 6 topics: Cloud Vehicle Integration, Containerized Vehicle Apps, Digital Twin Vehicles, Ota Update Systems, Vehicle App Stores.","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-sdv\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: automotive-sdv\ndescription: >\n  Automotive Sdv expertise. Covers 6 topics: Cloud Vehicle Integration, Containerized Vehicle Apps, Digital Twin Vehicles, Ota Update Systems, Vehicle App Stores.\ntags: [automotive, automotive-sdv]\n---\n\n# Automotive Sdv\n\n## Cloud Vehicle Integration\n\n# Cloud-Vehicle Integration — Connected Vehicle Platforms\n\nExpert knowledge of vehicle-to-cloud connectivity (MQTT, AMQP, HTTP\u002F2), telemetry streaming, remote diagnostics, cloud-based fleet management, and API gateways.\n\n## Core Concepts\n\n### Communication Protocols\n\n1. **MQTT**: Lightweight pub\u002Fsub for telemetry (Eclipse Mosquitto, AWS IoT Core)\n2. **AMQP**: Reliable message queuing (RabbitMQ, Azure Service Bus)\n3. **HTTP\u002F2**: RESTful APIs with server push\n4. **WebSocket**: Real-time bidirectional communication\n5. **gRPC**: High-performance RPC for services\n\n### Architecture Patterns\n\n- **Edge Computing**: Process data locally before cloud\n- **Digital Twin**: Virtual representation of vehicle in cloud\n- **Command & Control**: Remote vehicle operations\n- **Fleet Management**: Aggregate analytics across vehicles\n- **OTA Coordination**: Centralized update management\n\n## Production-Ready Implementation\n\n### 1. Vehicle Telemetry Client (Python\u002FMQTT)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle telemetry client using MQTT.\nStreams vehicle data to cloud platform with offline buffering.\n\"\"\"\n\nimport json\nimport time\nimport sqlite3\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\nfrom typing import Optional, List\nimport paho.mqtt.client as mqtt\nimport can\n\n\n@dataclass\nclass TelemetryMessage:\n    \"\"\"Vehicle telemetry data point.\"\"\"\n    vin: str\n    timestamp: str\n    message_type: str\n    data: dict\n\n\nclass VehicleTelemetryClient:\n    \"\"\"\n    MQTT-based telemetry client.\n\n    Features:\n    - Real-time telemetry streaming\n    - Offline buffering with SQLite\n    - Automatic reconnection\n    - QoS levels for reliability\n    - Compression for bandwidth optimization\n    \"\"\"\n\n    def __init__(self, config_path: str = \"\u002Fetc\u002Fvehicle\u002Ftelemetry-config.json\"):\n        self.config = self._load_config(config_path)\n        self.vin = self._get_vin()\n        self.mqtt_client = None\n        self.can_bus = None\n        self.offline_buffer = OfflineBuffer()\n        self.connected = False\n\n    def _load_config(self, path: str) -> dict:\n        \"\"\"Load configuration.\"\"\"\n        with open(path, 'r') as f:\n            return json.load(f)\n\n    def _get_vin(self) -> str:\n        \"\"\"Get vehicle VIN.\"\"\"\n        with open('\u002Fsys\u002Ffirmware\u002Fdevicetree\u002Fbase\u002Fserial-number', 'r') as f:\n            return f.read().strip()\n\n    def connect(self):\n        \"\"\"Connect to MQTT broker.\"\"\"\n        self.mqtt_client = mqtt.Client(\n            client_id=f\"vehicle-{self.vin}\",\n            clean_session=False,  # Maintain session across reconnects\n            protocol=mqtt.MQTTv5\n        )\n\n        # Set credentials\n        self.mqtt_client.username_pw_set(\n            self.config['mqtt_username'],\n            self.config['mqtt_password']\n        )\n\n        # Configure TLS\n        if self.config.get('mqtt_tls', True):\n            self.mqtt_client.tls_set(\n                ca_certs=self.config['mqtt_ca_cert'],\n                certfile=self.config.get('mqtt_client_cert'),\n                keyfile=self.config.get('mqtt_client_key')\n            )\n\n        # Set callbacks\n        self.mqtt_client.on_connect = self._on_connect\n        self.mqtt_client.on_disconnect = self._on_disconnect\n        self.mqtt_client.on_message = self._on_message\n        self.mqtt_client.on_publish = self._on_publish\n\n        # Set last will (notify cloud if vehicle disconnects unexpectedly)\n        self.mqtt_client.will_set(\n            f\"vehicles\u002F{self.vin}\u002Fstatus\",\n            payload=json.dumps({\n                \"status\": \"offline\",\n                \"timestamp\": datetime.utcnow().isoformat()\n            }),\n            qos=1,\n            retain=True\n        )\n\n        # Connect\n        print(f\"[Telemetry] Connecting to {self.config['mqtt_broker']}:{self.config['mqtt_port']}\")\n        self.mqtt_client.connect(\n            self.config['mqtt_broker'],\n            self.config['mqtt_port'],\n            keepalive=60\n        )\n\n        # Start network loop in background\n        self.mqtt_client.loop_start()\n\n    def _on_connect(self, client, userdata, flags, rc, properties=None):\n        \"\"\"Handle MQTT connection.\"\"\"\n        if rc == 0:\n            print(\"[Telemetry] Connected to MQTT broker\")\n            self.connected = True\n\n            # Publish online status\n            self.mqtt_client.publish(\n                f\"vehicles\u002F{self.vin}\u002Fstatus\",\n                payload=json.dumps({\n                    \"status\": \"online\",\n                    \"timestamp\": datetime.utcnow().isoformat(),\n                    \"sw_version\": self._get_software_version()\n                }),\n                qos=1,\n                retain=True\n            )\n\n            # Subscribe to command topics\n            self.mqtt_client.subscribe(f\"vehicles\u002F{self.vin}\u002Fcommands\u002F#\", qos=1)\n\n            # Send buffered messages\n            self._flush_offline_buffer()\n        else:\n            print(f\"[Telemetry] Connection failed: {rc}\")\n            self.connected = False\n\n    def _on_disconnect(self, client, userdata, rc):\n        \"\"\"Handle MQTT disconnection.\"\"\"\n        print(f\"[Telemetry] Disconnected from broker: {rc}\")\n        self.connected = False\n\n        if rc != 0:\n            print(\"[Telemetry] Unexpected disconnect, will reconnect\")\n\n    def _on_message(self, client, userdata, msg):\n        \"\"\"Handle incoming command messages.\"\"\"\n        print(f\"[Telemetry] Received command: {msg.topic}\")\n\n        try:\n            payload = json.loads(msg.payload.decode())\n            self._handle_command(msg.topic, payload)\n        except Exception as e:\n            print(f\"[Telemetry] Error processing command: {e}\")\n\n    def _on_publish(self, client, userdata, mid):\n        \"\"\"Handle successful publish.\"\"\"\n        # Remove from offline buffer if it was buffered\n        pass\n\n    def _handle_command(self, topic: str, payload: dict):\n        \"\"\"Handle remote commands from cloud.\"\"\"\n        command_type = topic.split('\u002F')[-1]\n\n        if command_type == \"diagnostics\":\n            # Trigger diagnostic data collection\n            print(\"[Telemetry] Starting diagnostic data collection\")\n            self._collect_diagnostics()\n\n        elif command_type == \"update\":\n            # Trigger OTA update check\n            print(\"[Telemetry] Checking for updates\")\n            # Integration with OTA system\n\n        elif command_type == \"lock\":\n            # Remote lock command\n            print(\"[Telemetry] Remote lock requested\")\n            self._remote_lock()\n\n        elif command_type == \"honk\":\n            # Remote horn activation\n            print(\"[Telemetry] Remote honk requested\")\n            self._remote_honk()\n\n    def publish_telemetry(self, message_type: str, data: dict, qos: int = 0):\n        \"\"\"\n        Publish telemetry message.\n\n        Args:\n            message_type: Type of telemetry (battery, location, speed, etc.)\n            data: Telemetry data\n            qos: MQTT QoS level (0, 1, or 2)\n        \"\"\"\n        msg = TelemetryMessage(\n            vin=self.vin,\n            timestamp=datetime.utcnow().isoformat(),\n            message_type=message_type,\n            data=data\n        )\n\n        topic = f\"vehicles\u002F{self.vin}\u002Ftelemetry\u002F{message_type}\"\n        payload = json.dumps(asdict(msg))\n\n        if self.connected:\n            result = self.mqtt_client.publish(topic, payload, qos=qos)\n\n            if result.rc == mqtt.MQTT_ERR_SUCCESS:\n                print(f\"[Telemetry] Published {message_type}\")\n            else:\n                print(f\"[Telemetry] Publish failed: {result.rc}\")\n                # Buffer for later\n                self.offline_buffer.store(topic, payload, qos)\n        else:\n            # Store in offline buffer\n            self.offline_buffer.store(topic, payload, qos)\n            print(f\"[Telemetry] Buffered {message_type} (offline)\")\n\n    def _flush_offline_buffer(self):\n        \"\"\"Send buffered messages when connection restored.\"\"\"\n        messages = self.offline_buffer.retrieve_all()\n        print(f\"[Telemetry] Flushing {len(messages)} buffered messages\")\n\n        for msg in messages:\n            self.mqtt_client.publish(msg['topic'], msg['payload'], qos=msg['qos'])\n            self.offline_buffer.delete(msg['id'])\n\n    def start_can_monitoring(self):\n        \"\"\"Start monitoring CAN bus and streaming telemetry.\"\"\"\n        print(\"[Telemetry] Starting CAN bus monitoring\")\n\n        # Connect to CAN bus\n        self.can_bus = can.interface.Bus(channel='can0', bustype='socketcan')\n\n        # Define telemetry intervals\n        intervals = {\n            'battery': 60,  # Every minute\n            'location': 300,  # Every 5 minutes\n            'speed': 10,  # Every 10 seconds\n            'diagnostics': 3600,  # Every hour\n        }\n\n        last_publish = {k: 0 for k in intervals.keys()}\n\n        while True:\n            # Read CAN messages\n            msg = self.can_bus.recv(timeout=1.0)\n\n            if msg is None:\n                continue\n\n            current_time = time.time()\n\n            # Process specific CAN IDs\n            if msg.arbitration_id == 0x123:  # Battery telemetry\n                if current_time - last_publish['battery'] >= intervals['battery']:\n                    battery_data = self._parse_battery_can(msg.data)\n                    self.publish_telemetry('battery', battery_data, qos=1)\n                    last_publish['battery'] = current_time\n\n            elif msg.arbitration_id == 0x456:  # Speed\u002Flocation\n                if current_time - last_publish['speed'] >= intervals['speed']:\n                    speed_data = self._parse_speed_can(msg.data)\n                    self.publish_telemetry('speed', speed_data, qos=0)\n                    last_publish['speed'] = current_time\n\n            # Periodic location publish\n            if current_time - last_publish['location'] >= intervals['location']:\n                location_data = self._get_gps_location()\n                self.publish_telemetry('location', location_data, qos=1)\n                last_publish['location'] = current_time\n\n    def _parse_battery_can(self, data: bytes) -> dict:\n        \"\"\"Parse battery telemetry from CAN message.\"\"\"\n        return {\n            'soc': int.from_bytes(data[0:2], 'big') \u002F 100,  # State of charge %\n            'voltage': int.from_bytes(data[2:4], 'big') \u002F 10,  # Volts\n            'current': int.from_bytes(data[4:6], 'big', signed=True) \u002F 10,  # Amps\n            'temperature': int.from_bytes(data[6:8], 'big') \u002F 10 - 40,  # Celsius\n        }\n\n    def _parse_speed_can(self, data: bytes) -> dict:\n        \"\"\"Parse speed telemetry from CAN message.\"\"\"\n        return {\n            'speed': int.from_bytes(data[0:2], 'big') \u002F 100,  # km\u002Fh\n            'odometer': int.from_bytes(data[2:6], 'big') \u002F 10,  # km\n        }\n\n    def _get_gps_location(self) -> dict:\n        \"\"\"Get GPS location from GNSS receiver.\"\"\"\n        # Read from gpsd or similar\n        return {\n            'latitude': 37.7749,\n            'longitude': -122.4194,\n            'altitude': 16.0,\n            'heading': 270.0,\n            'accuracy': 3.5\n        }\n\n    def _get_software_version(self) -> str:\n        \"\"\"Get vehicle software version.\"\"\"\n        with open('\u002Fetc\u002Fvehicle\u002Fversion', 'r') as f:\n            return f.read().strip()\n\n    def _collect_diagnostics(self):\n        \"\"\"Collect comprehensive diagnostic data.\"\"\"\n        diagnostics = {\n            'dtcs': [],  # Diagnostic Trouble Codes\n            'ecu_status': {},\n            'battery_health': {},\n            'sensor_status': {},\n        }\n\n        # Publish diagnostic report\n        self.publish_telemetry('diagnostics', diagnostics, qos=1)\n\n    def _remote_lock(self):\n        \"\"\"Execute remote lock command.\"\"\"\n        # Send CAN command to lock doors\n        pass\n\n    def _remote_honk(self):\n        \"\"\"Execute remote horn activation.\"\"\"\n        # Send CAN command to honk\n        pass\n\n    def disconnect(self):\n        \"\"\"Disconnect from MQTT broker.\"\"\"\n        if self.mqtt_client:\n            self.mqtt_client.loop_stop()\n            self.mqtt_client.disconnect()\n\n        if self.can_bus:\n            self.can_bus.shutdown()\n\n\nclass OfflineBuffer:\n    \"\"\"SQLite-based offline message buffer.\"\"\"\n\n    def __init__(self, db_path: str = \"\u002Fvar\u002Flib\u002Fvehicle\u002Ftelemetry-buffer.db\"):\n        self.db_path = db_path\n        self._init_db()\n\n    def _init_db(self):\n        \"\"\"Initialize SQLite database.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('''\n            CREATE TABLE IF NOT EXISTS buffer (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                topic TEXT NOT NULL,\n                payload TEXT NOT NULL,\n                qos INTEGER NOT NULL,\n                timestamp REAL NOT NULL\n            )\n        ''')\n\n        conn.commit()\n        conn.close()\n\n    def store(self, topic: str, payload: str, qos: int):\n        \"\"\"Store message in buffer.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute(\n            'INSERT INTO buffer (topic, payload, qos, timestamp) VALUES (?, ?, ?, ?)',\n            (topic, payload, qos, time.time())\n        )\n\n        conn.commit()\n        conn.close()\n\n    def retrieve_all(self) -> List[dict]:\n        \"\"\"Retrieve all buffered messages.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('SELECT id, topic, payload, qos FROM buffer ORDER BY timestamp')\n        rows = cursor.fetchall()\n\n        conn.close()\n\n        return [\n            {'id': row[0], 'topic': row[1], 'payload': row[2], 'qos': row[3]}\n            for row in rows\n        ]\n\n    def delete(self, msg_id: int):\n        \"\"\"Delete message from buffer.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('DELETE FROM buffer WHERE id = ?', (msg_id,))\n\n        conn.commit()\n        conn.close()\n\n\ndef main():\n    \"\"\"Main telemetry client loop.\"\"\"\n    client = VehicleTelemetryClient()\n\n    try:\n        client.connect()\n        client.start_can_monitoring()\n    except KeyboardInterrupt:\n        print(\"\\n[Telemetry] Shutting down\")\n        client.disconnect()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. Cloud Backend (AWS IoT Core Integration)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCloud backend for vehicle fleet management using AWS IoT Core.\n\"\"\"\n\nimport json\nimport boto3\nfrom datetime import datetime\nfrom typing import Dict, List\nfrom aws_iot_device_sdk import mqtt as mqtt5\nimport redis\n\n\nclass FleetManagementBackend:\n    \"\"\"\n    Fleet management backend.\n\n    Services:\n    - Receive telemetry from vehicles\n    - Store in time-series database\n    - Real-time analytics\n    - Remote command dispatch\n    \"\"\"\n\n    def __init__(self):\n        # AWS IoT Core client\n        self.iot_client = boto3.client('iot-data', region_name='us-west-2')\n\n        # DynamoDB for vehicle state\n        self.dynamodb = boto3.resource('dynamodb', region_name='us-west-2')\n        self.vehicle_table = self.dynamodb.Table('VehicleState')\n\n        # Timestream for telemetry\n        self.timestream = boto3.client('timestream-write', region_name='us-west-2')\n        self.ts_database = 'VehicleTelemetry'\n        self.ts_table = 'TelemetryData'\n\n        # Redis for real-time data\n        self.redis = redis.Redis(host='localhost', port=6379, decode_responses=True)\n\n    def process_telemetry(self, vin: str, message_type: str, data: dict):\n        \"\"\"\n        Process incoming telemetry message.\n\n        Args:\n            vin: Vehicle identification number\n            message_type: Type of telemetry\n            data: Telemetry data\n        \"\"\"\n        print(f\"[Fleet] Processing {message_type} from {vin}\")\n\n        # Update vehicle state in DynamoDB\n        self._update_vehicle_state(vin, message_type, data)\n\n        # Store in Timestream for historical analytics\n        self._store_timestream(vin, message_type, data)\n\n        # Cache in Redis for real-time queries\n        self._cache_redis(vin, message_type, data)\n\n        # Trigger alerts if necessary\n        self._check_alerts(vin, message_type, data)\n\n    def _update_vehicle_state(self, vin: str, message_type: str, data: dict):\n        \"\"\"Update vehicle state in DynamoDB.\"\"\"\n        self.vehicle_table.update_item(\n            Key={'vin': vin},\n            UpdateExpression=f'SET {message_type} = :data, last_update = :timestamp',\n            ExpressionAttributeValues={\n                ':data': data,\n                ':timestamp': datetime.utcnow().isoformat()\n            }\n        )\n\n    def _store_timestream(self, vin: str, message_type: str, data: dict):\n        \"\"\"Store telemetry in AWS Timestream.\"\"\"\n        records = []\n\n        for key, value in data.items():\n            records.append({\n                'Time': str(int(datetime.utcnow().timestamp() * 1000)),\n                'TimeUnit': 'MILLISECONDS',\n                'Dimensions': [\n                    {'Name': 'vin', 'Value': vin},\n                    {'Name': 'message_type', 'Value': message_type},\n                ],\n                'MeasureName': key,\n                'MeasureValue': str(value),\n                'MeasureValueType': 'DOUBLE' if isinstance(value, float) else 'BIGINT'\n            })\n\n        try:\n            self.timestream.write_records(\n                DatabaseName=self.ts_database,\n                TableName=self.ts_table,\n                Records=records\n            )\n        except Exception as e:\n            print(f\"[Fleet] Timestream write error: {e}\")\n\n    def _cache_redis(self, vin: str, message_type: str, data: dict):\n        \"\"\"Cache latest telemetry in Redis.\"\"\"\n        key = f\"vehicle:{vin}:{message_type}\"\n        self.redis.setex(key, 3600, json.dumps(data))  # 1 hour TTL\n\n    def _check_alerts(self, vin: str, message_type: str, data: dict):\n        \"\"\"Check for alert conditions.\"\"\"\n        if message_type == 'battery':\n            # Low battery alert\n            if data.get('soc', 100) \u003C 20:\n                self._send_alert(vin, 'low_battery', f\"Battery at {data['soc']}%\")\n\n            # High temperature alert\n            if data.get('temperature', 0) > 50:\n                self._send_alert(vin, 'high_temperature',\n                               f\"Battery temp: {data['temperature']}°C\")\n\n        elif message_type == 'diagnostics':\n            # DTC alert\n            if data.get('dtcs'):\n                self._send_alert(vin, 'diagnostic_codes',\n                               f\"DTCs: {', '.join(data['dtcs'])}\")\n\n    def _send_alert(self, vin: str, alert_type: str, message: str):\n        \"\"\"Send alert to monitoring system.\"\"\"\n        print(f\"[Fleet] ALERT - {vin}: {alert_type} - {message}\")\n\n        # Send to SNS topic\n        sns = boto3.client('sns', region_name='us-west-2')\n        sns.publish(\n            TopicArn='arn:aws:sns:us-west-2:123456789012:vehicle-alerts',\n            Subject=f\"Vehicle Alert: {alert_type}\",\n            Message=f\"VIN: {vin}\\nType: {alert_type}\\nMessage: {message}\"\n        )\n\n    def send_command(self, vin: str, command: str, params: dict = None):\n        \"\"\"\n        Send command to vehicle.\n\n        Args:\n            vin: Vehicle identification number\n            command: Command type (lock, unlock, honk, update)\n            params: Command parameters\n        \"\"\"\n        topic = f\"vehicles\u002F{vin}\u002Fcommands\u002F{command}\"\n        payload = json.dumps(params or {})\n\n        print(f\"[Fleet] Sending command to {vin}: {command}\")\n\n        try:\n            self.iot_client.publish(\n                topic=topic,\n                qos=1,\n                payload=payload\n            )\n\n            # Log command\n            self._log_command(vin, command, params)\n\n        except Exception as e:\n            print(f\"[Fleet] Command send error: {e}\")\n\n    def _log_command(self, vin: str, command: str, params: dict):\n        \"\"\"Log command to DynamoDB.\"\"\"\n        commands_table = self.dynamodb.Table('VehicleCommands')\n\n        commands_table.put_item(\n            Item={\n                'vin': vin,\n                'timestamp': datetime.utcnow().isoformat(),\n                'command': command,\n                'params': params or {},\n                'status': 'sent'\n            }\n        )\n\n    def get_vehicle_state(self, vin: str) -> Dict:\n        \"\"\"Get current vehicle state.\"\"\"\n        response = self.vehicle_table.get_item(Key={'vin': vin})\n        return response.get('Item', {})\n\n    def get_fleet_status(self) -> List[Dict]:\n        \"\"\"Get status of entire fleet.\"\"\"\n        response = self.vehicle_table.scan()\n        return response.get('Items', [])\n\n    def query_telemetry_history(self, vin: str, metric: str,\n                                start_time: datetime, end_time: datetime) -> List[Dict]:\n        \"\"\"Query historical telemetry from Timestream.\"\"\"\n        query_client = boto3.client('timestream-query', region_name='us-west-2')\n\n        query = f\"\"\"\n        SELECT time, measure_value::double as value\n        FROM \"{self.ts_database}\".\"{self.ts_table}\"\n        WHERE vin = '{vin}'\n          AND measure_name = '{metric}'\n          AND time BETWEEN from_iso8601_timestamp('{start_time.isoformat()}')\n                       AND from_iso8601_timestamp('{end_time.isoformat()}')\n        ORDER BY time DESC\n        \"\"\"\n\n        try:\n            response = query_client.query(QueryString=query)\n\n            results = []\n            for row in response['Rows']:\n                results.append({\n                    'time': row['Data'][0]['ScalarValue'],\n                    'value': float(row['Data'][1]['ScalarValue'])\n                })\n\n            return results\n\n        except Exception as e:\n            print(f\"[Fleet] Query error: {e}\")\n            return []\n```\n\n### 3. API Gateway (FastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nFleet management API gateway.\nRESTful API for vehicle operations and telemetry queries.\n\"\"\"\n\nfrom fastapi import FastAPI, HTTPException, Depends, Security\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\nfrom pydantic import BaseModel\nfrom datetime import datetime\nfrom typing import List, Optional\n\n\napp = FastAPI(title=\"Fleet Management API\", version=\"2.0.0\")\nsecurity = HTTPBearer()\n\n# Initialize backend\nbackend = FleetManagementBackend()\n\n\nclass CommandRequest(BaseModel):\n    \"\"\"Remote command request.\"\"\"\n    command: str\n    params: Optional[dict] = None\n\n\nclass TelemetryQuery(BaseModel):\n    \"\"\"Telemetry query parameters.\"\"\"\n    metric: str\n    start_time: datetime\n    end_time: datetime\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fvehicles\")\nasync def list_vehicles(credentials: HTTPAuthorizationCredentials = Security(security)):\n    \"\"\"List all vehicles in fleet.\"\"\"\n    fleet = backend.get_fleet_status()\n    return {\"vehicles\": fleet, \"count\": len(fleet)}\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\")\nasync def get_vehicle(vin: str, credentials: HTTPAuthorizationCredentials = Security(security)):\n    \"\"\"Get vehicle state.\"\"\"\n    state = backend.get_vehicle_state(vin)\n\n    if not state:\n        raise HTTPException(status_code=404, detail=\"Vehicle not found\")\n\n    return state\n\n\n@app.post(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\u002Fcommands\")\nasync def send_command(\n    vin: str,\n    request: CommandRequest,\n    credentials: HTTPAuthorizationCredentials = Security(security)\n):\n    \"\"\"Send command to vehicle.\"\"\"\n    backend.send_command(vin, request.command, request.params)\n    return {\"message\": \"Command sent\", \"vin\": vin, \"command\": request.command}\n\n\n@app.post(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\u002Ftelemetry\u002Fquery\")\nasync def query_telemetry(\n    vin: str,\n    query: TelemetryQuery,\n    credentials: HTTPAuthorizationCredentials = Security(security)\n):\n    \"\"\"Query historical telemetry data.\"\"\"\n    results = backend.query_telemetry_history(\n        vin,\n        query.metric,\n        query.start_time,\n        query.end_time\n    )\n\n    return {\"vin\": vin, \"metric\": query.metric, \"data\": results}\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### 4. Terraform Infrastructure (AWS)\n\n```hcl\n# File: terraform\u002Fmain.tf\n# AWS IoT Core infrastructure for vehicle fleet\n\nterraform {\n  required_providers {\n    aws = {\n      source  = \"hashicorp\u002Faws\"\n      version = \"~> 5.0\"\n    }\n  }\n}\n\nprovider \"aws\" {\n  region = var.aws_region\n}\n\n# IoT Core Thing Type for Vehicles\nresource \"aws_iot_thing_type\" \"vehicle\" {\n  name = \"VehicleType\"\n\n  properties {\n    description           = \"Connected vehicle\"\n    searchable_attributes = [\"vin\", \"model\", \"year\"]\n  }\n}\n\n# IoT Policy for Vehicle\nresource \"aws_iot_policy\" \"vehicle_policy\" {\n  name = \"VehiclePolicy\"\n\n  policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Connect\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:client\u002Fvehicle-*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Publish\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topic\u002Fvehicles\u002F*\u002Ftelemetry\u002F*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Subscribe\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topicfilter\u002Fvehicles\u002F*\u002Fcommands\u002F*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Receive\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topic\u002Fvehicles\u002F*\u002Fcommands\u002F*\"\n      }\n    ]\n  })\n}\n\n# DynamoDB Table for Vehicle State\nresource \"aws_dynamodb_table\" \"vehicle_state\" {\n  name           = \"VehicleState\"\n  billing_mode   = \"PAY_PER_REQUEST\"\n  hash_key       = \"vin\"\n\n  attribute {\n    name = \"vin\"\n    type = \"S\"\n  }\n\n  ttl {\n    attribute_name = \"ttl\"\n    enabled        = true\n  }\n\n  tags = {\n    Name = \"vehicle-state\"\n  }\n}\n\n# Timestream Database for Telemetry\nresource \"aws_timestreamwrite_database\" \"telemetry\" {\n  database_name = \"VehicleTelemetry\"\n}\n\nresource \"aws_timestreamwrite_table\" \"telemetry_data\" {\n  database_name = aws_timestreamwrite_database.telemetry.database_name\n  table_name    = \"TelemetryData\"\n\n  retention_properties {\n    memory_store_retention_period_in_hours  = 24\n    magnetic_store_retention_period_in_days = 365\n  }\n}\n\n# SNS Topic for Alerts\nresource \"aws_sns_topic\" \"vehicle_alerts\" {\n  name = \"vehicle-alerts\"\n}\n\n# IoT Rule to Route Telemetry\nresource \"aws_iot_topic_rule\" \"telemetry_rule\" {\n  name        = \"VehicleTelemetryRule\"\n  enabled     = true\n  sql         = \"SELECT * FROM 'vehicles\u002F+\u002Ftelemetry\u002F#'\"\n  sql_version = \"2016-03-23\"\n\n  timestream {\n    database_name = aws_timestreamwrite_database.telemetry.database_name\n    table_name    = aws_timestreamwrite_table.telemetry_data.table_name\n    role_arn      = aws_iam_role.iot_timestream_role.arn\n\n    dimension {\n      name  = \"vin\"\n      value = \"${topic(2)}\"\n    }\n\n    dimension {\n      name  = \"message_type\"\n      value = \"${topic(4)}\"\n    }\n  }\n\n  dynamodb_v2 {\n    role_arn = aws_iam_role.iot_dynamodb_role.arn\n    put_item {\n      table_name = aws_dynamodb_table.vehicle_state.name\n    }\n  }\n}\n\n# IAM Roles\nresource \"aws_iam_role\" \"iot_timestream_role\" {\n  name = \"IoTTimestreamRole\"\n\n  assume_role_policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Principal = {\n          Service = \"iot.amazonaws.com\"\n        }\n        Action = \"sts:AssumeRole\"\n      }\n    ]\n  })\n}\n\nresource \"aws_iam_role_policy\" \"iot_timestream_policy\" {\n  name = \"IoTTimestreamPolicy\"\n  role = aws_iam_role.iot_timestream_role.id\n\n  policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"timestream:WriteRecords\"\n        ]\n        Resource = aws_timestreamwrite_table.telemetry_data.arn\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"timestream:DescribeEndpoints\"\n        ]\n        Resource = \"*\"\n      }\n    ]\n  })\n}\n\ndata \"aws_caller_identity\" \"current\" {}\n\nvariable \"aws_region\" {\n  default = \"us-west-2\"\n}\n```\n\n## Real-World Examples\n\n### Tesla Cloud Architecture\n- **Real-time telemetry**: Battery, location, charging status\n- **Fleet learning**: Aggregate data for Autopilot improvement\n- **Remote commands**: Lock\u002Funlock, climate control, horn\u002Flights\n- **OTA coordination**: Staged rollout based on fleet data\n\n### Rivian Cloud Platform\n- **Adventure network**: Charging station availability\n- **Fleet Services**: Commercial fleet management for R1T\n- **Remote diagnostics**: Proactive service scheduling\n- **Gear Shop integration**: In-vehicle accessory ordering\n\n### VW.OS Cloud Services\n- **We Connect**: Remote vehicle services\n- **Charging optimization**: Route planning with charging stations\n- **Predictive maintenance**: AI-based service predictions\n- **Car-Net**: Emergency services integration\n\n## Best Practices\n\n1. **Use MQTT for telemetry**: Lightweight, efficient, pub\u002Fsub\n2. **Implement offline buffering**: Handle connectivity loss gracefully\n3. **QoS levels**: Critical data (QoS 1), non-critical (QoS 0)\n4. **TLS encryption**: Always use TLS 1.2+ for transport security\n5. **Rate limiting**: Prevent telemetry storms\n6. **Compression**: Reduce bandwidth usage\n7. **Edge processing**: Process data locally before cloud\n8. **Time-series database**: Use Timestream, InfluxDB, or TimescaleDB\n9. **Real-time cache**: Redis for low-latency queries\n10. **Command acknowledgment**: Require vehicle ACK for critical commands\n\n## Security Considerations\n\n- **Device authentication**: X.509 certificates per vehicle\n- **Message encryption**: TLS 1.2+ for transport\n- **Authorization**: Fine-grained permissions per VIN\n- **Audit logging**: Log all commands and access\n- **API rate limiting**: Prevent abuse\n- **Data retention**: GDPR-compliant data lifecycle\n- **Secure provisioning**: Certificate injection during manufacturing\n\n## References\n\n- **AWS IoT Core**: https:\u002F\u002Faws.amazon.com\u002Fiot-core\u002F\n- **Azure IoT Hub**: https:\u002F\u002Fazure.microsoft.com\u002Fen-us\u002Fproducts\u002Fiot-hub\u002F\n- **Eclipse Paho MQTT**: https:\u002F\u002Fwww.eclipse.org\u002Fpaho\u002F\n- **MQTT Specification**: https:\u002F\u002Fmqtt.org\u002F\n- **AMQP**: https:\u002F\u002Fwww.amqp.org\u002F\n\n---\n\n## Containerized Vehicle Apps\n\n# Containerized Vehicle Apps — Container Runtimes for Automotive\n\nExpert knowledge of container runtimes for automotive (Docker, Podman, containerd), manifest formats, resource limits, inter-container communication, and orchestration (Kubernetes, K3s).\n\n## Core Concepts\n\n### Container Runtimes for Automotive\n\n1. **containerd**: Lightweight, industry-standard container runtime\n2. **Docker**: Full container platform (heavier footprint)\n3. **Podman**: Daemonless, rootless containers\n4. **LXC\u002FLXD**: System containers for full OS isolation\n5. **Balena Engine**: IoT-optimized Docker fork\n\n### Why Containers in Vehicles?\n\n- **Isolation**: Apps can't interfere with critical systems\n- **Portability**: Same app runs on different vehicle models\n- **Updates**: Update apps without full system reflash\n- **Third-party apps**: Safe execution of untrusted code\n- **Resource control**: CPU, memory, network limits per app\n\n## Production-Ready Implementation\n\n### 1. Vehicle Container Runtime (containerd + systemd)\n\n```bash\n#!\u002Fbin\u002Fbash\n# File: setup-vehicle-container-runtime.sh\n# Setup containerd for automotive use\n\nset -e\n\necho \"[Setup] Installing containerd for vehicle platform\"\n\n# Install containerd\napt-get update\napt-get install -y containerd\n\n# Configure containerd for automotive\nmkdir -p \u002Fetc\u002Fcontainerd\ncat > \u002Fetc\u002Fcontainerd\u002Fconfig.toml \u003C\u003CEOF\nversion = 2\n\n# Root directory for containerd\nroot = \"\u002Fvar\u002Flib\u002Fcontainerd\"\nstate = \"\u002Frun\u002Fcontainerd\"\n\n# OCI runtime\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n  runtime_type = \"io.containerd.runc.v2\"\n\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc.options]\n  SystemdCgroup = true\n\n# Resource limits\n[plugins.\"io.containerd.grpc.v1.cri\".containerd]\n  default_runtime_name = \"runc\"\n\n# Registry configuration\n[plugins.\"io.containerd.grpc.v1.cri\".registry]\n  [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors]\n    [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"vehicle-registry.local:5000\"]\n      endpoint = [\"http:\u002F\u002Fvehicle-registry.local:5000\"]\n\n# CNI plugins for networking\n[plugins.\"io.containerd.grpc.v1.cri\".cni]\n  bin_dir = \"\u002Fopt\u002Fcni\u002Fbin\"\n  conf_dir = \"\u002Fetc\u002Fcni\u002Fnet.d\"\nEOF\n\n# Enable and start containerd\nsystemctl enable containerd\nsystemctl start containerd\n\n# Install CNI plugins\nmkdir -p \u002Fopt\u002Fcni\u002Fbin\ncurl -L https:\u002F\u002Fgithub.com\u002Fcontainernetworking\u002Fplugins\u002Freleases\u002Fdownload\u002Fv1.3.0\u002Fcni-plugins-linux-arm64-v1.3.0.tgz | \\\n  tar -C \u002Fopt\u002Fcni\u002Fbin -xz\n\n# Configure CNI networking\nmkdir -p \u002Fetc\u002Fcni\u002Fnet.d\ncat > \u002Fetc\u002Fcni\u002Fnet.d\u002F10-vehicle-bridge.conf \u003C\u003CEOF\n{\n  \"cniVersion\": \"1.0.0\",\n  \"name\": \"vehicle-bridge\",\n  \"type\": \"bridge\",\n  \"bridge\": \"veh0\",\n  \"isGateway\": true,\n  \"ipMasq\": true,\n  \"ipam\": {\n    \"type\": \"host-local\",\n    \"subnet\": \"10.88.0.0\u002F16\",\n    \"routes\": [\n      { \"dst\": \"0.0.0.0\u002F0\" }\n    ]\n  }\n}\nEOF\n\necho \"[Setup] Container runtime ready\"\n```\n\n### 2. App Manifest Format (OCI-compatible)\n\n```yaml\n# Vehicle app manifest (OCI-compatible)\n# File: spotify-app.yaml\n\napiVersion: vehicle.io\u002Fv1\nkind: VehicleApp\nmetadata:\n  name: spotify\n  namespace: infotainment\n  labels:\n    category: media\n    vendor: spotify\n    safety-critical: \"false\"\n\nspec:\n  # Container specification\n  container:\n    image: vehicle-registry.local:5000\u002Fspotify\u002Fautomotive:2.1.4\n    imagePullPolicy: IfNotPresent\n\n    # Resource limits\n    resources:\n      requests:\n        memory: \"256Mi\"\n        cpu: \"250m\"\n        storage: \"1Gi\"\n      limits:\n        memory: \"512Mi\"\n        cpu: \"500m\"\n        storage: \"2Gi\"\n        network:\n          bandwidth: \"10Mbps\"\n\n    # Security context\n    securityContext:\n      runAsUser: 1000\n      runAsGroup: 1000\n      readOnlyRootFilesystem: true\n      allowPrivilegeEscalation: false\n      capabilities:\n        drop:\n          - ALL\n        add:\n          - NET_BIND_SERVICE  # For network access\n\n    # Environment variables\n    env:\n      - name: API_KEY\n        valueFrom:\n          secretRef:\n            name: spotify-credentials\n            key: api-key\n      - name: VEHICLE_VIN\n        valueFrom:\n          fieldRef:\n            fieldPath: metadata.vin\n\n    # Volume mounts\n    volumeMounts:\n      - name: cache\n        mountPath: \u002Fapp\u002Fcache\n      - name: config\n        mountPath: \u002Fapp\u002Fconfig\n        readOnly: true\n      - name: dbus-socket\n        mountPath: \u002Fvar\u002Frun\u002Fdbus\n\n  # Volumes\n  volumes:\n    - name: cache\n      emptyDir:\n        sizeLimit: 500Mi\n    - name: config\n      configMap:\n        name: spotify-config\n    - name: dbus-socket\n      hostPath:\n        path: \u002Fvar\u002Frun\u002Fdbus\n        type: Socket\n\n  # Networking\n  networking:\n    ports:\n      - name: http\n        containerPort: 8080\n        protocol: TCP\n    hostNetwork: false\n    dnsPolicy: ClusterFirst\n\n  # Lifecycle hooks\n  lifecycle:\n    postStart:\n      exec:\n        command: [\"\u002Fapp\u002Fscripts\u002Fpost-start.sh\"]\n    preStop:\n      exec:\n        command: [\"\u002Fapp\u002Fscripts\u002Fgraceful-shutdown.sh\"]\n\n  # Health checks\n  livenessProbe:\n    httpGet:\n      path: \u002Fhealth\n      port: 8080\n    initialDelaySeconds: 10\n    periodSeconds: 30\n  readinessProbe:\n    httpGet:\n      path: \u002Fready\n      port: 8080\n    initialDelaySeconds: 5\n    periodSeconds: 10\n\n  # Service integration\n  services:\n    - name: media-player\n      type: dbus\n      interface: org.mpris.MediaPlayer2\n    - name: steering-controls\n      type: vehicle-bus\n      permissions: [read]\n\n  # Safety constraints\n  safety:\n    disableWhileDriving: false\n    touchLimit: true\n    requireVoiceControl: false\n    criticalityLevel: low\n\n  # Update strategy\n  updateStrategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxUnavailable: 1\n```\n\n### 3. Container Orchestrator (K3s for Automotive)\n\n```bash\n#!\u002Fbin\u002Fbash\n# File: install-k3s-automotive.sh\n# Install K3s (lightweight Kubernetes) for vehicle platform\n\nset -e\n\necho \"[K3s] Installing K3s for vehicle platform\"\n\n# Install K3s with automotive-specific configuration\ncurl -sfL https:\u002F\u002Fget.k3s.io | INSTALL_K3S_EXEC=\"server \\\n  --disable traefik \\\n  --disable servicelb \\\n  --disable local-storage \\\n  --write-kubeconfig-mode 644 \\\n  --kubelet-arg=max-pods=50 \\\n  --kubelet-arg=eviction-hard=memory.available\u003C100Mi \\\n  --kubelet-arg=eviction-soft=memory.available\u003C200Mi \\\n  --kubelet-arg=eviction-soft-grace-period=memory.available=1m \\\n  --kube-controller-manager-arg=node-monitor-period=10s \\\n  --kube-controller-manager-arg=node-monitor-grace-period=30s\" sh -\n\n# Wait for K3s to start\nsleep 10\n\n# Install vehicle-specific CRDs\ncat \u003C\u003CEOF | kubectl apply -f -\napiVersion: apiextensions.k8s.io\u002Fv1\nkind: CustomResourceDefinition\nmetadata:\n  name: vehicleapps.vehicle.io\nspec:\n  group: vehicle.io\n  versions:\n    - name: v1\n      served: true\n      storage: true\n      schema:\n        openAPIV3Schema:\n          type: object\n          properties:\n            spec:\n              type: object\n              properties:\n                container:\n                  type: object\n                safety:\n                  type: object\n                services:\n                  type: array\n  scope: Namespaced\n  names:\n    plural: vehicleapps\n    singular: vehicleapp\n    kind: VehicleApp\n    shortNames:\n      - vapp\nEOF\n\n# Create namespaces\nkubectl create namespace infotainment\nkubectl create namespace adas\nkubectl create namespace diagnostics\n\n# Install resource quotas\ncat \u003C\u003CEOF | kubectl apply -f -\napiVersion: v1\nkind: ResourceQuota\nmetadata:\n  name: infotainment-quota\n  namespace: infotainment\nspec:\n  hard:\n    requests.cpu: \"2\"\n    requests.memory: \"4Gi\"\n    persistentvolumeclaims: \"10\"\nEOF\n\necho \"[K3s] Installation complete\"\n```\n\n### 4. App Deployment Script (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle app deployment tool using containerd API.\n\"\"\"\n\nimport subprocess\nimport json\nimport yaml\nfrom pathlib import Path\nfrom typing import Dict\n\n\nclass VehicleAppDeployer:\n    \"\"\"Deploy containerized apps to vehicle platform.\"\"\"\n\n    def __init__(self, runtime: str = \"containerd\"):\n        self.runtime = runtime\n        self.namespace = \"vehicle-apps\"\n\n    def deploy_app(self, manifest_path: str):\n        \"\"\"\n        Deploy app from manifest.\n\n        Args:\n            manifest_path: Path to app manifest YAML\n        \"\"\"\n        with open(manifest_path, 'r') as f:\n            manifest = yaml.safe_load(f)\n\n        app_name = manifest['metadata']['name']\n        print(f\"[Deploy] Deploying {app_name}\")\n\n        # Pull container image\n        self._pull_image(manifest['spec']['container']['image'])\n\n        # Create namespace\n        self._create_namespace(manifest['metadata']['namespace'])\n\n        # Create container\n        container_id = self._create_container(manifest)\n\n        # Start container\n        self._start_container(container_id)\n\n        print(f\"[Deploy] {app_name} deployed successfully (ID: {container_id})\")\n\n    def _pull_image(self, image: str):\n        \"\"\"Pull container image.\"\"\"\n        print(f\"[Deploy] Pulling image: {image}\")\n\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"image\", \"pull\", image\n        ]\n\n        subprocess.run(cmd, check=True)\n\n    def _create_namespace(self, namespace: str):\n        \"\"\"Create containerd namespace.\"\"\"\n        # Containerd namespaces are created automatically on first use\n        pass\n\n    def _create_container(self, manifest: Dict) -> str:\n        \"\"\"Create container from manifest.\"\"\"\n        spec = manifest['spec']\n        metadata = manifest['metadata']\n\n        app_name = metadata['name']\n        image = spec['container']['image']\n\n        # Build OCI runtime spec\n        runtime_spec = self._build_runtime_spec(spec)\n\n        # Write spec to file\n        spec_path = f\"\u002Ftmp\u002F{app_name}-spec.json\"\n        with open(spec_path, 'w') as f:\n            json.dump(runtime_spec, f, indent=2)\n\n        # Create container\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"create\",\n            \"--runtime\", \"io.containerd.runc.v2\",\n            \"--config\", spec_path,\n            image,\n            app_name\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            raise RuntimeError(f\"Container creation failed: {result.stderr}\")\n\n        return app_name\n\n    def _build_runtime_spec(self, spec: Dict) -> Dict:\n        \"\"\"Build OCI runtime specification.\"\"\"\n        container = spec['container']\n        resources = container.get('resources', {})\n\n        # Parse resource limits\n        memory_limit = self._parse_memory(\n            resources.get('limits', {}).get('memory', '512Mi')\n        )\n        cpu_quota = self._parse_cpu(\n            resources.get('limits', {}).get('cpu', '500m')\n        )\n\n        # Build OCI spec\n        oci_spec = {\n            \"ociVersion\": \"1.0.2\",\n            \"process\": {\n                \"terminal\": False,\n                \"user\": {\n                    \"uid\": container.get('securityContext', {}).get('runAsUser', 1000),\n                    \"gid\": container.get('securityContext', {}).get('runAsGroup', 1000)\n                },\n                \"env\": self._build_env(container.get('env', [])),\n                \"cwd\": \"\u002Fapp\",\n                \"capabilities\": {\n                    \"bounding\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"effective\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"inheritable\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"permitted\": [\"CAP_NET_BIND_SERVICE\"]\n                },\n                \"rlimits\": [\n                    {\n                        \"type\": \"RLIMIT_NOFILE\",\n                        \"hard\": 1024,\n                        \"soft\": 1024\n                    }\n                ],\n                \"noNewPrivileges\": True\n            },\n            \"root\": {\n                \"path\": \"rootfs\",\n                \"readonly\": container.get('securityContext', {}).get(\n                    'readOnlyRootFilesystem', True\n                )\n            },\n            \"mounts\": self._build_mounts(spec.get('volumes', [])),\n            \"linux\": {\n                \"namespaces\": [\n                    {\"type\": \"pid\"},\n                    {\"type\": \"network\"},\n                    {\"type\": \"ipc\"},\n                    {\"type\": \"uts\"},\n                    {\"type\": \"mount\"}\n                ],\n                \"resources\": {\n                    \"memory\": {\n                        \"limit\": memory_limit\n                    },\n                    \"cpu\": {\n                        \"quota\": cpu_quota,\n                        \"period\": 100000\n                    }\n                },\n                \"cgroupsPath\": f\"\u002Fvehicle-apps\u002F{spec['container']['image'].split('\u002F')[-1]}\"\n            }\n        }\n\n        return oci_spec\n\n    def _build_env(self, env_vars: list) -> list:\n        \"\"\"Build environment variable list.\"\"\"\n        env = [\"PATH=\u002Fusr\u002Flocal\u002Fsbin:\u002Fusr\u002Flocal\u002Fbin:\u002Fusr\u002Fsbin:\u002Fusr\u002Fbin:\u002Fsbin:\u002Fbin\"]\n\n        for var in env_vars:\n            name = var['name']\n            value = var.get('value')\n\n            if value:\n                env.append(f\"{name}={value}\")\n            elif 'valueFrom' in var:\n                # Resolve from secret\u002Fconfigmap\n                # Simplified implementation\n                env.append(f\"{name}=\u003Cresolved-value>\")\n\n        return env\n\n    def _build_mounts(self, volumes: list) -> list:\n        \"\"\"Build mount list.\"\"\"\n        mounts = [\n            {\n                \"destination\": \"\u002Fproc\",\n                \"type\": \"proc\",\n                \"source\": \"proc\"\n            },\n            {\n                \"destination\": \"\u002Fdev\",\n                \"type\": \"tmpfs\",\n                \"source\": \"tmpfs\",\n                \"options\": [\"nosuid\", \"strictatime\", \"mode=755\", \"size=65536k\"]\n            },\n            {\n                \"destination\": \"\u002Fdev\u002Fpts\",\n                \"type\": \"devpts\",\n                \"source\": \"devpts\",\n                \"options\": [\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\"]\n            },\n            {\n                \"destination\": \"\u002Fsys\",\n                \"type\": \"sysfs\",\n                \"source\": \"sysfs\",\n                \"options\": [\"nosuid\", \"noexec\", \"nodev\", \"ro\"]\n            }\n        ]\n\n        # Add application-specific mounts\n        for volume in volumes:\n            if volume.get('emptyDir'):\n                mounts.append({\n                    \"destination\": \"\u002Fapp\u002Fcache\",\n                    \"type\": \"tmpfs\",\n                    \"source\": \"tmpfs\",\n                    \"options\": [\"nosuid\", \"nodev\"]\n                })\n            elif volume.get('hostPath'):\n                mounts.append({\n                    \"destination\": \"\u002Fvar\u002Frun\u002Fdbus\",\n                    \"type\": \"bind\",\n                    \"source\": volume['hostPath']['path'],\n                    \"options\": [\"rbind\", \"ro\"]\n                })\n\n        return mounts\n\n    def _start_container(self, container_id: str):\n        \"\"\"Start container.\"\"\"\n        print(f\"[Deploy] Starting container: {container_id}\")\n\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"task\", \"start\", \"-d\",\n            container_id\n        ]\n\n        subprocess.run(cmd, check=True)\n\n    def _parse_memory(self, mem_str: str) -> int:\n        \"\"\"Parse memory string to bytes.\"\"\"\n        units = {'Ki': 1024, 'Mi': 1024**2, 'Gi': 1024**3}\n\n        for unit, multiplier in units.items():\n            if mem_str.endswith(unit):\n                return int(mem_str[:-2]) * multiplier\n\n        return int(mem_str)\n\n    def _parse_cpu(self, cpu_str: str) -> int:\n        \"\"\"Parse CPU string to quota.\"\"\"\n        if cpu_str.endswith('m'):\n            millicores = int(cpu_str[:-1])\n            return millicores * 100  # quota in microseconds\n        else:\n            cores = float(cpu_str)\n            return int(cores * 100000)\n\n    def list_apps(self):\n        \"\"\"List deployed apps.\"\"\"\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"ls\"\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n        print(result.stdout)\n\n    def stop_app(self, app_name: str):\n        \"\"\"Stop running app.\"\"\"\n        print(f\"[Deploy] Stopping app: {app_name}\")\n\n        # Stop task\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"task\", \"kill\", app_name,\n            \"SIGTERM\"\n        ]\n\n        subprocess.run(cmd, check=False)\n\n    def remove_app(self, app_name: str):\n        \"\"\"Remove app.\"\"\"\n        print(f\"[Deploy] Removing app: {app_name}\")\n\n        # Delete container\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"rm\", app_name\n        ]\n\n        subprocess.run(cmd, check=True)\n\n\ndef main():\n    \"\"\"Main deployment script.\"\"\"\n    deployer = VehicleAppDeployer()\n\n    # Deploy app\n    deployer.deploy_app(\"spotify-app.yaml\")\n\n    # List apps\n    deployer.list_apps()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 5. Inter-Container Communication (D-Bus)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nD-Bus service for inter-container communication.\nAllows sandboxed apps to communicate with vehicle services.\n\"\"\"\n\nimport dbus\nimport dbus.service\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom gi.repository import GLib\n\n\nclass VehicleServiceBus(dbus.service.Object):\n    \"\"\"\n    D-Bus service for vehicle platform.\n\n    Provides APIs for apps to:\n    - Get vehicle state\n    - Control audio\n    - Receive user input (steering controls)\n    - Display notifications\n    \"\"\"\n\n    def __init__(self):\n        bus_name = dbus.service.BusName('com.vehicle.Platform',\n                                       bus=dbus.SystemBus())\n        dbus.service.Object.__init__(self, bus_name, '\u002Fcom\u002Fvehicle\u002FPlatform')\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='', out_signature='a{sv}')\n    def GetVehicleState(self):\n        \"\"\"Get current vehicle state.\"\"\"\n        return {\n            'speed': dbus.Double(65.0),  # km\u002Fh\n            'batterySoc': dbus.Double(75.0),  # %\n            'range': dbus.Double(300.0),  # km\n            'gear': dbus.String('D'),\n            'isMoving': dbus.Boolean(True)\n        }\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='s', out_signature='b')\n    def PlayAudio(self, url):\n        \"\"\"Play audio from URL.\"\"\"\n        print(f\"[D-Bus] Playing audio: {url}\")\n        # Integrate with vehicle audio system\n        return True\n\n    @dbus.service.signal('com.vehicle.Platform', signature='s')\n    def SteeringControlEvent(self, action):\n        \"\"\"Signal for steering control events.\"\"\"\n        print(f\"[D-Bus] Steering control: {action}\")\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='ss', out_signature='b')\n    def ShowNotification(self, title, message):\n        \"\"\"Display notification in vehicle cluster.\"\"\"\n        print(f\"[D-Bus] Notification: {title} - {message}\")\n        # Send to instrument cluster\n        return True\n\n\ndef main():\n    \"\"\"Start D-Bus service.\"\"\"\n    DBusGMainLoop(set_as_default=True)\n\n    service = VehicleServiceBus()\n    print(\"[D-Bus] Vehicle service bus started\")\n\n    # Run main loop\n    loop = GLib.MainLoop()\n    loop.run()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Real-World Examples\n\n### Tesla Container Strategy\n- **Native apps**: Tesla apps run directly on Linux (no containers yet)\n- **Future plans**: Exploring containers for third-party apps\n- **Steam integration**: Games run in isolated environment\n\n### GM Ultifi Platform\n- **Full container orchestration**: Kubernetes-based\n- **App marketplace**: Third-party containerized apps\n- **Resource isolation**: CPU\u002Fmemory limits per app\n- **OTA updates**: Update containers independently\n\n### Rivian App Platform\n- **Docker-based**: Uses Docker for app isolation\n- **Custom runtime**: Modified Docker daemon for automotive\n- **Safety constraints**: Apps can't access CAN bus directly\n- **Fleet deployment**: Kubernetes for managing app fleet\n\n### Android Automotive\n- **Container-like isolation**: APK sandboxing similar to containers\n- **Resource limits**: Memory\u002FCPU limits per app\n- **Permission model**: Fine-grained permissions\n- **Update mechanism**: Individual app updates\n\n## Best Practices\n\n1. **Use containerd**: Lightweight, industry-standard\n2. **Resource limits**: Always set CPU\u002Fmemory limits\n3. **Read-only root**: Immutable container filesystem\n4. **Drop capabilities**: Minimal Linux capabilities\n5. **Network isolation**: Isolate app network traffic\n6. **Health checks**: Liveness and readiness probes\n7. **Graceful shutdown**: Handle SIGTERM properly\n8. **Persistent data**: Use volumes for app data\n9. **Image scanning**: Scan images for vulnerabilities\n10. **Update strategy**: Rolling updates with rollback\n\n## Security Considerations\n\n- **User namespaces**: Run containers as non-root\n- **Seccomp profiles**: Restrict system calls\n- **AppArmor\u002FSELinux**: Mandatory access control\n- **Image signing**: Verify container image signatures\n- **Network policies**: Restrict inter-container communication\n- **Audit logging**: Log container lifecycle events\n- **Resource quotas**: Prevent resource exhaustion\n\n## References\n\n- **containerd**: https:\u002F\u002Fcontainerd.io\u002F\n- **OCI Runtime Spec**: https:\u002F\u002Fgithub.com\u002Fopencontainers\u002Fruntime-spec\n- **K3s**: https:\u002F\u002Fk3s.io\u002F\n- **Podman**: https:\u002F\u002Fpodman.io\u002F\n- **Balena Engine**: https:\u002F\u002Fwww.balena.io\u002Fengine\u002F\n\n---\n\n## Digital Twin Vehicles\n\n# Digital Twin Vehicles — Virtual Vehicle Representations\n\nExpert knowledge of digital twin architecture, real-time synchronization, simulation for testing, predictive maintenance, virtual testing environments, and CI\u002FCD for vehicle software.\n\n## Core Concepts\n\n### Digital Twin Architecture\n\n1. **Physical Twin**: Actual vehicle with sensors and actuators\n2. **Digital Twin**: Virtual representation in cloud\u002Fedge\n3. **Bi-directional Sync**: Real-time data flow both ways\n4. **Simulation Engine**: Physics-based vehicle model\n5. **Analytics Layer**: ML\u002FAI for predictions\n\n### Use Cases\n\n- **Predictive Maintenance**: Predict failures before they occur\n- **Virtual Testing**: Test software without physical vehicle\n- **Fleet Optimization**: Optimize routing, charging, maintenance\n- **Development**: Rapid prototyping and testing\n- **Training**: Train ML models on simulated data\n\n## Production-Ready Implementation\n\n### 1. Digital Twin Engine (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nDigital Twin Engine for vehicle simulation and synchronization.\n\"\"\"\n\nimport json\nimport time\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\nfrom typing import Dict, List, Optional\nimport numpy as np\nfrom scipy.integrate import odeint\nimport paho.mqtt.client as mqtt\n\n\n@dataclass\nclass VehicleState:\n    \"\"\"Complete vehicle state.\"\"\"\n    vin: str\n    timestamp: float\n\n    # Powertrain\n    battery_soc: float  # State of charge (%)\n    battery_voltage: float  # Volts\n    battery_current: float  # Amps\n    battery_temperature: float  # Celsius\n    motor_speed: float  # RPM\n    motor_torque: float  # Nm\n\n    # Dynamics\n    speed: float  # km\u002Fh\n    acceleration: float  # m\u002Fs^2\n    position: tuple  # (latitude, longitude)\n    heading: float  # degrees\n\n    # Environment\n    ambient_temperature: float  # Celsius\n    road_grade: float  # %\n\n    # Diagnostics\n    odometer: float  # km\n    energy_consumed: float  # kWh\n    regeneration_energy: float  # kWh\n\n\nclass VehiclePhysicsModel:\n    \"\"\"\n    Physics-based vehicle simulation model.\n\n    Models:\n    - Battery dynamics (charge\u002Fdischarge, thermal)\n    - Electric motor efficiency\n    - Vehicle dynamics (acceleration, drag, rolling resistance)\n    - Energy consumption\n    \"\"\"\n\n    def __init__(self, vehicle_params: dict):\n        self.params = vehicle_params\n\n        # Vehicle parameters\n        self.mass = vehicle_params['mass']  # kg\n        self.drag_coefficient = vehicle_params['drag_coefficient']  # Cd\n        self.frontal_area = vehicle_params['frontal_area']  # m^2\n        self.rolling_resistance = vehicle_params['rolling_resistance']  # Crr\n        self.wheel_radius = vehicle_params['wheel_radius']  # m\n\n        # Battery parameters\n        self.battery_capacity = vehicle_params['battery_capacity']  # kWh\n        self.battery_resistance = vehicle_params['battery_resistance']  # Ohms\n        self.battery_thermal_mass = vehicle_params['battery_thermal_mass']  # J\u002FK\n\n        # Motor parameters\n        self.motor_max_power = vehicle_params['motor_max_power']  # kW\n        self.motor_efficiency_map = vehicle_params['motor_efficiency_map']\n\n        # Constants\n        self.air_density = 1.225  # kg\u002Fm^3\n        self.gravity = 9.81  # m\u002Fs^2\n\n    def simulate_step(self, state: VehicleState, throttle: float,\n                     dt: float) -> VehicleState:\n        \"\"\"\n        Simulate one time step.\n\n        Args:\n            state: Current vehicle state\n            throttle: Throttle input (-1 to 1, negative for regen)\n            dt: Time step (seconds)\n\n        Returns:\n            Updated vehicle state\n        \"\"\"\n        # Convert speed to m\u002Fs\n        speed_mps = state.speed \u002F 3.6\n\n        # Calculate forces\n        drag_force = 0.5 * self.air_density * self.drag_coefficient * \\\n                     self.frontal_area * speed_mps**2\n\n        rolling_resistance_force = self.rolling_resistance * self.mass * \\\n                                  self.gravity * np.cos(np.radians(state.road_grade))\n\n        grade_force = self.mass * self.gravity * np.sin(np.radians(state.road_grade))\n\n        # Calculate required power\n        if throttle > 0:\n            # Acceleration\n            motor_torque = throttle * self._calculate_max_torque(state.motor_speed)\n            motor_power = motor_torque * state.motor_speed * 2 * np.pi \u002F 60 \u002F 1000  # kW\n\n            # Motor efficiency\n            efficiency = self._get_motor_efficiency(motor_power, state.motor_speed)\n            battery_power = motor_power \u002F efficiency\n\n        else:\n            # Regenerative braking\n            regen_power = abs(throttle) * self.motor_max_power * 0.7  # 70% max regen\n            battery_power = -regen_power * 0.85  # 85% regen efficiency\n            motor_power = -regen_power\n\n        # Battery dynamics\n        battery_current = battery_power * 1000 \u002F state.battery_voltage\n        voltage_drop = battery_current * self.battery_resistance\n        state.battery_voltage = self._calculate_ocv(state.battery_soc) - voltage_drop\n\n        # Energy consumed\u002Fregenerated\n        energy_delta = battery_power * dt \u002F 3600  # kWh\n        state.battery_soc -= (energy_delta \u002F self.battery_capacity) * 100\n\n        if battery_power > 0:\n            state.energy_consumed += energy_delta\n        else:\n            state.regeneration_energy += abs(energy_delta)\n\n        # Battery thermal model\n        heat_generation = battery_current**2 * self.battery_resistance  # Watts\n        cooling_rate = (state.battery_temperature - state.ambient_temperature) * 50  # W\n        temp_delta = (heat_generation - cooling_rate) * dt \u002F self.battery_thermal_mass\n        state.battery_temperature += temp_delta\n\n        # Vehicle dynamics\n        net_force = (motor_power * 1000 \u002F max(speed_mps, 0.1)) - \\\n                   drag_force - rolling_resistance_force - grade_force\n\n        acceleration = net_force \u002F self.mass\n        speed_mps += acceleration * dt\n        speed_mps = max(0, speed_mps)  # Can't go backwards\n\n        state.speed = speed_mps * 3.6  # Convert to km\u002Fh\n        state.acceleration = acceleration\n\n        # Update position (simplified)\n        distance_delta = speed_mps * dt \u002F 1000  # km\n        state.odometer += distance_delta\n\n        # Update motor state\n        state.motor_speed = speed_mps \u002F (2 * np.pi * self.wheel_radius) * 60  # RPM\n        state.motor_torque = motor_power * 1000 \u002F (state.motor_speed * 2 * np.pi \u002F 60) \\\n                           if state.motor_speed > 0 else 0\n\n        state.battery_current = battery_current\n        state.timestamp = time.time()\n\n        return state\n\n    def _calculate_max_torque(self, motor_speed: float) -> float:\n        \"\"\"Calculate maximum available torque at given speed.\"\"\"\n        if motor_speed \u003C 3000:\n            return 400  # Nm (constant torque region)\n        else:\n            # Constant power region\n            max_power = self.motor_max_power * 1000  # W\n            return max_power \u002F (motor_speed * 2 * np.pi \u002F 60)\n\n    def _get_motor_efficiency(self, power: float, speed: float) -> float:\n        \"\"\"Get motor efficiency from efficiency map.\"\"\"\n        # Simplified efficiency model\n        # In production, use lookup table\n        if power \u003C 0.1 * self.motor_max_power:\n            return 0.85\n        elif power \u003C 0.5 * self.motor_max_power:\n            return 0.93\n        elif power \u003C 0.8 * self.motor_max_power:\n            return 0.95\n        else:\n            return 0.92\n\n    def _calculate_ocv(self, soc: float) -> float:\n        \"\"\"Calculate open-circuit voltage from SOC.\"\"\"\n        # Simplified polynomial fit\n        # In production, use actual OCV curve\n        return 300 + 100 * (soc \u002F 100)\n\n\nclass DigitalTwin:\n    \"\"\"\n    Digital twin of vehicle with bi-directional synchronization.\n\n    Features:\n    - Real-time sync with physical vehicle\n    - Physics-based simulation\n    - Predictive analytics\n    - Virtual testing\n    \"\"\"\n\n    def __init__(self, vin: str, vehicle_params: dict, cloud_config: dict):\n        self.vin = vin\n        self.physics_model = VehiclePhysicsModel(vehicle_params)\n        self.cloud_config = cloud_config\n\n        # Initialize state\n        self.state = VehicleState(\n            vin=vin,\n            timestamp=time.time(),\n            battery_soc=100.0,\n            battery_voltage=400.0,\n            battery_current=0.0,\n            battery_temperature=25.0,\n            motor_speed=0.0,\n            motor_torque=0.0,\n            speed=0.0,\n            acceleration=0.0,\n            position=(0.0, 0.0),\n            heading=0.0,\n            ambient_temperature=25.0,\n            road_grade=0.0,\n            odometer=0.0,\n            energy_consumed=0.0,\n            regeneration_energy=0.0\n        )\n\n        # MQTT connection\n        self.mqtt_client = None\n        self.sync_enabled = True\n        self.simulation_mode = False\n\n        # Analytics\n        self.state_history = []\n        self.predictions = {}\n\n    def connect_to_cloud(self):\n        \"\"\"Connect to cloud platform for synchronization.\"\"\"\n        self.mqtt_client = mqtt.Client(client_id=f\"twin-{self.vin}\")\n\n        self.mqtt_client.username_pw_set(\n            self.cloud_config['mqtt_username'],\n            self.cloud_config['mqtt_password']\n        )\n\n        self.mqtt_client.on_connect = self._on_connect\n        self.mqtt_client.on_message = self._on_message\n\n        self.mqtt_client.connect(\n            self.cloud_config['mqtt_broker'],\n            self.cloud_config['mqtt_port']\n        )\n\n        self.mqtt_client.loop_start()\n\n    def _on_connect(self, client, userdata, flags, rc):\n        \"\"\"Handle MQTT connection.\"\"\"\n        print(f\"[Twin] Connected to cloud (VIN: {self.vin})\")\n\n        # Subscribe to physical vehicle telemetry\n        client.subscribe(f\"vehicles\u002F{self.vin}\u002Ftelemetry\u002F#\")\n\n        # Subscribe to commands\n        client.subscribe(f\"twins\u002F{self.vin}\u002Fcommands\u002F#\")\n\n    def _on_message(self, client, userdata, msg):\n        \"\"\"Handle incoming messages.\"\"\"\n        topic_parts = msg.topic.split('\u002F')\n\n        if 'telemetry' in topic_parts:\n            # Update from physical vehicle\n            self._sync_from_physical(json.loads(msg.payload))\n\n        elif 'commands' in topic_parts:\n            # Command from cloud\n            command = topic_parts[-1]\n            self._handle_command(command, json.loads(msg.payload))\n\n    def _sync_from_physical(self, telemetry: dict):\n        \"\"\"Synchronize state from physical vehicle.\"\"\"\n        if not self.sync_enabled:\n            return\n\n        print(f\"[Twin] Syncing from physical vehicle\")\n\n        # Update state from telemetry\n        message_type = telemetry.get('message_type')\n        data = telemetry.get('data', {})\n\n        if message_type == 'battery':\n            self.state.battery_soc = data.get('soc', self.state.battery_soc)\n            self.state.battery_voltage = data.get('voltage', self.state.battery_voltage)\n            self.state.battery_current = data.get('current', self.state.battery_current)\n            self.state.battery_temperature = data.get('temperature',\n                                                     self.state.battery_temperature)\n\n        elif message_type == 'speed':\n            self.state.speed = data.get('speed', self.state.speed)\n            self.state.odometer = data.get('odometer', self.state.odometer)\n\n        elif message_type == 'location':\n            self.state.position = (data.get('latitude', 0), data.get('longitude', 0))\n            self.state.heading = data.get('heading', self.state.heading)\n\n        # Publish updated twin state\n        self._publish_twin_state()\n\n    def _publish_twin_state(self):\n        \"\"\"Publish digital twin state to cloud.\"\"\"\n        if self.mqtt_client and self.mqtt_client.is_connected():\n            topic = f\"twins\u002F{self.vin}\u002Fstate\"\n            payload = json.dumps(asdict(self.state))\n            self.mqtt_client.publish(topic, payload, qos=0)\n\n    def run_simulation(self, drive_cycle: List[dict], dt: float = 0.1):\n        \"\"\"\n        Run simulation with given drive cycle.\n\n        Args:\n            drive_cycle: List of {'time': t, 'throttle': x, 'grade': y}\n            dt: Time step (seconds)\n        \"\"\"\n        print(f\"[Twin] Starting simulation (duration: {drive_cycle[-1]['time']}s)\")\n\n        self.simulation_mode = True\n        self.state_history = []\n\n        for i, cycle_point in enumerate(drive_cycle[:-1]):\n            next_point = drive_cycle[i + 1]\n\n            # Interpolate throttle\n            throttle = cycle_point['throttle']\n            self.state.road_grade = cycle_point.get('grade', 0)\n\n            # Simulate\n            self.state = self.physics_model.simulate_step(self.state, throttle, dt)\n\n            # Store history\n            self.state_history.append(asdict(self.state))\n\n            # Publish periodically\n            if i % 10 == 0:\n                self._publish_twin_state()\n\n            time.sleep(dt)\n\n        self.simulation_mode = False\n        print(f\"[Twin] Simulation complete\")\n\n        # Analyze results\n        self._analyze_simulation()\n\n    def _analyze_simulation(self):\n        \"\"\"Analyze simulation results.\"\"\"\n        if not self.state_history:\n            return\n\n        final_state = self.state_history[-1]\n\n        print(f\"\\n[Twin] Simulation Results:\")\n        print(f\"  Distance: {final_state['odometer']:.2f} km\")\n        print(f\"  Energy consumed: {final_state['energy_consumed']:.2f} kWh\")\n        print(f\"  Regeneration: {final_state['regeneration_energy']:.2f} kWh\")\n        print(f\"  Final SOC: {final_state['battery_soc']:.1f}%\")\n        print(f\"  Efficiency: {final_state['odometer'] \u002F final_state['energy_consumed']:.2f} km\u002FkWh\")\n\n    def predict_range(self) -> float:\n        \"\"\"\n        Predict remaining range based on current state and driving pattern.\n\n        Returns:\n            Predicted range in km\n        \"\"\"\n        # Simple model: current SOC * typical efficiency\n        # In production, use ML model trained on historical data\n\n        typical_efficiency = 5.0  # km\u002FkWh\n        remaining_energy = self.state.battery_soc \u002F 100 * self.physics_model.battery_capacity\n\n        predicted_range = remaining_energy * typical_efficiency\n\n        print(f\"[Twin] Predicted range: {predicted_range:.1f} km\")\n        return predicted_range\n\n    def predict_maintenance(self) -> Dict:\n        \"\"\"\n        Predict maintenance needs using anomaly detection.\n\n        Returns:\n            Dictionary of predicted maintenance items\n        \"\"\"\n        predictions = {\n            'battery_health': 95.0,  # %\n            'estimated_degradation': 5.0,  # %\n            'cycles_remaining': 1500,\n            'recommendations': []\n        }\n\n        # Check battery temperature trends\n        if len(self.state_history) > 100:\n            recent_temps = [s['battery_temperature'] for s in self.state_history[-100:]]\n            avg_temp = np.mean(recent_temps)\n\n            if avg_temp > 45:\n                predictions['recommendations'].append(\n                    \"Battery running hot. Check cooling system.\"\n                )\n\n        # Check energy consumption anomalies\n        if self.state.energy_consumed > 0:\n            efficiency = self.state.odometer \u002F self.state.energy_consumed\n\n            if efficiency \u003C 4.0:  # Below expected\n                predictions['recommendations'].append(\n                    \"Low efficiency detected. Check tire pressure and alignment.\"\n                )\n\n        return predictions\n\n    def _handle_command(self, command: str, params: dict):\n        \"\"\"Handle commands from cloud.\"\"\"\n        print(f\"[Twin] Received command: {command}\")\n\n        if command == 'simulate':\n            # Run simulation with provided drive cycle\n            drive_cycle = params.get('drive_cycle', [])\n            self.run_simulation(drive_cycle)\n\n        elif command == 'predict_range':\n            # Predict range\n            range_km = self.predict_range()\n            self.mqtt_client.publish(\n                f\"twins\u002F{self.vin}\u002Fpredictions\u002Frange\",\n                json.dumps({'range_km': range_km})\n            )\n\n        elif command == 'predict_maintenance':\n            # Predict maintenance\n            predictions = self.predict_maintenance()\n            self.mqtt_client.publish(\n                f\"twins\u002F{self.vin}\u002Fpredictions\u002Fmaintenance\",\n                json.dumps(predictions)\n            )\n\n    def export_state_history(self, filename: str):\n        \"\"\"Export state history to file for analysis.\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.state_history, f, indent=2)\n\n        print(f\"[Twin] State history exported to {filename}\")\n\n\n# Example usage\ndef main():\n    \"\"\"Example digital twin usage.\"\"\"\n\n    # Vehicle parameters (Tesla Model 3 Long Range approximate)\n    vehicle_params = {\n        'mass': 1847,  # kg\n        'drag_coefficient': 0.23,\n        'frontal_area': 2.22,  # m^2\n        'rolling_resistance': 0.01,\n        'wheel_radius': 0.368,  # m (18\" wheels)\n        'battery_capacity': 82,  # kWh\n        'battery_resistance': 0.05,  # Ohms\n        'battery_thermal_mass': 50000,  # J\u002FK\n        'motor_max_power': 258,  # kW (combined front+rear)\n        'motor_efficiency_map': {}\n    }\n\n    cloud_config = {\n        'mqtt_broker': 'mqtt.example.com',\n        'mqtt_port': 8883,\n        'mqtt_username': 'twin-client',\n        'mqtt_password': 'password'\n    }\n\n    # Create digital twin\n    twin = DigitalTwin('VIN123456789', vehicle_params, cloud_config)\n    twin.connect_to_cloud()\n\n    # Example drive cycle (WLTP-like)\n    drive_cycle = []\n    for t in range(0, 1800, 10):  # 30 minutes\n        if t \u003C 600:\n            throttle = 0.3  # City driving\n        elif t \u003C 1200:\n            throttle = 0.5  # Highway\n        else:\n            throttle = 0.2  # Slow down\n\n        drive_cycle.append({\n            'time': t,\n            'throttle': throttle,\n            'grade': 0\n        })\n\n    # Run simulation\n    twin.run_simulation(drive_cycle, dt=10.0)\n\n    # Predictions\n    twin.predict_range()\n    twin.predict_maintenance()\n\n    # Export data\n    twin.export_state_history('twin_history.json')\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. Azure Digital Twins Integration\n\n```yaml\n# Azure Digital Twins model definition (DTDL)\n# File: vehicle-model.json\n\n{\n  \"@context\": \"dtmi:dtdl:context;2\",\n  \"@id\": \"dtmi:com:example:Vehicle;1\",\n  \"@type\": \"Interface\",\n  \"displayName\": \"Electric Vehicle\",\n  \"contents\": [\n    {\n      \"@type\": \"Property\",\n      \"name\": \"vin\",\n      \"schema\": \"string\",\n      \"description\": \"Vehicle Identification Number\"\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"battery\",\n      \"schema\": {\n        \"@type\": \"Object\",\n        \"fields\": [\n          {\n            \"name\": \"soc\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"voltage\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"current\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"temperature\",\n            \"schema\": \"double\"\n          }\n        ]\n      }\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"location\",\n      \"schema\": \"geopoint\"\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"speed\",\n      \"schema\": \"double\"\n    },\n    {\n      \"@type\": \"Command\",\n      \"name\": \"predictRange\",\n      \"response\": {\n        \"name\": \"rangeResult\",\n        \"schema\": \"double\"\n      }\n    },\n    {\n      \"@type\": \"Command\",\n      \"name\": \"simulateDriveCycle\",\n      \"request\": {\n        \"name\": \"driveCycleData\",\n        \"schema\": \"string\"\n      }\n    }\n  ]\n}\n```\n\n### 3. CI\u002FCD Pipeline for Digital Twin\n\n```yaml\n# File: .github\u002Fworkflows\u002Fdigital-twin-ci.yml\n\nname: Digital Twin CI\u002FCD\n\non:\n  push:\n    branches: [main, develop]\n  pull_request:\n    branches: [main]\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v4\n        with:\n          python-version: '3.9'\n\n      - name: Install dependencies\n        run: |\n          pip install -r requirements.txt\n          pip install pytest pytest-cov\n\n      - name: Run unit tests\n        run: |\n          pytest tests\u002F --cov=digital_twin --cov-report=xml\n\n      - name: Run physics model validation\n        run: |\n          python tests\u002Fvalidate_physics.py\n\n      - name: Upload coverage\n        uses: codecov\u002Fcodecov-action@v3\n        with:\n          file: .\u002Fcoverage.xml\n\n  simulate:\n    runs-on: ubuntu-latest\n    needs: test\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Run simulation tests\n        run: |\n          python digital_twin.py --mode simulation \\\n            --drive-cycle tests\u002Fwltp_cycle.json \\\n            --output results\u002F\n\n      - name: Validate results\n        run: |\n          python tests\u002Fvalidate_simulation.py results\u002F\n\n      - name: Upload artifacts\n        uses: actions\u002Fupload-artifact@v3\n        with:\n          name: simulation-results\n          path: results\u002F\n\n  deploy:\n    runs-on: ubuntu-latest\n    needs: [test, simulate]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Configure AWS credentials\n        uses: aws-actions\u002Fconfigure-aws-credentials@v2\n        with:\n          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          aws-region: us-west-2\n\n      - name: Deploy to AWS IoT\n        run: |\n          aws iot create-thing --thing-name digital-twin-${{ github.sha }}\n          aws lambda update-function-code \\\n            --function-name vehicle-digital-twin \\\n            --zip-file fileb:\u002F\u002Fdigital_twin.zip\n```\n\n## Real-World Examples\n\n### Tesla Digital Twin\n- **Fleet learning**: Aggregate shadow mode data for Autopilot\n- **Battery degradation modeling**: Predict range loss over time\n- **Virtual testing**: Test new software on digital fleet before OTA\n- **Predictive maintenance**: Schedule service based on digital twin analysis\n\n### BMW Digital Twin\n- **Production line**: Digital twin during manufacturing\n- **Lifetime tracking**: Track vehicle from production to end-of-life\n- **Service optimization**: Predict maintenance needs\n- **Retrofit planning**: Test compatibility of new features\n\n### Rivian Adventure Network\n- **Route optimization**: Simulate range on planned routes\n- **Charging strategy**: Optimize charging stops\n- **Off-road capability**: Simulate vehicle performance on trails\n- **Load planning**: Test vehicle with different cargo\u002Ftrailer loads\n\n## Best Practices\n\n1. **High-fidelity physics**: Use validated physics models\n2. **Real-time sync**: Keep twin synchronized with physical vehicle\n3. **Historical data**: Store state history for analytics\n4. **Predictive models**: Use ML for maintenance predictions\n5. **Virtual testing**: Test software on twins before deployment\n6. **CI\u002FCD integration**: Automate testing with digital twins\n7. **Fleet-wide insights**: Aggregate data across all twins\n8. **Privacy protection**: Anonymize sensitive data\n9. **Model validation**: Continuously validate against real-world data\n10. **Scalability**: Design for millions of twins\n\n## Security Considerations\n\n- **Authentication**: Secure twin-to-cloud communication\n- **Data encryption**: Encrypt state data and telemetry\n- **Access control**: Limit who can command twins\n- **Audit logging**: Track all twin operations\n- **Simulation isolation**: Sandbox simulation environments\n- **Model protection**: Protect proprietary physics models\n\n## References\n\n- **Azure Digital Twins**: https:\u002F\u002Fazure.microsoft.com\u002Fen-us\u002Fproducts\u002Fdigital-twins\u002F\n- **AWS IoT TwinMaker**: https:\u002F\u002Faws.amazon.com\u002Fiot-twinmaker\u002F\n- **Eclipse Ditto**: https:\u002F\u002Fwww.eclipse.org\u002Fditto\u002F\n- **Digital Twin Consortium**: https:\u002F\u002Fwww.digitaltwinconsortium.org\u002F\n\n---\n\n## Ota Update Systems\n\n# OTA Update Systems — Over-The-Air Updates for Vehicles\n\nExpert knowledge of OTA (Over-The-Air) update architecture, A\u002FB partitioning, differential updates, rollback mechanisms, secure boot chain, and update orchestration across ECUs.\n\n## Core Concepts\n\n### Update Architecture Patterns\n\n1. **Full Image Updates**: Complete partition replacement\n2. **Differential Updates**: Binary diffs to minimize bandwidth\n3. **Component Updates**: Individual ECU\u002Fapplication updates\n4. **Atomic Updates**: All-or-nothing update transactions\n5. **Staged Rollouts**: Phased deployment across fleet\n\n### Security Requirements\n\n- **Uptane Framework**: Industry standard for secure vehicle updates\n- **TUF (The Update Framework)**: Metadata and signature verification\n- **Secure Boot Chain**: UEFI\u002FU-Boot signature validation\n- **Hardware Root of Trust**: TPM\u002FHSM for key storage\n- **Rollback Protection**: Anti-rollback counters\n\n## Production-Ready Implementations\n\n### 1. Uptane-Compliant Update Client (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nUptane-compliant OTA update client for automotive ECUs.\nImplements Director and Image repository verification.\n\"\"\"\n\nimport hashlib\nimport json\nimport os\nimport subprocess\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\nimport requests\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import padding, rsa\nfrom cryptography.hazmat.backends import default_backend\n\n\n@dataclass\nclass UpdateMetadata:\n    \"\"\"Update metadata from Director repository.\"\"\"\n    version: str\n    targets: Dict[str, dict]\n    signatures: List[dict]\n    expires: str\n\n    @classmethod\n    def from_json(cls, data: dict):\n        return cls(\n            version=data[\"signed\"][\"version\"],\n            targets=data[\"signed\"][\"targets\"],\n            signatures=data[\"signatures\"],\n            expires=data[\"signed\"][\"expires\"]\n        )\n\n\nclass UptaneClient:\n    \"\"\"\n    Uptane OTA update client.\n\n    Supports:\n    - Dual Director\u002FImage repository verification\n    - Signature validation with threshold\n    - Differential update download\n    - A\u002FB partition switching\n    - Automatic rollback on boot failure\n    \"\"\"\n\n    def __init__(self, config_path: str = \"\u002Fetc\u002Fota\u002Fuptane-config.json\"):\n        self.config = self._load_config(config_path)\n        self.ecu_serial = self._get_ecu_serial()\n        self.current_version = self._get_current_version()\n        self.director_url = self.config[\"director_url\"]\n        self.image_repo_url = self.config[\"image_repo_url\"]\n        self.root_keys = self._load_root_keys()\n\n    def _load_config(self, path: str) -> dict:\n        \"\"\"Load Uptane configuration.\"\"\"\n        with open(path, 'r') as f:\n            return json.load(f)\n\n    def _get_ecu_serial(self) -> str:\n        \"\"\"Get unique ECU serial number.\"\"\"\n        # Read from secure storage (TPM, EEPROM, etc.)\n        serial_path = Path(\"\u002Fsys\u002Ffirmware\u002Fdevicetree\u002Fbase\u002Fserial-number\")\n        if serial_path.exists():\n            return serial_path.read_text().strip()\n        return os.uname().nodename  # Fallback\n\n    def _get_current_version(self) -> str:\n        \"\"\"Get currently running software version.\"\"\"\n        version_path = Path(\"\u002Fetc\u002Fota\u002Fcurrent-version\")\n        if version_path.exists():\n            return version_path.read_text().strip()\n        return \"unknown\"\n\n    def _load_root_keys(self) -> List[rsa.RSAPublicKey]:\n        \"\"\"Load root public keys for signature verification.\"\"\"\n        keys = []\n        for key_file in self.config[\"root_keys\"]:\n            with open(key_file, 'rb') as f:\n                key = serialization.load_pem_public_key(\n                    f.read(),\n                    backend=default_backend()\n                )\n                keys.append(key)\n        return keys\n\n    def verify_signature(self, data: bytes, signature: bytes,\n                        public_key: rsa.RSAPublicKey) -> bool:\n        \"\"\"Verify RSA signature on data.\"\"\"\n        try:\n            public_key.verify(\n                signature,\n                data,\n                padding.PSS(\n                    mgf=padding.MGF1(hashes.SHA256()),\n                    salt_length=padding.PSS.MAX_LENGTH\n                ),\n                hashes.SHA256()\n            )\n            return True\n        except Exception as e:\n            print(f\"Signature verification failed: {e}\")\n            return False\n\n    def check_for_updates(self) -> Optional[UpdateMetadata]:\n        \"\"\"\n        Check Director repository for available updates.\n\n        Returns:\n            UpdateMetadata if update available, None otherwise\n        \"\"\"\n        print(f\"[OTA] Checking for updates (ECU: {self.ecu_serial}, \"\n              f\"Version: {self.current_version})\")\n\n        # Fetch Director metadata\n        url = f\"{self.director_url}\u002Fmetadata\u002F{self.ecu_serial}\u002Ftargets.json\"\n        try:\n            response = requests.get(url, timeout=30)\n            response.raise_for_status()\n            metadata = UpdateMetadata.from_json(response.json())\n\n            # Verify signatures (threshold: 2\u002F3)\n            verified_sigs = 0\n            for sig_data in metadata.signatures:\n                sig_bytes = bytes.fromhex(sig_data[\"sig\"])\n                # Verify against root keys\n                for key in self.root_keys:\n                    if self.verify_signature(\n                        json.dumps(response.json()[\"signed\"]).encode(),\n                        sig_bytes,\n                        key\n                    ):\n                        verified_sigs += 1\n                        break\n\n            if verified_sigs \u003C self.config.get(\"signature_threshold\", 2):\n                raise ValueError(f\"Insufficient signatures: {verified_sigs}\")\n\n            # Check if update is newer\n            for target_name, target_info in metadata.targets.items():\n                if target_info[\"custom\"].get(\"ecu_identifier\") == self.ecu_serial:\n                    target_version = target_info[\"custom\"][\"version\"]\n                    if target_version != self.current_version:\n                        print(f\"[OTA] Update available: {target_version}\")\n                        return metadata\n\n            print(\"[OTA] No updates available\")\n            return None\n\n        except Exception as e:\n            print(f\"[OTA] Error checking for updates: {e}\")\n            return None\n\n    def download_update(self, metadata: UpdateMetadata) -> Optional[Path]:\n        \"\"\"\n        Download update image from Image repository.\n\n        Uses differential updates if available.\n\n        Returns:\n            Path to downloaded update file\n        \"\"\"\n        for target_name, target_info in metadata.targets.items():\n            if target_info[\"custom\"].get(\"ecu_identifier\") != self.ecu_serial:\n                continue\n\n            # Check for differential update\n            if \"delta_from\" in target_info[\"custom\"]:\n                if target_info[\"custom\"][\"delta_from\"] == self.current_version:\n                    print(\"[OTA] Downloading differential update...\")\n                    url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}.delta\"\n                else:\n                    print(\"[OTA] Delta not applicable, downloading full image\")\n                    url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}\"\n            else:\n                print(\"[OTA] Downloading full update image...\")\n                url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}\"\n\n            # Download with progress\n            download_path = Path(f\"\u002Ftmp\u002Fota-update-{target_name}\")\n            try:\n                with requests.get(url, stream=True, timeout=300) as r:\n                    r.raise_for_status()\n                    total_size = int(r.headers.get('content-length', 0))\n                    downloaded = 0\n\n                    with open(download_path, 'wb') as f:\n                        for chunk in r.iter_content(chunk_size=8192):\n                            f.write(chunk)\n                            downloaded += len(chunk)\n                            progress = (downloaded \u002F total_size * 100) if total_size else 0\n                            print(f\"\\r[OTA] Download progress: {progress:.1f}%\", end='')\n\n                    print()  # New line after progress\n\n                # Verify hash\n                expected_hash = target_info[\"hashes\"][\"sha256\"]\n                actual_hash = self._compute_sha256(download_path)\n\n                if actual_hash != expected_hash:\n                    raise ValueError(f\"Hash mismatch: {actual_hash} != {expected_hash}\")\n\n                print(f\"[OTA] Download complete: {download_path}\")\n                return download_path\n\n            except Exception as e:\n                print(f\"[OTA] Download failed: {e}\")\n                if download_path.exists():\n                    download_path.unlink()\n                return None\n\n        return None\n\n    def _compute_sha256(self, file_path: Path) -> str:\n        \"\"\"Compute SHA256 hash of file.\"\"\"\n        sha256 = hashlib.sha256()\n        with open(file_path, 'rb') as f:\n            for chunk in iter(lambda: f.read(8192), b''):\n                sha256.update(chunk)\n        return sha256.hexdigest()\n\n    def install_update(self, update_path: Path) -> bool:\n        \"\"\"\n        Install update to inactive partition.\n\n        Uses A\u002FB partition switching for atomic updates.\n\n        Returns:\n            True if installation successful\n        \"\"\"\n        print(\"[OTA] Installing update...\")\n\n        try:\n            # Determine inactive partition\n            current_slot = self._get_current_boot_slot()\n            inactive_slot = 'b' if current_slot == 'a' else 'a'\n            inactive_partition = f\"\u002Fdev\u002Fmmcblk0p{2 if inactive_slot == 'b' else 1}\"\n\n            print(f\"[OTA] Current slot: {current_slot}, \"\n                  f\"Installing to: {inactive_slot}\")\n\n            # Write update to inactive partition\n            cmd = f\"dd if={update_path} of={inactive_partition} bs=4M status=progress\"\n            subprocess.run(cmd, shell=True, check=True)\n\n            # Set boot slot to inactive (will become active on next boot)\n            self._set_boot_slot(inactive_slot)\n\n            # Mark for boot attempt counter (rollback if boot fails 3 times)\n            self._set_boot_counter(3)\n\n            print(f\"[OTA] Update installed to slot {inactive_slot}\")\n            return True\n\n        except Exception as e:\n            print(f\"[OTA] Installation failed: {e}\")\n            return False\n\n    def _get_current_boot_slot(self) -> str:\n        \"\"\"Get currently booted partition slot.\"\"\"\n        # Read from U-Boot environment or kernel command line\n        with open(\"\u002Fproc\u002Fcmdline\", 'r') as f:\n            cmdline = f.read()\n            if \"root=\u002Fdev\u002Fmmcblk0p1\" in cmdline:\n                return 'a'\n            elif \"root=\u002Fdev\u002Fmmcblk0p2\" in cmdline:\n                return 'b'\n        return 'a'  # Default\n\n    def _set_boot_slot(self, slot: str):\n        \"\"\"Set boot slot for next reboot.\"\"\"\n        # Write to U-Boot environment\n        cmd = f\"fw_setenv boot_slot {slot}\"\n        subprocess.run(cmd, shell=True, check=True)\n\n    def _set_boot_counter(self, count: int):\n        \"\"\"Set boot attempt counter for rollback protection.\"\"\"\n        cmd = f\"fw_setenv boot_counter {count}\"\n        subprocess.run(cmd, shell=True, check=True)\n\n    def apply_update(self) -> bool:\n        \"\"\"\n        Apply update by rebooting into new partition.\n\n        Returns:\n            True if reboot initiated\n        \"\"\"\n        print(\"[OTA] Applying update (rebooting)...\")\n        try:\n            subprocess.run([\"reboot\"], check=True)\n            return True\n        except Exception as e:\n            print(f\"[OTA] Reboot failed: {e}\")\n            return False\n\n    def verify_boot_success(self):\n        \"\"\"\n        Verify successful boot after update.\n\n        Called by systemd service on boot.\n        Confirms update success or triggers rollback.\n        \"\"\"\n        boot_counter_path = Path(\"\u002Fproc\u002Fdevice-tree\u002Fchosen\u002Fu-boot,boot-counter\")\n\n        if boot_counter_path.exists():\n            counter = int(boot_counter_path.read_text().strip())\n\n            if counter > 0:\n                # Boot successful, commit update\n                print(\"[OTA] Boot successful, committing update\")\n                self._set_boot_counter(0)  # Clear counter\n\n                # Update current version\n                new_version = self._detect_version()\n                Path(\"\u002Fetc\u002Fota\u002Fcurrent-version\").write_text(new_version)\n            else:\n                print(\"[OTA] Already committed\")\n        else:\n            print(\"[OTA] Boot counter not found (no pending update)\")\n\n    def _detect_version(self) -> str:\n        \"\"\"Detect software version from running system.\"\"\"\n        version_files = [\n            \"\u002Fetc\u002Fota\u002Fversion\",\n            \"\u002Fetc\u002Fos-release\"\n        ]\n\n        for path in version_files:\n            if Path(path).exists():\n                content = Path(path).read_text()\n                # Extract version from os-release\n                for line in content.split('\\n'):\n                    if line.startswith(\"VERSION=\"):\n                        return line.split('=')[1].strip('\"')\n\n        return \"unknown\"\n\n\ndef main():\n    \"\"\"OTA update client main loop.\"\"\"\n    client = UptaneClient()\n\n    # Check on boot\n    client.verify_boot_success()\n\n    # Periodic update check\n    while True:\n        metadata = client.check_for_updates()\n\n        if metadata:\n            update_path = client.download_update(metadata)\n\n            if update_path:\n                if client.install_update(update_path):\n                    print(\"[OTA] Update ready, will apply on next reboot\")\n                    # Optionally auto-reboot or wait for user confirmation\n                    # client.apply_update()\n\n        # Check every hour\n        time.sleep(3600)\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. A\u002FB Partition Configuration (U-Boot)\n\n```bash\n# U-Boot environment for A\u002FB partitioning\n# File: \u002Fetc\u002Ffw_env.config\n\n# Device              Offset    Size     Erasesize\n\u002Fdev\u002Fmtd1             0x0000    0x1000   0x1000\n\u002Fdev\u002Fmtd2             0x0000    0x1000   0x1000\n```\n\n```bash\n# U-Boot bootcmd script for A\u002FB boot\n# File: boot.cmd\n\n# Read boot slot from environment\nsetenv bootslot ${boot_slot}\nif test -z \"${bootslot}\"; then\n    setenv bootslot a\nfi\n\n# Read boot counter\nsetenv bootcount ${boot_counter}\nif test -z \"${bootcount}\"; then\n    setenv bootcount 0\nfi\n\n# Check rollback condition\nif test ${bootcount} -eq 0; then\n    echo \"Booting from slot ${bootslot}\"\nelse\n    # Decrement boot counter\n    setexpr bootcount ${bootcount} - 1\n    setenv boot_counter ${bootcount}\n    saveenv\n\n    # If counter reaches 0, rollback to other slot\n    if test ${bootcount} -eq 0; then\n        echo \"Boot failed 3 times, rolling back\"\n        if test \"${bootslot}\" = \"a\"; then\n            setenv bootslot b\n        else\n            setenv bootslot a\n        fi\n        setenv boot_slot ${bootslot}\n        saveenv\n    fi\nfi\n\n# Set root partition\nif test \"${bootslot}\" = \"a\"; then\n    setenv bootargs console=ttyS0,115200 root=\u002Fdev\u002Fmmcblk0p1 rw rootwait\n    load mmc 0:1 ${kernel_addr_r} \u002Fboot\u002FImage\n    load mmc 0:1 ${fdt_addr_r} \u002Fboot\u002Fdtb\nelse\n    setenv bootargs console=ttyS0,115200 root=\u002Fdev\u002Fmmcblk0p2 rw rootwait\n    load mmc 0:2 ${kernel_addr_r} \u002Fboot\u002FImage\n    load mmc 0:2 ${fdt_addr_r} \u002Fboot\u002Fdtb\nfi\n\n# Boot kernel\nbooti ${kernel_addr_r} - ${fdt_addr_r}\n```\n\n### 3. Differential Update Generator (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nGenerate binary differential updates for OTA.\nUses bsdiff algorithm for efficient bandwidth usage.\n\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport subprocess\nimport sys\nfrom pathlib import Path\n\n\ndef generate_delta(old_image: Path, new_image: Path, output: Path):\n    \"\"\"\n    Generate binary diff between two images.\n\n    Args:\n        old_image: Path to old firmware image\n        new_image: Path to new firmware image\n        output: Path to output delta file\n    \"\"\"\n    print(f\"Generating delta: {old_image} -> {new_image}\")\n\n    # Use bsdiff for binary diffing\n    cmd = [\"bsdiff\", str(old_image), str(new_image), str(output)]\n\n    try:\n        subprocess.run(cmd, check=True)\n    except FileNotFoundError:\n        print(\"Error: bsdiff not found. Install with: apt-get install bsdiff\")\n        sys.exit(1)\n    except subprocess.CalledProcessError as e:\n        print(f\"Error generating delta: {e}\")\n        sys.exit(1)\n\n    # Calculate sizes and compression ratio\n    old_size = old_image.stat().st_size\n    new_size = new_image.stat().st_size\n    delta_size = output.stat().st_size\n\n    ratio = (1 - delta_size \u002F new_size) * 100\n\n    print(f\"Old image size: {old_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"New image size: {new_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"Delta size: {delta_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"Bandwidth savings: {ratio:.1f}%\")\n\n    # Generate metadata\n    metadata = {\n        \"old_version\": old_image.stem,\n        \"new_version\": new_image.stem,\n        \"old_hash\": compute_sha256(old_image),\n        \"new_hash\": compute_sha256(new_image),\n        \"delta_hash\": compute_sha256(output),\n        \"delta_size\": delta_size,\n        \"compression_ratio\": ratio\n    }\n\n    metadata_path = output.with_suffix('.json')\n    with open(metadata_path, 'w') as f:\n        json.dump(metadata, f, indent=2)\n\n    print(f\"Metadata written to: {metadata_path}\")\n\n\ndef compute_sha256(path: Path) -> str:\n    \"\"\"Compute SHA256 hash of file.\"\"\"\n    sha256 = hashlib.sha256()\n    with open(path, 'rb') as f:\n        for chunk in iter(lambda: f.read(8192), b''):\n            sha256.update(chunk)\n    return sha256.hexdigest()\n\n\ndef apply_delta(old_image: Path, delta: Path, output: Path):\n    \"\"\"\n    Apply delta patch to old image.\n\n    Args:\n        old_image: Path to old firmware image\n        delta: Path to delta file\n        output: Path to output patched image\n    \"\"\"\n    print(f\"Applying delta: {old_image} + {delta} -> {output}\")\n\n    cmd = [\"bspatch\", str(old_image), str(output), str(delta)]\n\n    try:\n        subprocess.run(cmd, check=True)\n        print(f\"Patched image created: {output}\")\n    except FileNotFoundError:\n        print(\"Error: bspatch not found. Install with: apt-get install bsdiff\")\n        sys.exit(1)\n    except subprocess.CalledProcessError as e:\n        print(f\"Error applying delta: {e}\")\n        sys.exit(1)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"OTA differential update generator\")\n    subparsers = parser.add_subparsers(dest='command', help='Command to execute')\n\n    # Generate delta\n    gen_parser = subparsers.add_parser('generate', help='Generate delta update')\n    gen_parser.add_argument('--old', type=Path, required=True, help='Old image')\n    gen_parser.add_argument('--new', type=Path, required=True, help='New image')\n    gen_parser.add_argument('--output', type=Path, required=True, help='Output delta file')\n\n    # Apply delta\n    apply_parser = subparsers.add_parser('apply', help='Apply delta update')\n    apply_parser.add_argument('--old', type=Path, required=True, help='Old image')\n    apply_parser.add_argument('--delta', type=Path, required=True, help='Delta file')\n    apply_parser.add_argument('--output', type=Path, required=True, help='Output image')\n\n    args = parser.parse_args()\n\n    if args.command == 'generate':\n        generate_delta(args.old, args.new, args.output)\n    elif args.command == 'apply':\n        apply_delta(args.old, args.delta, args.output)\n    else:\n        parser.print_help()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 4. OTA Update Service (systemd)\n\n```ini\n# File: \u002Fetc\u002Fsystemd\u002Fsystem\u002Fota-update.service\n\n[Unit]\nDescription=OTA Update Client\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nExecStart=\u002Fusr\u002Fbin\u002Fpython3 \u002Fusr\u002Flocal\u002Fbin\u002Fuptane-client.py\nRestart=always\nRestartSec=60\nUser=ota\nGroup=ota\n\n# Security hardening\nPrivateTmp=yes\nProtectSystem=strict\nProtectHome=yes\nReadWritePaths=\u002Ftmp \u002Fvar\u002Flib\u002Fota\nNoNewPrivileges=yes\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\n\n[Install]\nWantedBy=multi-user.target\n```\n\n```ini\n# File: \u002Fetc\u002Fsystemd\u002Fsystem\u002Fota-boot-verify.service\n\n[Unit]\nDescription=OTA Boot Verification\nDefaultDependencies=no\nAfter=local-fs.target\nBefore=sysinit.target\n\n[Service]\nType=oneshot\nExecStart=\u002Fusr\u002Fbin\u002Fpython3 -c \"from uptane_client import UptaneClient; UptaneClient().verify_boot_success()\"\nRemainAfterExit=yes\n\n[Install]\nWantedBy=sysinit.target\n```\n\n### 5. Mender Integration (Alternative Framework)\n\n```yaml\n# File: \u002Fetc\u002Fmender\u002Fmender.conf\n{\n  \"ServerURL\": \"https:\u002F\u002Fota.example.com\",\n  \"TenantToken\": \"TENANT_TOKEN_HERE\",\n  \"InventoryPollIntervalSeconds\": 28800,\n  \"UpdatePollIntervalSeconds\": 1800,\n  \"RetryPollIntervalSeconds\": 300,\n  \"RootfsPartA\": \"\u002Fdev\u002Fmmcblk0p2\",\n  \"RootfsPartB\": \"\u002Fdev\u002Fmmcblk0p3\",\n  \"ServerCertificate\": \"\u002Fetc\u002Fmender\u002Fserver.crt\",\n  \"DeviceTypeFile\": \"\u002Fvar\u002Flib\u002Fmender\u002Fdevice_type\"\n}\n```\n\n```bash\n# Mender artifact creation script\n#!\u002Fbin\u002Fbash\n# File: create-mender-artifact.sh\n\nset -e\n\nIMAGE_FILE=$1\nARTIFACT_NAME=$2\nDEVICE_TYPE=$3\n\nif [ -z \"$IMAGE_FILE\" ] || [ -z \"$ARTIFACT_NAME\" ] || [ -z \"$DEVICE_TYPE\" ]; then\n    echo \"Usage: $0 \u003Cimage-file> \u003Cartifact-name> \u003Cdevice-type>\"\n    exit 1\nfi\n\n# Create Mender artifact\nmender-artifact write rootfs-image \\\n    --file \"$IMAGE_FILE\" \\\n    --artifact-name \"$ARTIFACT_NAME\" \\\n    --device-type \"$DEVICE_TYPE\" \\\n    --output-path \"${ARTIFACT_NAME}.mender\"\n\necho \"Mender artifact created: ${ARTIFACT_NAME}.mender\"\n\n# Sign artifact (optional)\nif [ -f \"private.key\" ]; then\n    mender-artifact sign \"${ARTIFACT_NAME}.mender\" \\\n        --key private.key \\\n        --output-path \"${ARTIFACT_NAME}.signed.mender\"\n\n    echo \"Signed artifact created: ${ARTIFACT_NAME}.signed.mender\"\nfi\n```\n\n## Real-World Examples\n\n### Tesla OTA Architecture\n\n- **Full stack updates**: Entire OS, kernel, applications\n- **Dual-bank storage**: 2x storage for A\u002FB switching\n- **Cellular + WiFi**: Automatic download scheduling\n- **User control**: Schedule updates, defer if driving\n- **Rollback**: Automatic if vehicle fails self-test\n\n### VW.OS Update Strategy\n\n- **ECU orchestration**: Update multiple ECUs in sequence\n- **Safety constraints**: No updates to critical systems while driving\n- **Partial updates**: Update infotainment without touching ADAS\n- **Fleet rollout**: Phased deployment by region\u002Fmodel\n\n### GM Ultifi Platform\n\n- **Container-based**: Update individual apps without full reflash\n- **Middleware updates**: Update communication layer separately\n- **Third-party apps**: App store model with independent update cycle\n- **Cloud sync**: Configuration sync across vehicles\n\n## Best Practices\n\n1. **Always use A\u002FB partitioning**: Never update the running system\n2. **Implement rollback**: Automatic rollback after 3 boot failures\n3. **Verify signatures**: Multi-level signature verification (Uptane)\n4. **Use differential updates**: Reduce bandwidth by 70-90%\n5. **Stage fleet rollouts**: 1% -> 10% -> 100% deployment\n6. **Monitor success rates**: Track update success\u002Ffailure metrics\n7. **Preserve user data**: Never wipe data partitions\n8. **Test offline rollback**: Ensure rollback works without network\n9. **Schedule updates**: Respect user preferences and vehicle state\n10. **Log everything**: Comprehensive telemetry for debugging\n\n## Security Considerations\n\n- **Secure Boot**: Verify every component in boot chain\n- **Encrypted updates**: TLS for transport, encryption at rest\n- **Anti-rollback**: Prevent downgrade to vulnerable versions\n- **Time validity**: Reject updates with expired metadata\n- **Threshold signatures**: Require multiple signers (2 of 3)\n- **Hardware root of trust**: TPM or secure enclave for keys\n- **Audit logging**: Track all update attempts and outcomes\n\n## References\n\n- **Uptane**: https:\u002F\u002Fuptane.github.io\u002F\n- **Mender**: https:\u002F\u002Fmender.io\u002F\n- **SWUpdate**: https:\u002F\u002Fsbabic.github.io\u002Fswupdate\u002F\n- **RAUC**: https:\u002F\u002Frauc.io\u002F\n- **TUF Specification**: https:\u002F\u002Ftheupdateframework.io\u002F\n\n---\n\n## Vehicle App Stores\n\n# Vehicle App Stores — Automotive Application Platforms\n\nExpert knowledge of automotive app platforms, app lifecycle management, sandboxing, permissions model, revenue sharing, 3rd-party developer SDKs, and app certification.\n\n## Core Concepts\n\n### App Store Architecture\n\n1. **App Marketplace**: Discovery, purchase, installation\n2. **Developer Portal**: App submission, certification, analytics\n3. **Runtime Environment**: Sandboxed execution environment\n4. **Payment Integration**: In-app purchases, subscriptions\n5. **Update Management**: Automatic app updates\n\n### App Types\n\n- **Infotainment Apps**: Media, navigation, productivity\n- **ADAS Extensions**: Enhanced driver assistance features\n- **Telematics Apps**: Fleet management, usage tracking\n- **Comfort Apps**: Climate control, seat adjustments\n- **Diagnostic Tools**: Vehicle health monitoring\n\n## Production-Ready Implementation\n\n### 1. App Store Backend API (Python\u002FFastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle App Store Backend API.\n\nHandles:\n- App catalog management\n- User authentication and purchases\n- App installation and updates\n- Developer portal integration\n\"\"\"\n\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom typing import List, Optional\nfrom fastapi import FastAPI, HTTPException, Depends, Security\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\nfrom pydantic import BaseModel, Field\nfrom sqlalchemy import create_engine, Column, String, Integer, Float, DateTime, Boolean, JSON\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, Session\nimport jwt\nimport hashlib\n\n\n# Database models\nBase = declarative_base()\n\n\nclass AppCategory(str, Enum):\n    \"\"\"App categories.\"\"\"\n    NAVIGATION = \"navigation\"\n    MEDIA = \"media\"\n    PRODUCTIVITY = \"productivity\"\n    GAMES = \"games\"\n    UTILITIES = \"utilities\"\n    ADAS = \"adas\"\n    DIAGNOSTICS = \"diagnostics\"\n\n\nclass AppStatus(str, Enum):\n    \"\"\"App certification status.\"\"\"\n    PENDING = \"pending\"\n    APPROVED = \"approved\"\n    REJECTED = \"rejected\"\n    SUSPENDED = \"suspended\"\n\n\nclass App(Base):\n    \"\"\"Application model.\"\"\"\n    __tablename__ = \"apps\"\n\n    id = Column(String, primary_key=True)\n    name = Column(String, nullable=False)\n    developer_id = Column(String, nullable=False)\n    category = Column(String, nullable=False)\n    version = Column(String, nullable=False)\n    description = Column(String)\n    price = Column(Float, default=0.0)\n    rating = Column(Float, default=0.0)\n    downloads = Column(Integer, default=0)\n    status = Column(String, default=AppStatus.PENDING.value)\n    manifest_url = Column(String)\n    icon_url = Column(String)\n    screenshots = Column(JSON, default=list)\n    permissions = Column(JSON, default=list)\n    min_platform_version = Column(String)\n    created_at = Column(DateTime, default=datetime.utcnow)\n    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)\n\n\nclass User(Base):\n    \"\"\"User model.\"\"\"\n    __tablename__ = \"users\"\n\n    id = Column(String, primary_key=True)\n    vin = Column(String, unique=True, nullable=False)  # Vehicle VIN\n    email = Column(String)\n    purchased_apps = Column(JSON, default=list)\n    installed_apps = Column(JSON, default=list)\n    created_at = Column(DateTime, default=datetime.utcnow)\n\n\nclass Purchase(Base):\n    \"\"\"Purchase transaction model.\"\"\"\n    __tablename__ = \"purchases\"\n\n    id = Column(String, primary_key=True)\n    user_id = Column(String, nullable=False)\n    app_id = Column(String, nullable=False)\n    amount = Column(Float)\n    transaction_date = Column(DateTime, default=datetime.utcnow)\n    status = Column(String, default=\"completed\")\n\n\n# Pydantic schemas\nclass AppCreate(BaseModel):\n    \"\"\"App creation schema.\"\"\"\n    name: str\n    developer_id: str\n    category: AppCategory\n    version: str\n    description: str\n    price: float = 0.0\n    manifest_url: str\n    icon_url: str\n    screenshots: List[str] = []\n    permissions: List[str] = []\n    min_platform_version: str = \"1.0.0\"\n\n\nclass AppResponse(BaseModel):\n    \"\"\"App response schema.\"\"\"\n    id: str\n    name: str\n    developer_id: str\n    category: str\n    version: str\n    description: str\n    price: float\n    rating: float\n    downloads: int\n    status: str\n    icon_url: str\n    screenshots: List[str]\n    permissions: List[str]\n    created_at: datetime\n\n    class Config:\n        from_attributes = True\n\n\nclass PurchaseRequest(BaseModel):\n    \"\"\"Purchase request schema.\"\"\"\n    app_id: str\n    payment_method: str = \"credit_card\"\n\n\nclass InstallRequest(BaseModel):\n    \"\"\"App installation request.\"\"\"\n    app_id: str\n\n\n# Initialize FastAPI\napp = FastAPI(title=\"Vehicle App Store API\", version=\"1.0.0\")\nsecurity = HTTPBearer()\n\n# Database setup\nDATABASE_URL = \"postgresql:\u002F\u002Fappstore:password@localhost\u002Fvehicle_appstore\"\nengine = create_engine(DATABASE_URL)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n# JWT secret\nJWT_SECRET = \"your-secret-key-change-in-production\"\n\n\ndef get_db():\n    \"\"\"Database session dependency.\"\"\"\n    db = SessionLocal()\n    try:\n        yield db\n    finally:\n        db.close()\n\n\ndef verify_token(credentials: HTTPAuthorizationCredentials = Security(security)) -> dict:\n    \"\"\"Verify JWT token and extract user info.\"\"\"\n    try:\n        token = credentials.credentials\n        payload = jwt.decode(token, JWT_SECRET, algorithms=[\"HS256\"])\n        return payload\n    except jwt.ExpiredSignatureError:\n        raise HTTPException(status_code=401, detail=\"Token expired\")\n    except jwt.InvalidTokenError:\n        raise HTTPException(status_code=401, detail=\"Invalid token\")\n\n\n@app.post(\"\u002Fauth\u002Flogin\")\nasync def login(vin: str, db: Session = Depends(get_db)):\n    \"\"\"\n    Authenticate vehicle by VIN.\n\n    In production, this would verify VIN against manufacturer database.\n    \"\"\"\n    user = db.query(User).filter(User.vin == vin).first()\n\n    if not user:\n        # Create new user\n        user = User(id=hashlib.sha256(vin.encode()).hexdigest()[:16], vin=vin)\n        db.add(user)\n        db.commit()\n\n    # Generate JWT\n    token = jwt.encode(\n        {\n            \"user_id\": user.id,\n            \"vin\": user.vin,\n            \"exp\": datetime.utcnow() + timedelta(days=30)\n        },\n        JWT_SECRET,\n        algorithm=\"HS256\"\n    )\n\n    return {\"access_token\": token, \"token_type\": \"bearer\"}\n\n\n@app.get(\"\u002Fapps\", response_model=List[AppResponse])\nasync def list_apps(\n    category: Optional[AppCategory] = None,\n    search: Optional[str] = None,\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    List available apps.\n\n    Filters by category and search query.\n    Only returns approved apps.\n    \"\"\"\n    query = db.query(App).filter(App.status == AppStatus.APPROVED.value)\n\n    if category:\n        query = query.filter(App.category == category.value)\n\n    if search:\n        query = query.filter(App.name.ilike(f\"%{search}%\"))\n\n    apps = query.order_by(App.rating.desc(), App.downloads.desc()).limit(50).all()\n    return apps\n\n\n@app.get(\"\u002Fapps\u002F{app_id}\", response_model=AppResponse)\nasync def get_app(app_id: str, db: Session = Depends(get_db)):\n    \"\"\"Get app details.\"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    return app_obj\n\n\n@app.post(\"\u002Fapps\", response_model=AppResponse)\nasync def submit_app(\n    app_data: AppCreate,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Submit new app for certification.\n\n    Developer portal endpoint.\n    \"\"\"\n    app_id = hashlib.sha256(\n        f\"{app_data.name}{app_data.developer_id}{datetime.utcnow()}\".encode()\n    ).hexdigest()[:16]\n\n    app_obj = App(\n        id=app_id,\n        name=app_data.name,\n        developer_id=app_data.developer_id,\n        category=app_data.category.value,\n        version=app_data.version,\n        description=app_data.description,\n        price=app_data.price,\n        manifest_url=app_data.manifest_url,\n        icon_url=app_data.icon_url,\n        screenshots=app_data.screenshots,\n        permissions=app_data.permissions,\n        min_platform_version=app_data.min_platform_version,\n        status=AppStatus.PENDING.value\n    )\n\n    db.add(app_obj)\n    db.commit()\n    db.refresh(app_obj)\n\n    return app_obj\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Fpurchase\")\nasync def purchase_app(\n    app_id: str,\n    purchase_data: PurchaseRequest,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Purchase app.\n\n    Handles payment processing and license activation.\n    \"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    # Check if already purchased\n    if app_id in user.purchased_apps:\n        return {\"message\": \"App already purchased\", \"app_id\": app_id}\n\n    # Process payment (integrate with payment gateway)\n    # For demo purposes, assume payment succeeds\n    purchase_id = hashlib.sha256(\n        f\"{user.id}{app_id}{datetime.utcnow()}\".encode()\n    ).hexdigest()[:16]\n\n    purchase = Purchase(\n        id=purchase_id,\n        user_id=user.id,\n        app_id=app_id,\n        amount=app_obj.price,\n        status=\"completed\"\n    )\n\n    # Update user purchased apps\n    user.purchased_apps.append(app_id)\n\n    # Increment app downloads\n    app_obj.downloads += 1\n\n    db.add(purchase)\n    db.commit()\n\n    return {\n        \"message\": \"Purchase successful\",\n        \"purchase_id\": purchase_id,\n        \"app_id\": app_id,\n        \"amount\": app_obj.price\n    }\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Finstall\")\nasync def install_app(\n    app_id: str,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Install app to vehicle.\n\n    Returns manifest URL for vehicle runtime to download.\n    \"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    # Check if purchased\n    if app_id not in user.purchased_apps:\n        raise HTTPException(status_code=403, detail=\"App not purchased\")\n\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    # Add to installed apps\n    if app_id not in user.installed_apps:\n        user.installed_apps.append(app_id)\n        db.commit()\n\n    return {\n        \"message\": \"Installation initiated\",\n        \"app_id\": app_id,\n        \"manifest_url\": app_obj.manifest_url,\n        \"version\": app_obj.version\n    }\n\n\n@app.get(\"\u002Fapps\u002F{app_id}\u002Fupdates\")\nasync def check_app_updates(\n    app_id: str,\n    current_version: str,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Check for app updates.\n\n    Returns latest version if newer than current.\n    \"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    if app_obj.version != current_version:\n        return {\n            \"update_available\": True,\n            \"latest_version\": app_obj.version,\n            \"manifest_url\": app_obj.manifest_url,\n            \"changelog\": f\"Updated to version {app_obj.version}\"\n        }\n\n    return {\"update_available\": False}\n\n\n@app.get(\"\u002Fuser\u002Fapps\")\nasync def get_user_apps(\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"Get user's purchased and installed apps.\"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    purchased = db.query(App).filter(App.id.in_(user.purchased_apps)).all()\n    installed = db.query(App).filter(App.id.in_(user.installed_apps)).all()\n\n    return {\n        \"purchased\": [AppResponse.from_orm(app) for app in purchased],\n        \"installed\": [AppResponse.from_orm(app) for app in installed]\n    }\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Frate\")\nasync def rate_app(\n    app_id: str,\n    rating: float = Field(..., ge=1.0, le=5.0),\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"Rate an app (1-5 stars).\"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    if app_id not in user.purchased_apps:\n        raise HTTPException(status_code=403, detail=\"Must own app to rate\")\n\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    # Update rolling average (simplified)\n    # In production, store individual ratings\n    app_obj.rating = (app_obj.rating + rating) \u002F 2\n\n    db.commit()\n\n    return {\"message\": \"Rating submitted\", \"new_rating\": app_obj.rating}\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    Base.metadata.create_all(bind=engine)\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n### 2. App Manifest Format\n\n```yaml\n# App manifest - describes app metadata and requirements\n# File: app-manifest.yaml\n\napiVersion: vehicle.app\u002Fv1\nkind: VehicleApp\nmetadata:\n  name: spotify-automotive\n  version: 2.1.4\n  displayName: Spotify for Cars\n  developer:\n    id: spotify-inc\n    name: Spotify AB\n    email: automotive@spotify.com\n    website: https:\u002F\u002Fwww.spotify.com\n\nspec:\n  description: |\n    Stream millions of songs and podcasts directly in your vehicle.\n    Integrates with vehicle audio system and steering wheel controls.\n\n  category: media\n  price: 0.0  # Free with subscription\n  inAppPurchases: true\n\n  # Platform requirements\n  platform:\n    minVersion: \"2.0.0\"\n    targetVersion: \"3.1.0\"\n    architecture: [\"arm64\", \"x86_64\"]\n\n  # Permissions required\n  permissions:\n    - AUDIO_PLAYBACK\n    - INTERNET\n    - BLUETOOTH\n    - VEHICLE_SPEED  # For audio ducking when speed > 100mph\n    - STEERING_CONTROLS\n    - LOCATION  # For personalized recommendations\n\n  # Resource limits\n  resources:\n    memory: 512Mi\n    cpu: 500m\n    storage: 2Gi\n    bandwidth: 10Mbps\n\n  # Container configuration\n  container:\n    image: registry.spotify.com\u002Fautomotive\u002Fspotify:2.1.4\n    entrypoint: [\"\u002Fusr\u002Fbin\u002Fspotify-app\"]\n    environment:\n      - name: API_KEY\n        valueFrom:\n          secretRef:\n            name: spotify-api-credentials\n            key: api-key\n\n  # Service exposure\n  services:\n    - name: media-player\n      protocol: dbus\n      interface: org.mpris.MediaPlayer2\n      path: \u002Forg\u002Fmpris\u002FMediaPlayer2\u002Fspotify\n\n  # UI configuration\n  ui:\n    icon: https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Ficon-512.png\n    screenshots:\n      - https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Fscreenshot1.png\n      - https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Fscreenshot2.png\n    launchMode: fullscreen\n    displayInLauncher: true\n\n  # Integration points\n  integrations:\n    voiceAssistant:\n      enabled: true\n      wakeWords: [\"play music\", \"open spotify\"]\n    steeringControls:\n      enabled: true\n      actions: [play, pause, next, previous, volume]\n    clusterDisplay:\n      enabled: true\n      showNowPlaying: true\n\n  # Safety constraints\n  safety:\n    disableWhileDriving: false\n    touchInteractionLimit: true  # Limit UI interaction while moving\n    voiceControlRequired: false\n\n  # Analytics and telemetry\n  telemetry:\n    enabled: true\n    endpoint: https:\u002F\u002Ftelemetry.spotify.com\u002Fautomotive\n    dataTypes:\n      - usage_statistics\n      - crash_reports\n      - performance_metrics\n\n  # Update strategy\n  updatePolicy:\n    automatic: true\n    canRollback: true\n    maxDowntime: 30s\n```\n\n### 3. App Sandbox Runtime (Golang)\n\n```go\n\u002F\u002F Vehicle app sandbox runtime using containerd\n\u002F\u002F File: app-runtime.go\n\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"path\u002Ffilepath\"\n    \"syscall\"\n\n    \"github.com\u002Fcontainerd\u002Fcontainerd\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Fcio\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Fnamespaces\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Foci\"\n    \"gopkg.in\u002Fyaml.v3\"\n)\n\n\u002F\u002F AppManifest represents vehicle app configuration\ntype AppManifest struct {\n    APIVersion string `yaml:\"apiVersion\"`\n    Kind       string `yaml:\"kind\"`\n    Metadata   struct {\n        Name        string `yaml:\"name\"`\n        Version     string `yaml:\"version\"`\n        DisplayName string `yaml:\"displayName\"`\n    } `yaml:\"metadata\"`\n    Spec struct {\n        Permissions []string `yaml:\"permissions\"`\n        Resources   struct {\n            Memory    string `yaml:\"memory\"`\n            CPU       string `yaml:\"cpu\"`\n            Storage   string `yaml:\"storage\"`\n            Bandwidth string `yaml:\"bandwidth\"`\n        } `yaml:\"resources\"`\n        Container struct {\n            Image       string   `yaml:\"image\"`\n            Entrypoint  []string `yaml:\"entrypoint\"`\n            Environment []struct {\n                Name  string `yaml:\"name\"`\n                Value string `yaml:\"value,omitempty\"`\n            } `yaml:\"environment\"`\n        } `yaml:\"container\"`\n        Safety struct {\n            DisableWhileDriving    bool `yaml:\"disableWhileDriving\"`\n            TouchInteractionLimit  bool `yaml:\"touchInteractionLimit\"`\n        } `yaml:\"safety\"`\n    } `yaml:\"spec\"`\n}\n\n\u002F\u002F AppRuntime manages vehicle app lifecycle\ntype AppRuntime struct {\n    client    *containerd.Client\n    namespace string\n}\n\n\u002F\u002F NewAppRuntime creates a new app runtime\nfunc NewAppRuntime() (*AppRuntime, error) {\n    client, err := containerd.New(\"\u002Frun\u002Fcontainerd\u002Fcontainerd.sock\")\n    if err != nil {\n        return nil, fmt.Errorf(\"failed to connect to containerd: %w\", err)\n    }\n\n    return &AppRuntime{\n        client:    client,\n        namespace: \"vehicle-apps\",\n    }, nil\n}\n\n\u002F\u002F InstallApp installs an app from manifest\nfunc (r *AppRuntime) InstallApp(manifestPath string) error {\n    \u002F\u002F Load manifest\n    manifest, err := r.loadManifest(manifestPath)\n    if err != nil {\n        return fmt.Errorf(\"failed to load manifest: %w\", err)\n    }\n\n    log.Printf(\"Installing app: %s v%s\", manifest.Metadata.Name, manifest.Metadata.Version)\n\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    \u002F\u002F Pull container image\n    image, err := r.client.Pull(ctx, manifest.Spec.Container.Image,\n        containerd.WithPullUnpack)\n    if err != nil {\n        return fmt.Errorf(\"failed to pull image: %w\", err)\n    }\n\n    log.Printf(\"Pulled image: %s\", image.Name())\n\n    \u002F\u002F Create container with security constraints\n    container, err := r.createSecureContainer(ctx, manifest, image)\n    if err != nil {\n        return fmt.Errorf(\"failed to create container: %w\", err)\n    }\n\n    log.Printf(\"App installed successfully: %s\", container.ID())\n    return nil\n}\n\n\u002F\u002F createSecureContainer creates a sandboxed container with security policies\nfunc (r *AppRuntime) createSecureContainer(\n    ctx context.Context,\n    manifest *AppManifest,\n    image containerd.Image,\n) (containerd.Container, error) {\n\n    appName := manifest.Metadata.Name\n\n    \u002F\u002F Define security policies based on permissions\n    opts := []oci.SpecOpts{\n        oci.WithImageConfig(image),\n        oci.WithEnv(r.buildEnvironment(manifest)),\n\n        \u002F\u002F Resource limits\n        oci.WithMemoryLimit(r.parseMemory(manifest.Spec.Resources.Memory)),\n        oci.WithCPUQuota(500000, 100000), \u002F\u002F 500m CPU\n\n        \u002F\u002F Security constraints\n        oci.WithNoNewPrivileges,\n        oci.WithPrivileged(false),\n\n        \u002F\u002F Read-only root filesystem\n        oci.WithRootFSReadonly(),\n\n        \u002F\u002F Drop all capabilities by default\n        oci.WithCapabilities([]string{}),\n\n        \u002F\u002F Add capabilities based on permissions\n        oci.WithAddedCapabilities(r.getCapabilities(manifest.Spec.Permissions)),\n\n        \u002F\u002F Mount tmpfs for writable directories\n        oci.WithMounts([]oci.Mount{\n            {\n                Type:        \"tmpfs\",\n                Source:      \"tmpfs\",\n                Destination: \"\u002Ftmp\",\n                Options:     []string{\"nosuid\", \"noexec\", \"nodev\"},\n            },\n            {\n                Type:        \"bind\",\n                Source:      filepath.Join(\"\u002Fvar\u002Flib\u002Fvehicle-apps\", appName, \"data\"),\n                Destination: \"\u002Fdata\",\n                Options:     []string{\"rbind\", \"rw\"},\n            },\n        }),\n\n        \u002F\u002F Namespace isolation\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"pid\",\n        }),\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"network\",\n        }),\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"ipc\",\n        }),\n    }\n\n    \u002F\u002F Permission-specific constraints\n    if !r.hasPermission(manifest.Spec.Permissions, \"INTERNET\") {\n        \u002F\u002F Block network access\n        opts = append(opts, oci.WithHostNamespace(oci.NetworkNamespace))\n    }\n\n    \u002F\u002F Create container\n    container, err := r.client.NewContainer(\n        ctx,\n        appName,\n        containerd.WithImage(image),\n        containerd.WithNewSnapshot(appName+\"-snapshot\", image),\n        containerd.WithNewSpec(opts...),\n    )\n\n    return container, err\n}\n\n\u002F\u002F StartApp starts an installed app\nfunc (r *AppRuntime) StartApp(appName string, manifest *AppManifest) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    \u002F\u002F Check safety constraints\n    if manifest.Spec.Safety.DisableWhileDriving {\n        if r.isVehicleMoving() {\n            return fmt.Errorf(\"app disabled while driving\")\n        }\n    }\n\n    \u002F\u002F Create task\n    task, err := container.NewTask(ctx, cio.NewCreator(cio.WithStdio))\n    if err != nil {\n        return fmt.Errorf(\"failed to create task: %w\", err)\n    }\n\n    \u002F\u002F Start task\n    if err := task.Start(ctx); err != nil {\n        return fmt.Errorf(\"failed to start task: %w\", err)\n    }\n\n    log.Printf(\"App started: %s (PID: %d)\", appName, task.Pid())\n    return nil\n}\n\n\u002F\u002F StopApp stops a running app\nfunc (r *AppRuntime) StopApp(appName string) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    task, err := container.Task(ctx, nil)\n    if err != nil {\n        return fmt.Errorf(\"failed to get task: %w\", err)\n    }\n\n    \u002F\u002F Graceful shutdown\n    if err := task.Kill(ctx, syscall.SIGTERM); err != nil {\n        return fmt.Errorf(\"failed to send SIGTERM: %w\", err)\n    }\n\n    \u002F\u002F Wait for exit (with timeout)\n    status, err := task.Wait(ctx)\n    if err != nil {\n        return fmt.Errorf(\"failed to wait for exit: %w\", err)\n    }\n\n    \u003C-status\n\n    log.Printf(\"App stopped: %s\", appName)\n    return nil\n}\n\n\u002F\u002F UninstallApp removes an installed app\nfunc (r *AppRuntime) UninstallApp(appName string) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    \u002F\u002F Stop if running\n    _ = r.StopApp(appName)\n\n    \u002F\u002F Delete container\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    if err := container.Delete(ctx, containerd.WithSnapshotCleanup); err != nil {\n        return fmt.Errorf(\"failed to delete container: %w\", err)\n    }\n\n    log.Printf(\"App uninstalled: %s\", appName)\n    return nil\n}\n\n\u002F\u002F Helper functions\n\nfunc (r *AppRuntime) loadManifest(path string) (*AppManifest, error) {\n    data, err := os.ReadFile(path)\n    if err != nil {\n        return nil, err\n    }\n\n    var manifest AppManifest\n    if err := yaml.Unmarshal(data, &manifest); err != nil {\n        return nil, err\n    }\n\n    return &manifest, nil\n}\n\nfunc (r *AppRuntime) buildEnvironment(manifest *AppManifest) []string {\n    env := []string{}\n    for _, e := range manifest.Spec.Container.Environment {\n        env = append(env, fmt.Sprintf(\"%s=%s\", e.Name, e.Value))\n    }\n    return env\n}\n\nfunc (r *AppRuntime) parseMemory(mem string) uint64 {\n    \u002F\u002F Simple parser for Mi\u002FGi units\n    \u002F\u002F In production, use proper parsing\n    return 512 * 1024 * 1024 \u002F\u002F 512Mi\n}\n\nfunc (r *AppRuntime) getCapabilities(permissions []string) []string {\n    caps := []string{}\n\n    for _, perm := range permissions {\n        switch perm {\n        case \"INTERNET\":\n            caps = append(caps, \"CAP_NET_BIND_SERVICE\")\n        case \"BLUETOOTH\":\n            caps = append(caps, \"CAP_NET_ADMIN\")\n        case \"AUDIO_PLAYBACK\":\n            \u002F\u002F Allow access to audio devices\n        }\n    }\n\n    return caps\n}\n\nfunc (r *AppRuntime) hasPermission(permissions []string, perm string) bool {\n    for _, p := range permissions {\n        if p == perm {\n            return true\n        }\n    }\n    return false\n}\n\nfunc (r *AppRuntime) isVehicleMoving() bool {\n    \u002F\u002F Check vehicle speed from CAN bus\n    \u002F\u002F Placeholder implementation\n    return false\n}\n\nfunc main() {\n    runtime, err := NewAppRuntime()\n    if err != nil {\n        log.Fatalf(\"Failed to create runtime: %v\", err)\n    }\n\n    \u002F\u002F Example: Install and start app\n    if err := runtime.InstallApp(\"spotify-manifest.yaml\"); err != nil {\n        log.Fatalf(\"Failed to install app: %v\", err)\n    }\n\n    \u002F\u002F Load manifest for safety checks\n    manifest, _ := runtime.loadManifest(\"spotify-manifest.yaml\")\n\n    if err := runtime.StartApp(\"spotify-automotive\", manifest); err != nil {\n        log.Fatalf(\"Failed to start app: %v\", err)\n    }\n\n    log.Println(\"App runtime running...\")\n    select {} \u002F\u002F Keep running\n}\n```\n\n### 4. Developer SDK Example (TypeScript)\n\n```typescript\n\u002F\u002F Vehicle App Developer SDK\n\u002F\u002F File: vehicle-app-sdk.ts\n\n\u002F**\n * Vehicle App SDK for TypeScript\u002FJavaScript apps\n * Provides APIs for vehicle integration\n *\u002F\n\nexport enum Permission {\n  AUDIO_PLAYBACK = 'AUDIO_PLAYBACK',\n  INTERNET = 'INTERNET',\n  BLUETOOTH = 'BLUETOOTH',\n  VEHICLE_SPEED = 'VEHICLE_SPEED',\n  LOCATION = 'LOCATION',\n  STEERING_CONTROLS = 'STEERING_CONTROLS',\n  CLIMATE_CONTROL = 'CLIMATE_CONTROL',\n}\n\nexport interface VehicleState {\n  speed: number; \u002F\u002F km\u002Fh\n  gear: string;\n  isMoving: boolean;\n  batteryLevel: number; \u002F\u002F percentage\n  range: number; \u002F\u002F km\n}\n\nexport class VehicleAppSDK {\n  private readonly appId: string;\n  private readonly permissions: Permission[];\n  private ws: WebSocket | null = null;\n\n  constructor(appId: string, permissions: Permission[]) {\n    this.appId = appId;\n    this.permissions = permissions;\n  }\n\n  \u002F**\n   * Initialize SDK connection to vehicle platform\n   *\u002F\n  async initialize(): Promise\u003Cvoid> {\n    console.log(`Initializing SDK for app: ${this.appId}`);\n\n    \u002F\u002F Connect to vehicle platform via WebSocket\n    this.ws = new WebSocket('ws:\u002F\u002Fvehicle-platform:8080\u002Fapps\u002Fws');\n\n    return new Promise((resolve, reject) => {\n      this.ws!.onopen = () => {\n        console.log('Connected to vehicle platform');\n\n        \u002F\u002F Send authentication\n        this.ws!.send(JSON.stringify({\n          type: 'auth',\n          appId: this.appId,\n          permissions: this.permissions,\n        }));\n\n        resolve();\n      };\n\n      this.ws!.onerror = (error) => {\n        reject(new Error(`WebSocket error: ${error}`));\n      };\n    });\n  }\n\n  \u002F**\n   * Get current vehicle state\n   *\u002F\n  async getVehicleState(): Promise\u003CVehicleState> {\n    this.checkPermission(Permission.VEHICLE_SPEED);\n\n    return new Promise((resolve, reject) => {\n      const requestId = Date.now().toString();\n\n      this.ws!.send(JSON.stringify({\n        type: 'request',\n        requestId,\n        method: 'getVehicleState',\n      }));\n\n      const handler = (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        if (data.requestId === requestId) {\n          this.ws!.removeEventListener('message', handler);\n          resolve(data.result);\n        }\n      };\n\n      this.ws!.addEventListener('message', handler);\n\n      \u002F\u002F Timeout after 5 seconds\n      setTimeout(() => {\n        this.ws!.removeEventListener('message', handler);\n        reject(new Error('Request timeout'));\n      }, 5000);\n    });\n  }\n\n  \u002F**\n   * Subscribe to vehicle state changes\n   *\u002F\n  onVehicleStateChange(callback: (state: VehicleState) => void): void {\n    this.checkPermission(Permission.VEHICLE_SPEED);\n\n    this.ws!.addEventListener('message', (event) => {\n      const data = JSON.parse(event.data);\n      if (data.type === 'vehicleStateUpdate') {\n        callback(data.state);\n      }\n    });\n\n    \u002F\u002F Subscribe\n    this.ws!.send(JSON.stringify({\n      type: 'subscribe',\n      topic: 'vehicleState',\n    }));\n  }\n\n  \u002F**\n   * Control audio playback\n   *\u002F\n  async playAudio(url: string): Promise\u003Cvoid> {\n    this.checkPermission(Permission.AUDIO_PLAYBACK);\n\n    await this.sendRequest('playAudio', { url });\n  }\n\n  \u002F**\n   * Subscribe to steering control events\n   *\u002F\n  onSteeringControl(callback: (action: string) => void): void {\n    this.checkPermission(Permission.STEERING_CONTROLS);\n\n    this.ws!.addEventListener('message', (event) => {\n      const data = JSON.parse(event.data);\n      if (data.type === 'steeringControl') {\n        callback(data.action); \u002F\u002F 'next', 'previous', 'play', 'pause'\n      }\n    });\n\n    this.ws!.send(JSON.stringify({\n      type: 'subscribe',\n      topic: 'steeringControls',\n    }));\n  }\n\n  \u002F**\n   * Display notification in vehicle cluster\n   *\u002F\n  async showNotification(title: string, message: string): Promise\u003Cvoid> {\n    await this.sendRequest('showNotification', { title, message });\n  }\n\n  \u002F**\n   * Get current location\n   *\u002F\n  async getLocation(): Promise\u003C{ latitude: number; longitude: number }> {\n    this.checkPermission(Permission.LOCATION);\n\n    const result = await this.sendRequest('getLocation', {});\n    return result as { latitude: number; longitude: number };\n  }\n\n  private checkPermission(permission: Permission): void {\n    if (!this.permissions.includes(permission)) {\n      throw new Error(`Permission not granted: ${permission}`);\n    }\n  }\n\n  private async sendRequest(method: string, params: any): Promise\u003Cany> {\n    return new Promise((resolve, reject) => {\n      const requestId = Date.now().toString();\n\n      this.ws!.send(JSON.stringify({\n        type: 'request',\n        requestId,\n        method,\n        params,\n      }));\n\n      const handler = (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        if (data.requestId === requestId) {\n          this.ws!.removeEventListener('message', handler);\n\n          if (data.error) {\n            reject(new Error(data.error));\n          } else {\n            resolve(data.result);\n          }\n        }\n      };\n\n      this.ws!.addEventListener('message', handler);\n\n      setTimeout(() => {\n        this.ws!.removeEventListener('message', handler);\n        reject(new Error('Request timeout'));\n      }, 5000);\n    });\n  }\n}\n\n\u002F\u002F Example app using SDK\nasync function exampleApp() {\n  const sdk = new VehicleAppSDK('spotify-automotive', [\n    Permission.AUDIO_PLAYBACK,\n    Permission.STEERING_CONTROLS,\n    Permission.VEHICLE_SPEED,\n  ]);\n\n  await sdk.initialize();\n\n  \u002F\u002F Get vehicle state\n  const state = await sdk.getVehicleState();\n  console.log(`Vehicle speed: ${state.speed} km\u002Fh`);\n\n  \u002F\u002F Subscribe to steering controls\n  sdk.onSteeringControl((action) => {\n    console.log(`Steering control: ${action}`);\n    if (action === 'play') {\n      sdk.playAudio('https:\u002F\u002Fcdn.spotify.com\u002Ftrack\u002F123.mp3');\n    }\n  });\n\n  \u002F\u002F Monitor vehicle state\n  sdk.onVehicleStateChange((state) => {\n    if (state.speed > 100) {\n      \u002F\u002F Duck audio volume at high speeds\n      console.log('High speed detected, reducing volume');\n    }\n  });\n}\n```\n\n## Real-World Examples\n\n### Tesla App Store Strategy\n- **Built-in apps**: Native Tesla apps (Netflix, YouTube, Spotify)\n- **No third-party yet**: Closed ecosystem for quality control\n- **Game integration**: Steam integration announced for Model S\u002FX\n- **API access**: Limited fleet API for developers\n\n### GM Ultifi Platform\n- **Open developer program**: Third-party app marketplace\n- **Revenue sharing**: 70\u002F30 split (developer\u002FGM)\n- **SDK availability**: Public SDK with APIs for vehicle data\n- **Categories**: Navigation, media, productivity, games\n\n### VW.OS App Store\n- **Phased rollout**: Starting with MEB platform (ID. series)\n- **Partner apps**: Curated partners initially\n- **In-car payment**: Integrated billing system\n- **Cross-brand**: Shared across VW Group brands\n\n### Rivian App Shop\n- **Adventure focus**: Apps for off-road, camping, outdoor\n- **Fleet integration**: Apps for commercial R1T owners\n- **OTA updates**: Apps update independently of vehicle software\n\n## Best Practices\n\n1. **Strict permission model**: Request only necessary permissions\n2. **Sandboxed execution**: Isolate apps from vehicle systems\n3. **Resource limits**: Enforce memory, CPU, bandwidth limits\n4. **Safety first**: Disable\u002Flimit apps while driving\n5. **Certification process**: Manual security review before approval\n6. **Privacy protection**: Transparent data collection policies\n7. **Offline functionality**: Apps should work without connectivity\n8. **Graceful degradation**: Handle missing permissions elegantly\n9. **Update mechanism**: Automatic updates for security patches\n10. **Rollback support**: Ability to rollback problematic updates\n\n## Security Considerations\n\n- **Code signing**: All apps must be signed by developer\n- **Runtime verification**: Verify signatures before execution\n- **Capability-based security**: Grant minimal capabilities\n- **Network isolation**: Apps cannot access vehicle CAN bus directly\n- **Data encryption**: Encrypt app data at rest\n- **Audit logging**: Log all permission requests and usage\n- **Kill switch**: Remote ability to disable compromised apps\n\n## References\n\n- **Android Automotive**: https:\u002F\u002Fsource.android.com\u002Fdevices\u002Fautomotive\n- **COVESA**: https:\u002F\u002Fcovesa.global\u002F\n- **GENIVI**: https:\u002F\u002Fwww.genivi.org\u002F\n- **Eclipse SDV**: https:\u002F\u002Fsdv.eclipse.org\u002F\n\n---\n\n## Vehicle Middleware Platforms\n\n# Vehicle Middleware Platforms — SDV Middleware Stacks\n\nExpert knowledge of SDV middleware stacks (COVESA VSS, Eclipse SDV, AUTOSAR Adaptive), data models (VSS\u002FVISS), pub-sub brokers, and service mesh for vehicles.\n\n## Core Concepts\n\n### Middleware Components\n\n1. **Data Abstraction**: VSS (Vehicle Signal Specification)\n2. **Service Communication**: SOME\u002FIP, DDS, MQTT\n3. **Service Discovery**: mDNS, service registries\n4. **Security**: TLS, authentication, authorization\n5. **Orchestration**: Lifecycle management\n\n### Key Standards\n\n- **COVESA VSS**: Standardized vehicle data model\n- **COVESA VISS**: Vehicle Information Service Specification (API)\n- **Eclipse SDV**: Open-source SDV components\n- **AUTOSAR Adaptive**: Service-oriented automotive architecture\n\n## Production-Ready Implementation\n\n### 1. VSS Data Model Implementation\n\n```yaml\n# Vehicle Signal Specification (VSS) tree\n# File: vehicle-signals.vspec\n\nVehicle:\n  description: Top-level vehicle\n  type: branch\n\nVehicle.Speed:\n  datatype: float\n  type: sensor\n  unit: km\u002Fh\n  description: Vehicle speed\n  min: 0\n  max: 300\n\nVehicle.Powertrain:\n  type: branch\n  description: Powertrain signals\n\nVehicle.Powertrain.Battery:\n  type: branch\n  description: Battery system\n\nVehicle.Powertrain.Battery.StateOfCharge:\n  datatype: float\n  type: sensor\n  unit: percent\n  description: Battery state of charge\n  min: 0\n  max: 100\n\nVehicle.Powertrain.Battery.Voltage:\n  datatype: float\n  type: sensor\n  unit: V\n  description: Battery voltage\n  min: 0\n  max: 800\n\nVehicle.Powertrain.Battery.Current:\n  datatype: float\n  type: sensor\n  unit: A\n  description: Battery current (positive = charging)\n  min: -400\n  max: 400\n\nVehicle.Powertrain.Battery.Temperature:\n  datatype: float\n  type: sensor\n  unit: celsius\n  description: Battery temperature\n  min: -40\n  max: 80\n\nVehicle.Cabin:\n  type: branch\n  description: Cabin signals\n\nVehicle.Cabin.HVAC:\n  type: branch\n  description: HVAC system\n\nVehicle.Cabin.HVAC.IsAirConditioningActive:\n  datatype: boolean\n  type: actuator\n  description: Air conditioning status\n\nVehicle.Cabin.HVAC.AmbientAirTemperature:\n  datatype: float\n  type: sensor\n  unit: celsius\n  description: Ambient temperature\n\nVehicle.Body:\n  type: branch\n  description: Body signals\n\nVehicle.Body.Doors:\n  type: branch\n  instances:\n    - Row1Left\n    - Row1Right\n    - Row2Left\n    - Row2Right\n\nVehicle.Body.Doors.IsLocked:\n  datatype: boolean\n  type: actuator\n  description: Door lock status\n\nVehicle.Body.Doors.IsOpen:\n  datatype: boolean\n  type: sensor\n  description: Door open status\n\nVehicle.ADAS:\n  type: branch\n  description: ADAS signals\n\nVehicle.ADAS.CruiseControl:\n  type: branch\n  description: Cruise control\n\nVehicle.ADAS.CruiseControl.IsActive:\n  datatype: boolean\n  type: actuator\n  description: Cruise control active\n\nVehicle.ADAS.CruiseControl.SpeedSet:\n  datatype: float\n  type: actuator\n  unit: km\u002Fh\n  description: Set cruise control speed\n```\n\n### 2. VSS Data Broker (Rust)\n\n```rust\n\u002F\u002F VSS data broker implementation\n\u002F\u002F File: vss-broker\u002Fsrc\u002Fmain.rs\n\nuse tokio;\nuse std::collections::HashMap;\nuse std::sync::{Arc, RwLock};\nuse serde::{Deserialize, Serialize};\nuse warp::Filter;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\nstruct VehicleSignal {\n    path: String,\n    value: SignalValue,\n    timestamp: u64,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\nenum SignalValue {\n    Float(f64),\n    Int(i64),\n    Bool(bool),\n    String(String),\n}\n\n#[derive(Clone)]\nstruct DataBroker {\n    signals: Arc\u003CRwLock\u003CHashMap\u003CString, VehicleSignal>>>,\n    subscribers: Arc\u003CRwLock\u003CHashMap\u003CString, Vec\u003Ctokio::sync::mpsc::UnboundedSender\u003CVehicleSignal>>>>>,\n}\n\nimpl DataBroker {\n    fn new() -> Self {\n        DataBroker {\n            signals: Arc::new(RwLock::new(HashMap::new())),\n            subscribers: Arc::new(RwLock::new(HashMap::new())),\n        }\n    }\n\n    \u002F\u002F\u002F Get signal value\n    fn get(&self, path: &str) -> Option\u003CVehicleSignal> {\n        let signals = self.signals.read().unwrap();\n        signals.get(path).cloned()\n    }\n\n    \u002F\u002F\u002F Set signal value\n    fn set(&self, signal: VehicleSignal) {\n        let path = signal.path.clone();\n\n        \u002F\u002F Store signal\n        {\n            let mut signals = self.signals.write().unwrap();\n            signals.insert(path.clone(), signal.clone());\n        }\n\n        \u002F\u002F Notify subscribers\n        self.notify_subscribers(&path, signal);\n    }\n\n    \u002F\u002F\u002F Subscribe to signal updates\n    fn subscribe(&self, path: String) -> tokio::sync::mpsc::UnboundedReceiver\u003CVehicleSignal> {\n        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();\n\n        let mut subscribers = self.subscribers.write().unwrap();\n        subscribers.entry(path).or_insert_with(Vec::new).push(tx);\n\n        rx\n    }\n\n    \u002F\u002F\u002F Notify subscribers of signal update\n    fn notify_subscribers(&self, path: &str, signal: VehicleSignal) {\n        let subscribers = self.subscribers.read().unwrap();\n\n        if let Some(subs) = subscribers.get(path) {\n            for tx in subs {\n                let _ = tx.send(signal.clone());\n            }\n        }\n\n        \u002F\u002F Also notify wildcard subscribers (path.*)\n        let parts: Vec\u003C&str> = path.split('.').collect();\n        for i in 0..parts.len() {\n            let wildcard_path = format!(\"{}.*\", parts[..i].join(\".\"));\n            if let Some(subs) = subscribers.get(&wildcard_path) {\n                for tx in subs {\n                    let _ = tx.send(signal.clone());\n                }\n            }\n        }\n    }\n\n    \u002F\u002F\u002F Batch get signals\n    fn get_batch(&self, paths: Vec\u003CString>) -> HashMap\u003CString, VehicleSignal> {\n        let signals = self.signals.read().unwrap();\n        let mut result = HashMap::new();\n\n        for path in paths {\n            if let Some(signal) = signals.get(&path) {\n                result.insert(path, signal.clone());\n            }\n        }\n\n        result\n    }\n}\n\n#[tokio::main]\nasync fn main() {\n    let broker = DataBroker::new();\n    let broker = Arc::new(broker);\n\n    \u002F\u002F REST API routes\n    let broker_filter = warp::any().map(move || broker.clone());\n\n    \u002F\u002F GET \u002Fapi\u002Fsignals\u002F{path}\n    let get_signal = warp::path!(\"api\" \u002F \"signals\" \u002F String)\n        .and(warp::get())\n        .and(broker_filter.clone())\n        .map(|path: String, broker: Arc\u003CDataBroker>| {\n            match broker.get(&path) {\n                Some(signal) => warp::reply::json(&signal),\n                None => warp::reply::json(&serde_json::json!({\n                    \"error\": \"Signal not found\"\n                })),\n            }\n        });\n\n    \u002F\u002F POST \u002Fapi\u002Fsignals\n    let set_signal = warp::path!(\"api\" \u002F \"signals\")\n        .and(warp::post())\n        .and(warp::body::json())\n        .and(broker_filter.clone())\n        .map(|signal: VehicleSignal, broker: Arc\u003CDataBroker>| {\n            broker.set(signal.clone());\n            warp::reply::json(&serde_json::json!({\n                \"status\": \"ok\",\n                \"path\": signal.path\n            }))\n        });\n\n    \u002F\u002F WebSocket \u002Fapi\u002Fsubscribe\n    let subscribe = warp::path!(\"api\" \u002F \"subscribe\")\n        .and(warp::ws())\n        .and(broker_filter.clone())\n        .map(|ws: warp::ws::Ws, broker: Arc\u003CDataBroker>| {\n            ws.on_upgrade(move |socket| handle_websocket(socket, broker))\n        });\n\n    let routes = get_signal\n        .or(set_signal)\n        .or(subscribe);\n\n    println!(\"[VSS Broker] Starting on 0.0.0.0:8080\");\n    warp::serve(routes)\n        .run(([0, 0, 0, 0], 8080))\n        .await;\n}\n\nasync fn handle_websocket(\n    websocket: warp::ws::WebSocket,\n    broker: Arc\u003CDataBroker>\n) {\n    use futures::{StreamExt, SinkExt};\n\n    let (mut tx, mut rx) = websocket.split();\n\n    \u002F\u002F Handle incoming subscription requests\n    while let Some(result) = rx.next().await {\n        let msg = match result {\n            Ok(msg) => msg,\n            Err(e) => {\n                eprintln!(\"WebSocket error: {}\", e);\n                break;\n            }\n        };\n\n        if let Ok(text) = msg.to_str() {\n            \u002F\u002F Parse subscription request\n            if let Ok(req) = serde_json::from_str::\u003Cserde_json::Value>(text) {\n                if let Some(path) = req[\"path\"].as_str() {\n                    let path = path.to_string();\n                    let mut signal_rx = broker.subscribe(path.clone());\n\n                    \u002F\u002F Send updates\n                    tokio::spawn(async move {\n                        while let Some(signal) = signal_rx.recv().await {\n                            let json = serde_json::to_string(&signal).unwrap();\n                            if tx.send(warp::ws::Message::text(json)).await.is_err() {\n                                break;\n                            }\n                        }\n                    });\n                }\n            }\n        }\n    }\n}\n```\n\n### 3. VISS Server (Python\u002FFastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVISS (Vehicle Information Service Specification) server.\nRESTful and WebSocket API for VSS data access.\n\"\"\"\n\nfrom fastapi import FastAPI, WebSocket, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\nfrom typing import Optional, List, Dict, Any\nimport asyncio\nimport json\nfrom datetime import datetime\n\n\napp = FastAPI(title=\"VISS Server\", version=\"2.0.0\")\n\n\nclass VehicleSignal(BaseModel):\n    \"\"\"Vehicle signal data model.\"\"\"\n    path: str\n    value: Any\n    timestamp: Optional[int] = None\n\n\nclass GetRequest(BaseModel):\n    \"\"\"VISS GET request.\"\"\"\n    action: str = \"get\"\n    path: str\n    requestId: str\n\n\nclass SetRequest(BaseModel):\n    \"\"\"VISS SET request.\"\"\"\n    action: str = \"set\"\n    path: str\n    value: Any\n    requestId: str\n\n\nclass SubscribeRequest(BaseModel):\n    \"\"\"VISS SUBSCRIBE request.\"\"\"\n    action: str = \"subscribe\"\n    path: str\n    subscriptionId: str\n\n\n# In-memory signal storage (replace with Redis in production)\nsignals_db: Dict[str, VehicleSignal] = {}\n\n# WebSocket subscriptions\nsubscriptions: Dict[str, List[WebSocket]] = {}\n\n\n@app.get(\"\u002Fvss\u002Fapi\u002Fv2\u002F{path:path}\")\nasync def get_signal_rest(path: str):\n    \"\"\"\n    Get signal value via REST API.\n\n    Example: GET \u002Fvss\u002Fapi\u002Fv2\u002FVehicle\u002FSpeed\n    \"\"\"\n    if path not in signals_db:\n        raise HTTPException(status_code=404, detail=\"Signal not found\")\n\n    signal = signals_db[path]\n\n    return JSONResponse({\n        \"action\": \"get\",\n        \"path\": path,\n        \"value\": signal.value,\n        \"timestamp\": signal.timestamp or int(datetime.utcnow().timestamp() * 1000),\n        \"requestId\": \"rest-\" + str(int(datetime.utcnow().timestamp()))\n    })\n\n\n@app.put(\"\u002Fvss\u002Fapi\u002Fv2\u002F{path:path}\")\nasync def set_signal_rest(path: str, value: Any):\n    \"\"\"\n    Set signal value via REST API.\n\n    Example: PUT \u002Fvss\u002Fapi\u002Fv2\u002FVehicle\u002FCabin\u002FHVAC\u002FIsAirConditioningActive\n    Body: {\"value\": true}\n    \"\"\"\n    signal = VehicleSignal(\n        path=path,\n        value=value,\n        timestamp=int(datetime.utcnow().timestamp() * 1000)\n    )\n\n    signals_db[path] = signal\n\n    # Notify subscribers\n    await notify_subscribers(path, signal)\n\n    return JSONResponse({\n        \"action\": \"set\",\n        \"path\": path,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": \"rest-\" + str(int(datetime.utcnow().timestamp()))\n    })\n\n\n@app.websocket(\"\u002Fvss\u002Fapi\u002Fv2\")\nasync def websocket_endpoint(websocket: WebSocket):\n    \"\"\"\n    VISS WebSocket endpoint for real-time communication.\n\n    Supports:\n    - GET: Get signal value\n    - SET: Set signal value\n    - SUBSCRIBE: Subscribe to signal updates\n    - UNSUBSCRIBE: Unsubscribe from signal\n    \"\"\"\n    await websocket.accept()\n\n    try:\n        while True:\n            # Receive request\n            data = await websocket.receive_text()\n            request = json.loads(data)\n\n            action = request.get(\"action\")\n\n            if action == \"get\":\n                await handle_get(websocket, request)\n            elif action == \"set\":\n                await handle_set(websocket, request)\n            elif action == \"subscribe\":\n                await handle_subscribe(websocket, request)\n            elif action == \"unsubscribe\":\n                await handle_unsubscribe(websocket, request)\n            else:\n                await websocket.send_json({\n                    \"error\": {\"number\": 400, \"message\": \"Invalid action\"},\n                    \"requestId\": request.get(\"requestId\", \"unknown\")\n                })\n\n    except Exception as e:\n        print(f\"[VISS] WebSocket error: {e}\")\n    finally:\n        # Clean up subscriptions\n        for path, subs in subscriptions.items():\n            if websocket in subs:\n                subs.remove(websocket)\n\n\nasync def handle_get(websocket: WebSocket, request: dict):\n    \"\"\"Handle GET request.\"\"\"\n    path = request[\"path\"]\n\n    if path not in signals_db:\n        await websocket.send_json({\n            \"action\": \"get\",\n            \"error\": {\"number\": 404, \"message\": \"Signal not found\"},\n            \"requestId\": request[\"requestId\"]\n        })\n        return\n\n    signal = signals_db[path]\n\n    await websocket.send_json({\n        \"action\": \"get\",\n        \"path\": path,\n        \"value\": signal.value,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": request[\"requestId\"]\n    })\n\n\nasync def handle_set(websocket: WebSocket, request: dict):\n    \"\"\"Handle SET request.\"\"\"\n    path = request[\"path\"]\n    value = request[\"value\"]\n\n    signal = VehicleSignal(\n        path=path,\n        value=value,\n        timestamp=int(datetime.utcnow().timestamp() * 1000)\n    )\n\n    signals_db[path] = signal\n\n    # Notify subscribers\n    await notify_subscribers(path, signal)\n\n    await websocket.send_json({\n        \"action\": \"set\",\n        \"path\": path,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": request[\"requestId\"]\n    })\n\n\nasync def handle_subscribe(websocket: WebSocket, request: dict):\n    \"\"\"Handle SUBSCRIBE request.\"\"\"\n    path = request[\"path\"]\n    subscription_id = request[\"subscriptionId\"]\n\n    # Add to subscriptions\n    if path not in subscriptions:\n        subscriptions[path] = []\n\n    subscriptions[path].append(websocket)\n\n    # Send confirmation\n    await websocket.send_json({\n        \"action\": \"subscribe\",\n        \"subscriptionId\": subscription_id,\n        \"timestamp\": int(datetime.utcnow().timestamp() * 1000)\n    })\n\n\nasync def handle_unsubscribe(websocket: WebSocket, request: dict):\n    \"\"\"Handle UNSUBSCRIBE request.\"\"\"\n    subscription_id = request[\"subscriptionId\"]\n\n    # Remove from subscriptions\n    for path, subs in subscriptions.items():\n        if websocket in subs:\n            subs.remove(websocket)\n\n    await websocket.send_json({\n        \"action\": \"unsubscribe\",\n        \"subscriptionId\": subscription_id,\n        \"timestamp\": int(datetime.utcnow().timestamp() * 1000)\n    })\n\n\nasync def notify_subscribers(path: str, signal: VehicleSignal):\n    \"\"\"Notify all subscribers of signal update.\"\"\"\n    if path in subscriptions:\n        notification = {\n            \"action\": \"subscription\",\n            \"path\": path,\n            \"value\": signal.value,\n            \"timestamp\": signal.timestamp\n        }\n\n        # Send to all subscribers\n        dead_sockets = []\n        for websocket in subscriptions[path]:\n            try:\n                await websocket.send_json(notification)\n            except Exception:\n                dead_sockets.append(websocket)\n\n        # Remove dead sockets\n        for ws in dead_sockets:\n            subscriptions[path].remove(ws)\n\n\n# Populate some initial data\n@app.on_event(\"startup\")\nasync def populate_initial_data():\n    \"\"\"Populate initial vehicle signals.\"\"\"\n    initial_signals = [\n        VehicleSignal(path=\"Vehicle.Speed\", value=0.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.StateOfCharge\", value=80.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.Voltage\", value=400.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.Current\", value=0.0),\n        VehicleSignal(path=\"Vehicle.Cabin.HVAC.IsAirConditioningActive\", value=False),\n        VehicleSignal(path=\"Vehicle.Body.Doors.Row1Left.IsLocked\", value=True),\n        VehicleSignal(path=\"Vehicle.ADAS.CruiseControl.IsActive\", value=False),\n    ]\n\n    for signal in initial_signals:\n        signal.timestamp = int(datetime.utcnow().timestamp() * 1000)\n        signals_db[signal.path] = signal\n\n    print(\"[VISS] Initial signals populated\")\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### 4. Service Mesh Configuration (Istio-like for Automotive)\n\n```yaml\n# Service mesh configuration for vehicle platform\n# File: vehicle-service-mesh.yaml\n\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: service-mesh-config\n  namespace: vehicle-platform\ndata:\n  mesh-config.yaml: |\n    # Global mesh configuration\n    defaultConfig:\n      discoveryAddress: mesh-pilot.vehicle-platform.svc:15010\n      tracing:\n        zipkin:\n          address: zipkin.vehicle-platform.svc:9411\n      proxyMetadata:\n        ISTIO_META_DNS_CAPTURE: \"true\"\n        ISTIO_META_DNS_AUTO_ALLOCATE: \"true\"\n\n    # Access logging\n    accessLogFile: \u002Fdev\u002Fstdout\n    accessLogEncoding: JSON\n\n    # mTLS configuration\n    enableAutoMtls: true\n\n    # Trust domain\n    trustDomain: vehicle.local\n\n    # Service discovery\n    defaultServiceExportTo:\n      - \"*\"\n\n---\napiVersion: networking.istio.io\u002Fv1alpha3\nkind: VirtualService\nmetadata:\n  name: vss-broker\nspec:\n  hosts:\n    - vss-broker.vehicle-platform.svc\n  http:\n    - match:\n        - uri:\n            prefix: \u002Fapi\u002Fsignals\n      route:\n        - destination:\n            host: vss-broker.vehicle-platform.svc\n            port:\n              number: 8080\n      timeout: 5s\n      retries:\n        attempts: 3\n        perTryTimeout: 2s\n\n---\napiVersion: networking.istio.io\u002Fv1alpha3\nkind: DestinationRule\nmetadata:\n  name: vss-broker\nspec:\n  host: vss-broker.vehicle-platform.svc\n  trafficPolicy:\n    loadBalancer:\n      simple: ROUND_ROBIN\n    connectionPool:\n      tcp:\n        maxConnections: 100\n      http:\n        http1MaxPendingRequests: 50\n        http2MaxRequests: 100\n    outlierDetection:\n      consecutiveErrors: 5\n      interval: 30s\n      baseEjectionTime: 60s\n      maxEjectionPercent: 50\n\n---\napiVersion: security.istio.io\u002Fv1beta1\nkind: PeerAuthentication\nmetadata:\n  name: default\n  namespace: vehicle-platform\nspec:\n  mtls:\n    mode: STRICT\n\n---\napiVersion: security.istio.io\u002Fv1beta1\nkind: AuthorizationPolicy\nmetadata:\n  name: vss-access-control\n  namespace: vehicle-platform\nspec:\n  selector:\n    matchLabels:\n      app: vss-broker\n  action: ALLOW\n  rules:\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Finfotainment\u002Fsa\u002Fspotify\"]\n      to:\n        - operation:\n            methods: [\"GET\"]\n            paths: [\"\u002Fapi\u002Fsignals\u002FVehicle\u002FSpeed\"]\n```\n\n### 5. Eclipse Kuksa Integration\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nEclipse Kuksa.VAL integration for VSS data access.\n\"\"\"\n\nimport asyncio\nfrom kuksa_client.grpc import VSSClient\nfrom kuksa_client.grpc.aio import VSSClientAsync\n\n\nasync def main():\n    \"\"\"Example Kuksa.VAL client.\"\"\"\n\n    # Connect to Kuksa databroker\n    async with VSSClientAsync('127.0.0.1', 55555) as client:\n        print(\"[Kuksa] Connected to data broker\")\n\n        # Set signal value\n        await client.set_current_values({\n            'Vehicle.Speed': 65.5,\n            'Vehicle.Powertrain.Battery.StateOfCharge': 75.0\n        })\n\n        print(\"[Kuksa] Signals set\")\n\n        # Get signal value\n        response = await client.get_current_values([\n            'Vehicle.Speed',\n            'Vehicle.Powertrain.Battery.StateOfCharge'\n        ])\n\n        for entry in response.entries:\n            print(f\"[Kuksa] {entry.path} = {entry.value.double}\")\n\n        # Subscribe to signal\n        async for updates in client.subscribe_current_values([\n            'Vehicle.Speed'\n        ]):\n            for update in updates.updates:\n                print(f\"[Kuksa] Update: {update.entry.path} = {update.entry.value.double}\")\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## Real-World Examples\n\n### COVESA (Connected Vehicle Systems Alliance)\n- **VSS Standard**: De facto vehicle data model\n- **VISS API**: RESTful and WebSocket access to VSS\n- **Industry adoption**: BMW, Ford, Tesla, VW all exploring VSS\n\n### Eclipse SDV Working Group\n- **Kuksa.VAL**: Reference VSS data broker\n- **Eclipse Leda**: SDV platform distribution\n- **Eclipse Ankaios**: Workload orchestrator\n- **Eclipse Zenoh**: Unified communication middleware\n\n### AUTOSAR Adaptive\n- **Service-oriented**: Pub\u002Fsub and RPC services\n- **SOME\u002FIP**: Scalable service-oriented middleware\n- **Ara::Com**: Communication management API\n- **Service discovery**: Dynamic service registration\n\n### Apex.AI\n- **ROS 2 for automotive**: Safe, real-time ROS 2\n- **DDS middleware**: OMG Data Distribution Service\n- **Apex.OS**: Automotive-grade Linux + ROS 2\n\n## Best Practices\n\n1. **Use VSS**: Standardize on VSS data model\n2. **Service mesh**: Use service mesh for inter-service communication\n3. **mTLS everywhere**: Mutual TLS for all service communication\n4. **API gateway**: Centralized API management\n5. **Rate limiting**: Protect services from overload\n6. **Circuit breakers**: Handle service failures gracefully\n7. **Observability**: Distributed tracing (Zipkin, Jaeger)\n8. **Service discovery**: Dynamic service registration\n9. **Version management**: API versioning strategy\n10. **Documentation**: OpenAPI specs for all services\n\n## Security Considerations\n\n- **mTLS**: Mutual authentication between services\n- **RBAC**: Role-based access control for VSS signals\n- **API keys**: Authenticate app access to services\n- **Rate limiting**: Prevent abuse\n- **Audit logging**: Log all signal access\n- **Encryption**: Encrypt sensitive signals at rest\n- **Network policies**: Restrict service-to-service communication\n\n## References\n\n- **COVESA VSS**: https:\u002F\u002Fcovesa.global\u002F\n- **Eclipse Kuksa**: https:\u002F\u002Fwww.eclipse.org\u002Fkuksa\u002F\n- **Eclipse SDV**: https:\u002F\u002Fsdv.eclipse.org\u002F\n- **AUTOSAR Adaptive**: https:\u002F\u002Fwww.autosar.org\u002Fstandards\u002Fadaptive-platform\u002F\n- **SOME\u002FIP**: https:\u002F\u002Fsome-ip.com\u002F\n- **Zenoh**: https:\u002F\u002Fzenoh.io\u002F\n","# Automotive Sdv\n\n## Cloud Vehicle Integration\n\n# Cloud-Vehicle Integration — Connected Vehicle Platforms\n\nExpert knowledge of vehicle-to-cloud connectivity (MQTT, AMQP, HTTP\u002F2), telemetry streaming, remote diagnostics, cloud-based fleet management, and API gateways.\n\n## Core Concepts\n\n### Communication Protocols\n\n1. **MQTT**: Lightweight pub\u002Fsub for telemetry (Eclipse Mosquitto, AWS IoT Core)\n2. **AMQP**: Reliable message queuing (RabbitMQ, Azure Service Bus)\n3. **HTTP\u002F2**: RESTful APIs with server push\n4. **WebSocket**: Real-time bidirectional communication\n5. **gRPC**: High-performance RPC for services\n\n### Architecture Patterns\n\n- **Edge Computing**: Process data locally before cloud\n- **Digital Twin**: Virtual representation of vehicle in cloud\n- **Command & Control**: Remote vehicle operations\n- **Fleet Management**: Aggregate analytics across vehicles\n- **OTA Coordination**: Centralized update management\n\n## Production-Ready Implementation\n\n### 1. Vehicle Telemetry Client (Python\u002FMQTT)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle telemetry client using MQTT.\nStreams vehicle data to cloud platform with offline buffering.\n\"\"\"\n\nimport json\nimport time\nimport sqlite3\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\nfrom typing import Optional, List\nimport paho.mqtt.client as mqtt\nimport can\n\n\n@dataclass\nclass TelemetryMessage:\n    \"\"\"Vehicle telemetry data point.\"\"\"\n    vin: str\n    timestamp: str\n    message_type: str\n    data: dict\n\n\nclass VehicleTelemetryClient:\n    \"\"\"\n    MQTT-based telemetry client.\n\n    Features:\n    - Real-time telemetry streaming\n    - Offline buffering with SQLite\n    - Automatic reconnection\n    - QoS levels for reliability\n    - Compression for bandwidth optimization\n    \"\"\"\n\n    def __init__(self, config_path: str = \"\u002Fetc\u002Fvehicle\u002Ftelemetry-config.json\"):\n        self.config = self._load_config(config_path)\n        self.vin = self._get_vin()\n        self.mqtt_client = None\n        self.can_bus = None\n        self.offline_buffer = OfflineBuffer()\n        self.connected = False\n\n    def _load_config(self, path: str) -> dict:\n        \"\"\"Load configuration.\"\"\"\n        with open(path, 'r') as f:\n            return json.load(f)\n\n    def _get_vin(self) -> str:\n        \"\"\"Get vehicle VIN.\"\"\"\n        with open('\u002Fsys\u002Ffirmware\u002Fdevicetree\u002Fbase\u002Fserial-number', 'r') as f:\n            return f.read().strip()\n\n    def connect(self):\n        \"\"\"Connect to MQTT broker.\"\"\"\n        self.mqtt_client = mqtt.Client(\n            client_id=f\"vehicle-{self.vin}\",\n            clean_session=False,  # Maintain session across reconnects\n            protocol=mqtt.MQTTv5\n        )\n\n        # Set credentials\n        self.mqtt_client.username_pw_set(\n            self.config['mqtt_username'],\n            self.config['mqtt_password']\n        )\n\n        # Configure TLS\n        if self.config.get('mqtt_tls', True):\n            self.mqtt_client.tls_set(\n                ca_certs=self.config['mqtt_ca_cert'],\n                certfile=self.config.get('mqtt_client_cert'),\n                keyfile=self.config.get('mqtt_client_key')\n            )\n\n        # Set callbacks\n        self.mqtt_client.on_connect = self._on_connect\n        self.mqtt_client.on_disconnect = self._on_disconnect\n        self.mqtt_client.on_message = self._on_message\n        self.mqtt_client.on_publish = self._on_publish\n\n        # Set last will (notify cloud if vehicle disconnects unexpectedly)\n        self.mqtt_client.will_set(\n            f\"vehicles\u002F{self.vin}\u002Fstatus\",\n            payload=json.dumps({\n                \"status\": \"offline\",\n                \"timestamp\": datetime.utcnow().isoformat()\n            }),\n            qos=1,\n            retain=True\n        )\n\n        # Connect\n        print(f\"[Telemetry] Connecting to {self.config['mqtt_broker']}:{self.config['mqtt_port']}\")\n        self.mqtt_client.connect(\n            self.config['mqtt_broker'],\n            self.config['mqtt_port'],\n            keepalive=60\n        )\n\n        # Start network loop in background\n        self.mqtt_client.loop_start()\n\n    def _on_connect(self, client, userdata, flags, rc, properties=None):\n        \"\"\"Handle MQTT connection.\"\"\"\n        if rc == 0:\n            print(\"[Telemetry] Connected to MQTT broker\")\n            self.connected = True\n\n            # Publish online status\n            self.mqtt_client.publish(\n                f\"vehicles\u002F{self.vin}\u002Fstatus\",\n                payload=json.dumps({\n                    \"status\": \"online\",\n                    \"timestamp\": datetime.utcnow().isoformat(),\n                    \"sw_version\": self._get_software_version()\n                }),\n                qos=1,\n                retain=True\n            )\n\n            # Subscribe to command topics\n            self.mqtt_client.subscribe(f\"vehicles\u002F{self.vin}\u002Fcommands\u002F#\", qos=1)\n\n            # Send buffered messages\n            self._flush_offline_buffer()\n        else:\n            print(f\"[Telemetry] Connection failed: {rc}\")\n            self.connected = False\n\n    def _on_disconnect(self, client, userdata, rc):\n        \"\"\"Handle MQTT disconnection.\"\"\"\n        print(f\"[Telemetry] Disconnected from broker: {rc}\")\n        self.connected = False\n\n        if rc != 0:\n            print(\"[Telemetry] Unexpected disconnect, will reconnect\")\n\n    def _on_message(self, client, userdata, msg):\n        \"\"\"Handle incoming command messages.\"\"\"\n        print(f\"[Telemetry] Received command: {msg.topic}\")\n\n        try:\n            payload = json.loads(msg.payload.decode())\n            self._handle_command(msg.topic, payload)\n        except Exception as e:\n            print(f\"[Telemetry] Error processing command: {e}\")\n\n    def _on_publish(self, client, userdata, mid):\n        \"\"\"Handle successful publish.\"\"\"\n        # Remove from offline buffer if it was buffered\n        pass\n\n    def _handle_command(self, topic: str, payload: dict):\n        \"\"\"Handle remote commands from cloud.\"\"\"\n        command_type = topic.split('\u002F')[-1]\n\n        if command_type == \"diagnostics\":\n            # Trigger diagnostic data collection\n            print(\"[Telemetry] Starting diagnostic data collection\")\n            self._collect_diagnostics()\n\n        elif command_type == \"update\":\n            # Trigger OTA update check\n            print(\"[Telemetry] Checking for updates\")\n            # Integration with OTA system\n\n        elif command_type == \"lock\":\n            # Remote lock command\n            print(\"[Telemetry] Remote lock requested\")\n            self._remote_lock()\n\n        elif command_type == \"honk\":\n            # Remote horn activation\n            print(\"[Telemetry] Remote honk requested\")\n            self._remote_honk()\n\n    def publish_telemetry(self, message_type: str, data: dict, qos: int = 0):\n        \"\"\"\n        Publish telemetry message.\n\n        Args:\n            message_type: Type of telemetry (battery, location, speed, etc.)\n            data: Telemetry data\n            qos: MQTT QoS level (0, 1, or 2)\n        \"\"\"\n        msg = TelemetryMessage(\n            vin=self.vin,\n            timestamp=datetime.utcnow().isoformat(),\n            message_type=message_type,\n            data=data\n        )\n\n        topic = f\"vehicles\u002F{self.vin}\u002Ftelemetry\u002F{message_type}\"\n        payload = json.dumps(asdict(msg))\n\n        if self.connected:\n            result = self.mqtt_client.publish(topic, payload, qos=qos)\n\n            if result.rc == mqtt.MQTT_ERR_SUCCESS:\n                print(f\"[Telemetry] Published {message_type}\")\n            else:\n                print(f\"[Telemetry] Publish failed: {result.rc}\")\n                # Buffer for later\n                self.offline_buffer.store(topic, payload, qos)\n        else:\n            # Store in offline buffer\n            self.offline_buffer.store(topic, payload, qos)\n            print(f\"[Telemetry] Buffered {message_type} (offline)\")\n\n    def _flush_offline_buffer(self):\n        \"\"\"Send buffered messages when connection restored.\"\"\"\n        messages = self.offline_buffer.retrieve_all()\n        print(f\"[Telemetry] Flushing {len(messages)} buffered messages\")\n\n        for msg in messages:\n            self.mqtt_client.publish(msg['topic'], msg['payload'], qos=msg['qos'])\n            self.offline_buffer.delete(msg['id'])\n\n    def start_can_monitoring(self):\n        \"\"\"Start monitoring CAN bus and streaming telemetry.\"\"\"\n        print(\"[Telemetry] Starting CAN bus monitoring\")\n\n        # Connect to CAN bus\n        self.can_bus = can.interface.Bus(channel='can0', bustype='socketcan')\n\n        # Define telemetry intervals\n        intervals = {\n            'battery': 60,  # Every minute\n            'location': 300,  # Every 5 minutes\n            'speed': 10,  # Every 10 seconds\n            'diagnostics': 3600,  # Every hour\n        }\n\n        last_publish = {k: 0 for k in intervals.keys()}\n\n        while True:\n            # Read CAN messages\n            msg = self.can_bus.recv(timeout=1.0)\n\n            if msg is None:\n                continue\n\n            current_time = time.time()\n\n            # Process specific CAN IDs\n            if msg.arbitration_id == 0x123:  # Battery telemetry\n                if current_time - last_publish['battery'] >= intervals['battery']:\n                    battery_data = self._parse_battery_can(msg.data)\n                    self.publish_telemetry('battery', battery_data, qos=1)\n                    last_publish['battery'] = current_time\n\n            elif msg.arbitration_id == 0x456:  # Speed\u002Flocation\n                if current_time - last_publish['speed'] >= intervals['speed']:\n                    speed_data = self._parse_speed_can(msg.data)\n                    self.publish_telemetry('speed', speed_data, qos=0)\n                    last_publish['speed'] = current_time\n\n            # Periodic location publish\n            if current_time - last_publish['location'] >= intervals['location']:\n                location_data = self._get_gps_location()\n                self.publish_telemetry('location', location_data, qos=1)\n                last_publish['location'] = current_time\n\n    def _parse_battery_can(self, data: bytes) -> dict:\n        \"\"\"Parse battery telemetry from CAN message.\"\"\"\n        return {\n            'soc': int.from_bytes(data[0:2], 'big') \u002F 100,  # State of charge %\n            'voltage': int.from_bytes(data[2:4], 'big') \u002F 10,  # Volts\n            'current': int.from_bytes(data[4:6], 'big', signed=True) \u002F 10,  # Amps\n            'temperature': int.from_bytes(data[6:8], 'big') \u002F 10 - 40,  # Celsius\n        }\n\n    def _parse_speed_can(self, data: bytes) -> dict:\n        \"\"\"Parse speed telemetry from CAN message.\"\"\"\n        return {\n            'speed': int.from_bytes(data[0:2], 'big') \u002F 100,  # km\u002Fh\n            'odometer': int.from_bytes(data[2:6], 'big') \u002F 10,  # km\n        }\n\n    def _get_gps_location(self) -> dict:\n        \"\"\"Get GPS location from GNSS receiver.\"\"\"\n        # Read from gpsd or similar\n        return {\n            'latitude': 37.7749,\n            'longitude': -122.4194,\n            'altitude': 16.0,\n            'heading': 270.0,\n            'accuracy': 3.5\n        }\n\n    def _get_software_version(self) -> str:\n        \"\"\"Get vehicle software version.\"\"\"\n        with open('\u002Fetc\u002Fvehicle\u002Fversion', 'r') as f:\n            return f.read().strip()\n\n    def _collect_diagnostics(self):\n        \"\"\"Collect comprehensive diagnostic data.\"\"\"\n        diagnostics = {\n            'dtcs': [],  # Diagnostic Trouble Codes\n            'ecu_status': {},\n            'battery_health': {},\n            'sensor_status': {},\n        }\n\n        # Publish diagnostic report\n        self.publish_telemetry('diagnostics', diagnostics, qos=1)\n\n    def _remote_lock(self):\n        \"\"\"Execute remote lock command.\"\"\"\n        # Send CAN command to lock doors\n        pass\n\n    def _remote_honk(self):\n        \"\"\"Execute remote horn activation.\"\"\"\n        # Send CAN command to honk\n        pass\n\n    def disconnect(self):\n        \"\"\"Disconnect from MQTT broker.\"\"\"\n        if self.mqtt_client:\n            self.mqtt_client.loop_stop()\n            self.mqtt_client.disconnect()\n\n        if self.can_bus:\n            self.can_bus.shutdown()\n\n\nclass OfflineBuffer:\n    \"\"\"SQLite-based offline message buffer.\"\"\"\n\n    def __init__(self, db_path: str = \"\u002Fvar\u002Flib\u002Fvehicle\u002Ftelemetry-buffer.db\"):\n        self.db_path = db_path\n        self._init_db()\n\n    def _init_db(self):\n        \"\"\"Initialize SQLite database.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('''\n            CREATE TABLE IF NOT EXISTS buffer (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                topic TEXT NOT NULL,\n                payload TEXT NOT NULL,\n                qos INTEGER NOT NULL,\n                timestamp REAL NOT NULL\n            )\n        ''')\n\n        conn.commit()\n        conn.close()\n\n    def store(self, topic: str, payload: str, qos: int):\n        \"\"\"Store message in buffer.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute(\n            'INSERT INTO buffer (topic, payload, qos, timestamp) VALUES (?, ?, ?, ?)',\n            (topic, payload, qos, time.time())\n        )\n\n        conn.commit()\n        conn.close()\n\n    def retrieve_all(self) -> List[dict]:\n        \"\"\"Retrieve all buffered messages.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('SELECT id, topic, payload, qos FROM buffer ORDER BY timestamp')\n        rows = cursor.fetchall()\n\n        conn.close()\n\n        return [\n            {'id': row[0], 'topic': row[1], 'payload': row[2], 'qos': row[3]}\n            for row in rows\n        ]\n\n    def delete(self, msg_id: int):\n        \"\"\"Delete message from buffer.\"\"\"\n        conn = sqlite3.connect(self.db_path)\n        cursor = conn.cursor()\n\n        cursor.execute('DELETE FROM buffer WHERE id = ?', (msg_id,))\n\n        conn.commit()\n        conn.close()\n\n\ndef main():\n    \"\"\"Main telemetry client loop.\"\"\"\n    client = VehicleTelemetryClient()\n\n    try:\n        client.connect()\n        client.start_can_monitoring()\n    except KeyboardInterrupt:\n        print(\"\\n[Telemetry] Shutting down\")\n        client.disconnect()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. Cloud Backend (AWS IoT Core Integration)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nCloud backend for vehicle fleet management using AWS IoT Core.\n\"\"\"\n\nimport json\nimport boto3\nfrom datetime import datetime\nfrom typing import Dict, List\nfrom aws_iot_device_sdk import mqtt as mqtt5\nimport redis\n\n\nclass FleetManagementBackend:\n    \"\"\"\n    Fleet management backend.\n\n    Services:\n    - Receive telemetry from vehicles\n    - Store in time-series database\n    - Real-time analytics\n    - Remote command dispatch\n    \"\"\"\n\n    def __init__(self):\n        # AWS IoT Core client\n        self.iot_client = boto3.client('iot-data', region_name='us-west-2')\n\n        # DynamoDB for vehicle state\n        self.dynamodb = boto3.resource('dynamodb', region_name='us-west-2')\n        self.vehicle_table = self.dynamodb.Table('VehicleState')\n\n        # Timestream for telemetry\n        self.timestream = boto3.client('timestream-write', region_name='us-west-2')\n        self.ts_database = 'VehicleTelemetry'\n        self.ts_table = 'TelemetryData'\n\n        # Redis for real-time data\n        self.redis = redis.Redis(host='localhost', port=6379, decode_responses=True)\n\n    def process_telemetry(self, vin: str, message_type: str, data: dict):\n        \"\"\"\n        Process incoming telemetry message.\n\n        Args:\n            vin: Vehicle identification number\n            message_type: Type of telemetry\n            data: Telemetry data\n        \"\"\"\n        print(f\"[Fleet] Processing {message_type} from {vin}\")\n\n        # Update vehicle state in DynamoDB\n        self._update_vehicle_state(vin, message_type, data)\n\n        # Store in Timestream for historical analytics\n        self._store_timestream(vin, message_type, data)\n\n        # Cache in Redis for real-time queries\n        self._cache_redis(vin, message_type, data)\n\n        # Trigger alerts if necessary\n        self._check_alerts(vin, message_type, data)\n\n    def _update_vehicle_state(self, vin: str, message_type: str, data: dict):\n        \"\"\"Update vehicle state in DynamoDB.\"\"\"\n        self.vehicle_table.update_item(\n            Key={'vin': vin},\n            UpdateExpression=f'SET {message_type} = :data, last_update = :timestamp',\n            ExpressionAttributeValues={\n                ':data': data,\n                ':timestamp': datetime.utcnow().isoformat()\n            }\n        )\n\n    def _store_timestream(self, vin: str, message_type: str, data: dict):\n        \"\"\"Store telemetry in AWS Timestream.\"\"\"\n        records = []\n\n        for key, value in data.items():\n            records.append({\n                'Time': str(int(datetime.utcnow().timestamp() * 1000)),\n                'TimeUnit': 'MILLISECONDS',\n                'Dimensions': [\n                    {'Name': 'vin', 'Value': vin},\n                    {'Name': 'message_type', 'Value': message_type},\n                ],\n                'MeasureName': key,\n                'MeasureValue': str(value),\n                'MeasureValueType': 'DOUBLE' if isinstance(value, float) else 'BIGINT'\n            })\n\n        try:\n            self.timestream.write_records(\n                DatabaseName=self.ts_database,\n                TableName=self.ts_table,\n                Records=records\n            )\n        except Exception as e:\n            print(f\"[Fleet] Timestream write error: {e}\")\n\n    def _cache_redis(self, vin: str, message_type: str, data: dict):\n        \"\"\"Cache latest telemetry in Redis.\"\"\"\n        key = f\"vehicle:{vin}:{message_type}\"\n        self.redis.setex(key, 3600, json.dumps(data))  # 1 hour TTL\n\n    def _check_alerts(self, vin: str, message_type: str, data: dict):\n        \"\"\"Check for alert conditions.\"\"\"\n        if message_type == 'battery':\n            # Low battery alert\n            if data.get('soc', 100) \u003C 20:\n                self._send_alert(vin, 'low_battery', f\"Battery at {data['soc']}%\")\n\n            # High temperature alert\n            if data.get('temperature', 0) > 50:\n                self._send_alert(vin, 'high_temperature',\n                               f\"Battery temp: {data['temperature']}°C\")\n\n        elif message_type == 'diagnostics':\n            # DTC alert\n            if data.get('dtcs'):\n                self._send_alert(vin, 'diagnostic_codes',\n                               f\"DTCs: {', '.join(data['dtcs'])}\")\n\n    def _send_alert(self, vin: str, alert_type: str, message: str):\n        \"\"\"Send alert to monitoring system.\"\"\"\n        print(f\"[Fleet] ALERT - {vin}: {alert_type} - {message}\")\n\n        # Send to SNS topic\n        sns = boto3.client('sns', region_name='us-west-2')\n        sns.publish(\n            TopicArn='arn:aws:sns:us-west-2:123456789012:vehicle-alerts',\n            Subject=f\"Vehicle Alert: {alert_type}\",\n            Message=f\"VIN: {vin}\\nType: {alert_type}\\nMessage: {message}\"\n        )\n\n    def send_command(self, vin: str, command: str, params: dict = None):\n        \"\"\"\n        Send command to vehicle.\n\n        Args:\n            vin: Vehicle identification number\n            command: Command type (lock, unlock, honk, update)\n            params: Command parameters\n        \"\"\"\n        topic = f\"vehicles\u002F{vin}\u002Fcommands\u002F{command}\"\n        payload = json.dumps(params or {})\n\n        print(f\"[Fleet] Sending command to {vin}: {command}\")\n\n        try:\n            self.iot_client.publish(\n                topic=topic,\n                qos=1,\n                payload=payload\n            )\n\n            # Log command\n            self._log_command(vin, command, params)\n\n        except Exception as e:\n            print(f\"[Fleet] Command send error: {e}\")\n\n    def _log_command(self, vin: str, command: str, params: dict):\n        \"\"\"Log command to DynamoDB.\"\"\"\n        commands_table = self.dynamodb.Table('VehicleCommands')\n\n        commands_table.put_item(\n            Item={\n                'vin': vin,\n                'timestamp': datetime.utcnow().isoformat(),\n                'command': command,\n                'params': params or {},\n                'status': 'sent'\n            }\n        )\n\n    def get_vehicle_state(self, vin: str) -> Dict:\n        \"\"\"Get current vehicle state.\"\"\"\n        response = self.vehicle_table.get_item(Key={'vin': vin})\n        return response.get('Item', {})\n\n    def get_fleet_status(self) -> List[Dict]:\n        \"\"\"Get status of entire fleet.\"\"\"\n        response = self.vehicle_table.scan()\n        return response.get('Items', [])\n\n    def query_telemetry_history(self, vin: str, metric: str,\n                                start_time: datetime, end_time: datetime) -> List[Dict]:\n        \"\"\"Query historical telemetry from Timestream.\"\"\"\n        query_client = boto3.client('timestream-query', region_name='us-west-2')\n\n        query = f\"\"\"\n        SELECT time, measure_value::double as value\n        FROM \"{self.ts_database}\".\"{self.ts_table}\"\n        WHERE vin = '{vin}'\n          AND measure_name = '{metric}'\n          AND time BETWEEN from_iso8601_timestamp('{start_time.isoformat()}')\n                       AND from_iso8601_timestamp('{end_time.isoformat()}')\n        ORDER BY time DESC\n        \"\"\"\n\n        try:\n            response = query_client.query(QueryString=query)\n\n            results = []\n            for row in response['Rows']:\n                results.append({\n                    'time': row['Data'][0]['ScalarValue'],\n                    'value': float(row['Data'][1]['ScalarValue'])\n                })\n\n            return results\n\n        except Exception as e:\n            print(f\"[Fleet] Query error: {e}\")\n            return []\n```\n\n### 3. API Gateway (FastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nFleet management API gateway.\nRESTful API for vehicle operations and telemetry queries.\n\"\"\"\n\nfrom fastapi import FastAPI, HTTPException, Depends, Security\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\nfrom pydantic import BaseModel\nfrom datetime import datetime\nfrom typing import List, Optional\n\n\napp = FastAPI(title=\"Fleet Management API\", version=\"2.0.0\")\nsecurity = HTTPBearer()\n\n# Initialize backend\nbackend = FleetManagementBackend()\n\n\nclass CommandRequest(BaseModel):\n    \"\"\"Remote command request.\"\"\"\n    command: str\n    params: Optional[dict] = None\n\n\nclass TelemetryQuery(BaseModel):\n    \"\"\"Telemetry query parameters.\"\"\"\n    metric: str\n    start_time: datetime\n    end_time: datetime\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fvehicles\")\nasync def list_vehicles(credentials: HTTPAuthorizationCredentials = Security(security)):\n    \"\"\"List all vehicles in fleet.\"\"\"\n    fleet = backend.get_fleet_status()\n    return {\"vehicles\": fleet, \"count\": len(fleet)}\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\")\nasync def get_vehicle(vin: str, credentials: HTTPAuthorizationCredentials = Security(security)):\n    \"\"\"Get vehicle state.\"\"\"\n    state = backend.get_vehicle_state(vin)\n\n    if not state:\n        raise HTTPException(status_code=404, detail=\"Vehicle not found\")\n\n    return state\n\n\n@app.post(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\u002Fcommands\")\nasync def send_command(\n    vin: str,\n    request: CommandRequest,\n    credentials: HTTPAuthorizationCredentials = Security(security)\n):\n    \"\"\"Send command to vehicle.\"\"\"\n    backend.send_command(vin, request.command, request.params)\n    return {\"message\": \"Command sent\", \"vin\": vin, \"command\": request.command}\n\n\n@app.post(\"\u002Fapi\u002Fv1\u002Fvehicles\u002F{vin}\u002Ftelemetry\u002Fquery\")\nasync def query_telemetry(\n    vin: str,\n    query: TelemetryQuery,\n    credentials: HTTPAuthorizationCredentials = Security(security)\n):\n    \"\"\"Query historical telemetry data.\"\"\"\n    results = backend.query_telemetry_history(\n        vin,\n        query.metric,\n        query.start_time,\n        query.end_time\n    )\n\n    return {\"vin\": vin, \"metric\": query.metric, \"data\": results}\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### 4. Terraform Infrastructure (AWS)\n\n```hcl\n# File: terraform\u002Fmain.tf\n# AWS IoT Core infrastructure for vehicle fleet\n\nterraform {\n  required_providers {\n    aws = {\n      source  = \"hashicorp\u002Faws\"\n      version = \"~> 5.0\"\n    }\n  }\n}\n\nprovider \"aws\" {\n  region = var.aws_region\n}\n\n# IoT Core Thing Type for Vehicles\nresource \"aws_iot_thing_type\" \"vehicle\" {\n  name = \"VehicleType\"\n\n  properties {\n    description           = \"Connected vehicle\"\n    searchable_attributes = [\"vin\", \"model\", \"year\"]\n  }\n}\n\n# IoT Policy for Vehicle\nresource \"aws_iot_policy\" \"vehicle_policy\" {\n  name = \"VehiclePolicy\"\n\n  policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Connect\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:client\u002Fvehicle-*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Publish\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topic\u002Fvehicles\u002F*\u002Ftelemetry\u002F*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Subscribe\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topicfilter\u002Fvehicles\u002F*\u002Fcommands\u002F*\"\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"iot:Receive\"\n        ]\n        Resource = \"arn:aws:iot:${var.aws_region}:${data.aws_caller_identity.current.account_id}:topic\u002Fvehicles\u002F*\u002Fcommands\u002F*\"\n      }\n    ]\n  })\n}\n\n# DynamoDB Table for Vehicle State\nresource \"aws_dynamodb_table\" \"vehicle_state\" {\n  name           = \"VehicleState\"\n  billing_mode   = \"PAY_PER_REQUEST\"\n  hash_key       = \"vin\"\n\n  attribute {\n    name = \"vin\"\n    type = \"S\"\n  }\n\n  ttl {\n    attribute_name = \"ttl\"\n    enabled        = true\n  }\n\n  tags = {\n    Name = \"vehicle-state\"\n  }\n}\n\n# Timestream Database for Telemetry\nresource \"aws_timestreamwrite_database\" \"telemetry\" {\n  database_name = \"VehicleTelemetry\"\n}\n\nresource \"aws_timestreamwrite_table\" \"telemetry_data\" {\n  database_name = aws_timestreamwrite_database.telemetry.database_name\n  table_name    = \"TelemetryData\"\n\n  retention_properties {\n    memory_store_retention_period_in_hours  = 24\n    magnetic_store_retention_period_in_days = 365\n  }\n}\n\n# SNS Topic for Alerts\nresource \"aws_sns_topic\" \"vehicle_alerts\" {\n  name = \"vehicle-alerts\"\n}\n\n# IoT Rule to Route Telemetry\nresource \"aws_iot_topic_rule\" \"telemetry_rule\" {\n  name        = \"VehicleTelemetryRule\"\n  enabled     = true\n  sql         = \"SELECT * FROM 'vehicles\u002F+\u002Ftelemetry\u002F#'\"\n  sql_version = \"2016-03-23\"\n\n  timestream {\n    database_name = aws_timestreamwrite_database.telemetry.database_name\n    table_name    = aws_timestreamwrite_table.telemetry_data.table_name\n    role_arn      = aws_iam_role.iot_timestream_role.arn\n\n    dimension {\n      name  = \"vin\"\n      value = \"${topic(2)}\"\n    }\n\n    dimension {\n      name  = \"message_type\"\n      value = \"${topic(4)}\"\n    }\n  }\n\n  dynamodb_v2 {\n    role_arn = aws_iam_role.iot_dynamodb_role.arn\n    put_item {\n      table_name = aws_dynamodb_table.vehicle_state.name\n    }\n  }\n}\n\n# IAM Roles\nresource \"aws_iam_role\" \"iot_timestream_role\" {\n  name = \"IoTTimestreamRole\"\n\n  assume_role_policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Principal = {\n          Service = \"iot.amazonaws.com\"\n        }\n        Action = \"sts:AssumeRole\"\n      }\n    ]\n  })\n}\n\nresource \"aws_iam_role_policy\" \"iot_timestream_policy\" {\n  name = \"IoTTimestreamPolicy\"\n  role = aws_iam_role.iot_timestream_role.id\n\n  policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"timestream:WriteRecords\"\n        ]\n        Resource = aws_timestreamwrite_table.telemetry_data.arn\n      },\n      {\n        Effect = \"Allow\"\n        Action = [\n          \"timestream:DescribeEndpoints\"\n        ]\n        Resource = \"*\"\n      }\n    ]\n  })\n}\n\ndata \"aws_caller_identity\" \"current\" {}\n\nvariable \"aws_region\" {\n  default = \"us-west-2\"\n}\n```\n\n## Real-World Examples\n\n### Tesla Cloud Architecture\n- **Real-time telemetry**: Battery, location, charging status\n- **Fleet learning**: Aggregate data for Autopilot improvement\n- **Remote commands**: Lock\u002Funlock, climate control, horn\u002Flights\n- **OTA coordination**: Staged rollout based on fleet data\n\n### Rivian Cloud Platform\n- **Adventure network**: Charging station availability\n- **Fleet Services**: Commercial fleet management for R1T\n- **Remote diagnostics**: Proactive service scheduling\n- **Gear Shop integration**: In-vehicle accessory ordering\n\n### VW.OS Cloud Services\n- **We Connect**: Remote vehicle services\n- **Charging optimization**: Route planning with charging stations\n- **Predictive maintenance**: AI-based service predictions\n- **Car-Net**: Emergency services integration\n\n## Best Practices\n\n1. **Use MQTT for telemetry**: Lightweight, efficient, pub\u002Fsub\n2. **Implement offline buffering**: Handle connectivity loss gracefully\n3. **QoS levels**: Critical data (QoS 1), non-critical (QoS 0)\n4. **TLS encryption**: Always use TLS 1.2+ for transport security\n5. **Rate limiting**: Prevent telemetry storms\n6. **Compression**: Reduce bandwidth usage\n7. **Edge processing**: Process data locally before cloud\n8. **Time-series database**: Use Timestream, InfluxDB, or TimescaleDB\n9. **Real-time cache**: Redis for low-latency queries\n10. **Command acknowledgment**: Require vehicle ACK for critical commands\n\n## Security Considerations\n\n- **Device authentication**: X.509 certificates per vehicle\n- **Message encryption**: TLS 1.2+ for transport\n- **Authorization**: Fine-grained permissions per VIN\n- **Audit logging**: Log all commands and access\n- **API rate limiting**: Prevent abuse\n- **Data retention**: GDPR-compliant data lifecycle\n- **Secure provisioning**: Certificate injection during manufacturing\n\n## References\n\n- **AWS IoT Core**: https:\u002F\u002Faws.amazon.com\u002Fiot-core\u002F\n- **Azure IoT Hub**: https:\u002F\u002Fazure.microsoft.com\u002Fen-us\u002Fproducts\u002Fiot-hub\u002F\n- **Eclipse Paho MQTT**: https:\u002F\u002Fwww.eclipse.org\u002Fpaho\u002F\n- **MQTT Specification**: https:\u002F\u002Fmqtt.org\u002F\n- **AMQP**: https:\u002F\u002Fwww.amqp.org\u002F\n\n---\n\n## Containerized Vehicle Apps\n\n# Containerized Vehicle Apps — Container Runtimes for Automotive\n\nExpert knowledge of container runtimes for automotive (Docker, Podman, containerd), manifest formats, resource limits, inter-container communication, and orchestration (Kubernetes, K3s).\n\n## Core Concepts\n\n### Container Runtimes for Automotive\n\n1. **containerd**: Lightweight, industry-standard container runtime\n2. **Docker**: Full container platform (heavier footprint)\n3. **Podman**: Daemonless, rootless containers\n4. **LXC\u002FLXD**: System containers for full OS isolation\n5. **Balena Engine**: IoT-optimized Docker fork\n\n### Why Containers in Vehicles?\n\n- **Isolation**: Apps can't interfere with critical systems\n- **Portability**: Same app runs on different vehicle models\n- **Updates**: Update apps without full system reflash\n- **Third-party apps**: Safe execution of untrusted code\n- **Resource control**: CPU, memory, network limits per app\n\n## Production-Ready Implementation\n\n### 1. Vehicle Container Runtime (containerd + systemd)\n\n```bash\n#!\u002Fbin\u002Fbash\n# File: setup-vehicle-container-runtime.sh\n# Setup containerd for automotive use\n\nset -e\n\necho \"[Setup] Installing containerd for vehicle platform\"\n\n# Install containerd\napt-get update\napt-get install -y containerd\n\n# Configure containerd for automotive\nmkdir -p \u002Fetc\u002Fcontainerd\ncat > \u002Fetc\u002Fcontainerd\u002Fconfig.toml \u003C\u003CEOF\nversion = 2\n\n# Root directory for containerd\nroot = \"\u002Fvar\u002Flib\u002Fcontainerd\"\nstate = \"\u002Frun\u002Fcontainerd\"\n\n# OCI runtime\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n  runtime_type = \"io.containerd.runc.v2\"\n\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc.options]\n  SystemdCgroup = true\n\n# Resource limits\n[plugins.\"io.containerd.grpc.v1.cri\".containerd]\n  default_runtime_name = \"runc\"\n\n# Registry configuration\n[plugins.\"io.containerd.grpc.v1.cri\".registry]\n  [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors]\n    [plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"vehicle-registry.local:5000\"]\n      endpoint = [\"http:\u002F\u002Fvehicle-registry.local:5000\"]\n\n# CNI plugins for networking\n[plugins.\"io.containerd.grpc.v1.cri\".cni]\n  bin_dir = \"\u002Fopt\u002Fcni\u002Fbin\"\n  conf_dir = \"\u002Fetc\u002Fcni\u002Fnet.d\"\nEOF\n\n# Enable and start containerd\nsystemctl enable containerd\nsystemctl start containerd\n\n# Install CNI plugins\nmkdir -p \u002Fopt\u002Fcni\u002Fbin\ncurl -L https:\u002F\u002Fgithub.com\u002Fcontainernetworking\u002Fplugins\u002Freleases\u002Fdownload\u002Fv1.3.0\u002Fcni-plugins-linux-arm64-v1.3.0.tgz | \\\n  tar -C \u002Fopt\u002Fcni\u002Fbin -xz\n\n# Configure CNI networking\nmkdir -p \u002Fetc\u002Fcni\u002Fnet.d\ncat > \u002Fetc\u002Fcni\u002Fnet.d\u002F10-vehicle-bridge.conf \u003C\u003CEOF\n{\n  \"cniVersion\": \"1.0.0\",\n  \"name\": \"vehicle-bridge\",\n  \"type\": \"bridge\",\n  \"bridge\": \"veh0\",\n  \"isGateway\": true,\n  \"ipMasq\": true,\n  \"ipam\": {\n    \"type\": \"host-local\",\n    \"subnet\": \"10.88.0.0\u002F16\",\n    \"routes\": [\n      { \"dst\": \"0.0.0.0\u002F0\" }\n    ]\n  }\n}\nEOF\n\necho \"[Setup] Container runtime ready\"\n```\n\n### 2. App Manifest Format (OCI-compatible)\n\n```yaml\n# Vehicle app manifest (OCI-compatible)\n# File: spotify-app.yaml\n\napiVersion: vehicle.io\u002Fv1\nkind: VehicleApp\nmetadata:\n  name: spotify\n  namespace: infotainment\n  labels:\n    category: media\n    vendor: spotify\n    safety-critical: \"false\"\n\nspec:\n  # Container specification\n  container:\n    image: vehicle-registry.local:5000\u002Fspotify\u002Fautomotive:2.1.4\n    imagePullPolicy: IfNotPresent\n\n    # Resource limits\n    resources:\n      requests:\n        memory: \"256Mi\"\n        cpu: \"250m\"\n        storage: \"1Gi\"\n      limits:\n        memory: \"512Mi\"\n        cpu: \"500m\"\n        storage: \"2Gi\"\n        network:\n          bandwidth: \"10Mbps\"\n\n    # Security context\n    securityContext:\n      runAsUser: 1000\n      runAsGroup: 1000\n      readOnlyRootFilesystem: true\n      allowPrivilegeEscalation: false\n      capabilities:\n        drop:\n          - ALL\n        add:\n          - NET_BIND_SERVICE  # For network access\n\n    # Environment variables\n    env:\n      - name: API_KEY\n        valueFrom:\n          secretRef:\n            name: spotify-credentials\n            key: api-key\n      - name: VEHICLE_VIN\n        valueFrom:\n          fieldRef:\n            fieldPath: metadata.vin\n\n    # Volume mounts\n    volumeMounts:\n      - name: cache\n        mountPath: \u002Fapp\u002Fcache\n      - name: config\n        mountPath: \u002Fapp\u002Fconfig\n        readOnly: true\n      - name: dbus-socket\n        mountPath: \u002Fvar\u002Frun\u002Fdbus\n\n  # Volumes\n  volumes:\n    - name: cache\n      emptyDir:\n        sizeLimit: 500Mi\n    - name: config\n      configMap:\n        name: spotify-config\n    - name: dbus-socket\n      hostPath:\n        path: \u002Fvar\u002Frun\u002Fdbus\n        type: Socket\n\n  # Networking\n  networking:\n    ports:\n      - name: http\n        containerPort: 8080\n        protocol: TCP\n    hostNetwork: false\n    dnsPolicy: ClusterFirst\n\n  # Lifecycle hooks\n  lifecycle:\n    postStart:\n      exec:\n        command: [\"\u002Fapp\u002Fscripts\u002Fpost-start.sh\"]\n    preStop:\n      exec:\n        command: [\"\u002Fapp\u002Fscripts\u002Fgraceful-shutdown.sh\"]\n\n  # Health checks\n  livenessProbe:\n    httpGet:\n      path: \u002Fhealth\n      port: 8080\n    initialDelaySeconds: 10\n    periodSeconds: 30\n  readinessProbe:\n    httpGet:\n      path: \u002Fready\n      port: 8080\n    initialDelaySeconds: 5\n    periodSeconds: 10\n\n  # Service integration\n  services:\n    - name: media-player\n      type: dbus\n      interface: org.mpris.MediaPlayer2\n    - name: steering-controls\n      type: vehicle-bus\n      permissions: [read]\n\n  # Safety constraints\n  safety:\n    disableWhileDriving: false\n    touchLimit: true\n    requireVoiceControl: false\n    criticalityLevel: low\n\n  # Update strategy\n  updateStrategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxUnavailable: 1\n```\n\n### 3. Container Orchestrator (K3s for Automotive)\n\n```bash\n#!\u002Fbin\u002Fbash\n# File: install-k3s-automotive.sh\n# Install K3s (lightweight Kubernetes) for vehicle platform\n\nset -e\n\necho \"[K3s] Installing K3s for vehicle platform\"\n\n# Install K3s with automotive-specific configuration\ncurl -sfL https:\u002F\u002Fget.k3s.io | INSTALL_K3S_EXEC=\"server \\\n  --disable traefik \\\n  --disable servicelb \\\n  --disable local-storage \\\n  --write-kubeconfig-mode 644 \\\n  --kubelet-arg=max-pods=50 \\\n  --kubelet-arg=eviction-hard=memory.available\u003C100Mi \\\n  --kubelet-arg=eviction-soft=memory.available\u003C200Mi \\\n  --kubelet-arg=eviction-soft-grace-period=memory.available=1m \\\n  --kube-controller-manager-arg=node-monitor-period=10s \\\n  --kube-controller-manager-arg=node-monitor-grace-period=30s\" sh -\n\n# Wait for K3s to start\nsleep 10\n\n# Install vehicle-specific CRDs\ncat \u003C\u003CEOF | kubectl apply -f -\napiVersion: apiextensions.k8s.io\u002Fv1\nkind: CustomResourceDefinition\nmetadata:\n  name: vehicleapps.vehicle.io\nspec:\n  group: vehicle.io\n  versions:\n    - name: v1\n      served: true\n      storage: true\n      schema:\n        openAPIV3Schema:\n          type: object\n          properties:\n            spec:\n              type: object\n              properties:\n                container:\n                  type: object\n                safety:\n                  type: object\n                services:\n                  type: array\n  scope: Namespaced\n  names:\n    plural: vehicleapps\n    singular: vehicleapp\n    kind: VehicleApp\n    shortNames:\n      - vapp\nEOF\n\n# Create namespaces\nkubectl create namespace infotainment\nkubectl create namespace adas\nkubectl create namespace diagnostics\n\n# Install resource quotas\ncat \u003C\u003CEOF | kubectl apply -f -\napiVersion: v1\nkind: ResourceQuota\nmetadata:\n  name: infotainment-quota\n  namespace: infotainment\nspec:\n  hard:\n    requests.cpu: \"2\"\n    requests.memory: \"4Gi\"\n    persistentvolumeclaims: \"10\"\nEOF\n\necho \"[K3s] Installation complete\"\n```\n\n### 4. App Deployment Script (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle app deployment tool using containerd API.\n\"\"\"\n\nimport subprocess\nimport json\nimport yaml\nfrom pathlib import Path\nfrom typing import Dict\n\n\nclass VehicleAppDeployer:\n    \"\"\"Deploy containerized apps to vehicle platform.\"\"\"\n\n    def __init__(self, runtime: str = \"containerd\"):\n        self.runtime = runtime\n        self.namespace = \"vehicle-apps\"\n\n    def deploy_app(self, manifest_path: str):\n        \"\"\"\n        Deploy app from manifest.\n\n        Args:\n            manifest_path: Path to app manifest YAML\n        \"\"\"\n        with open(manifest_path, 'r') as f:\n            manifest = yaml.safe_load(f)\n\n        app_name = manifest['metadata']['name']\n        print(f\"[Deploy] Deploying {app_name}\")\n\n        # Pull container image\n        self._pull_image(manifest['spec']['container']['image'])\n\n        # Create namespace\n        self._create_namespace(manifest['metadata']['namespace'])\n\n        # Create container\n        container_id = self._create_container(manifest)\n\n        # Start container\n        self._start_container(container_id)\n\n        print(f\"[Deploy] {app_name} deployed successfully (ID: {container_id})\")\n\n    def _pull_image(self, image: str):\n        \"\"\"Pull container image.\"\"\"\n        print(f\"[Deploy] Pulling image: {image}\")\n\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"image\", \"pull\", image\n        ]\n\n        subprocess.run(cmd, check=True)\n\n    def _create_namespace(self, namespace: str):\n        \"\"\"Create containerd namespace.\"\"\"\n        # Containerd namespaces are created automatically on first use\n        pass\n\n    def _create_container(self, manifest: Dict) -> str:\n        \"\"\"Create container from manifest.\"\"\"\n        spec = manifest['spec']\n        metadata = manifest['metadata']\n\n        app_name = metadata['name']\n        image = spec['container']['image']\n\n        # Build OCI runtime spec\n        runtime_spec = self._build_runtime_spec(spec)\n\n        # Write spec to file\n        spec_path = f\"\u002Ftmp\u002F{app_name}-spec.json\"\n        with open(spec_path, 'w') as f:\n            json.dump(runtime_spec, f, indent=2)\n\n        # Create container\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"create\",\n            \"--runtime\", \"io.containerd.runc.v2\",\n            \"--config\", spec_path,\n            image,\n            app_name\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n\n        if result.returncode != 0:\n            raise RuntimeError(f\"Container creation failed: {result.stderr}\")\n\n        return app_name\n\n    def _build_runtime_spec(self, spec: Dict) -> Dict:\n        \"\"\"Build OCI runtime specification.\"\"\"\n        container = spec['container']\n        resources = container.get('resources', {})\n\n        # Parse resource limits\n        memory_limit = self._parse_memory(\n            resources.get('limits', {}).get('memory', '512Mi')\n        )\n        cpu_quota = self._parse_cpu(\n            resources.get('limits', {}).get('cpu', '500m')\n        )\n\n        # Build OCI spec\n        oci_spec = {\n            \"ociVersion\": \"1.0.2\",\n            \"process\": {\n                \"terminal\": False,\n                \"user\": {\n                    \"uid\": container.get('securityContext', {}).get('runAsUser', 1000),\n                    \"gid\": container.get('securityContext', {}).get('runAsGroup', 1000)\n                },\n                \"env\": self._build_env(container.get('env', [])),\n                \"cwd\": \"\u002Fapp\",\n                \"capabilities\": {\n                    \"bounding\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"effective\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"inheritable\": [\"CAP_NET_BIND_SERVICE\"],\n                    \"permitted\": [\"CAP_NET_BIND_SERVICE\"]\n                },\n                \"rlimits\": [\n                    {\n                        \"type\": \"RLIMIT_NOFILE\",\n                        \"hard\": 1024,\n                        \"soft\": 1024\n                    }\n                ],\n                \"noNewPrivileges\": True\n            },\n            \"root\": {\n                \"path\": \"rootfs\",\n                \"readonly\": container.get('securityContext', {}).get(\n                    'readOnlyRootFilesystem', True\n                )\n            },\n            \"mounts\": self._build_mounts(spec.get('volumes', [])),\n            \"linux\": {\n                \"namespaces\": [\n                    {\"type\": \"pid\"},\n                    {\"type\": \"network\"},\n                    {\"type\": \"ipc\"},\n                    {\"type\": \"uts\"},\n                    {\"type\": \"mount\"}\n                ],\n                \"resources\": {\n                    \"memory\": {\n                        \"limit\": memory_limit\n                    },\n                    \"cpu\": {\n                        \"quota\": cpu_quota,\n                        \"period\": 100000\n                    }\n                },\n                \"cgroupsPath\": f\"\u002Fvehicle-apps\u002F{spec['container']['image'].split('\u002F')[-1]}\"\n            }\n        }\n\n        return oci_spec\n\n    def _build_env(self, env_vars: list) -> list:\n        \"\"\"Build environment variable list.\"\"\"\n        env = [\"PATH=\u002Fusr\u002Flocal\u002Fsbin:\u002Fusr\u002Flocal\u002Fbin:\u002Fusr\u002Fsbin:\u002Fusr\u002Fbin:\u002Fsbin:\u002Fbin\"]\n\n        for var in env_vars:\n            name = var['name']\n            value = var.get('value')\n\n            if value:\n                env.append(f\"{name}={value}\")\n            elif 'valueFrom' in var:\n                # Resolve from secret\u002Fconfigmap\n                # Simplified implementation\n                env.append(f\"{name}=\u003Cresolved-value>\")\n\n        return env\n\n    def _build_mounts(self, volumes: list) -> list:\n        \"\"\"Build mount list.\"\"\"\n        mounts = [\n            {\n                \"destination\": \"\u002Fproc\",\n                \"type\": \"proc\",\n                \"source\": \"proc\"\n            },\n            {\n                \"destination\": \"\u002Fdev\",\n                \"type\": \"tmpfs\",\n                \"source\": \"tmpfs\",\n                \"options\": [\"nosuid\", \"strictatime\", \"mode=755\", \"size=65536k\"]\n            },\n            {\n                \"destination\": \"\u002Fdev\u002Fpts\",\n                \"type\": \"devpts\",\n                \"source\": \"devpts\",\n                \"options\": [\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\"]\n            },\n            {\n                \"destination\": \"\u002Fsys\",\n                \"type\": \"sysfs\",\n                \"source\": \"sysfs\",\n                \"options\": [\"nosuid\", \"noexec\", \"nodev\", \"ro\"]\n            }\n        ]\n\n        # Add application-specific mounts\n        for volume in volumes:\n            if volume.get('emptyDir'):\n                mounts.append({\n                    \"destination\": \"\u002Fapp\u002Fcache\",\n                    \"type\": \"tmpfs\",\n                    \"source\": \"tmpfs\",\n                    \"options\": [\"nosuid\", \"nodev\"]\n                })\n            elif volume.get('hostPath'):\n                mounts.append({\n                    \"destination\": \"\u002Fvar\u002Frun\u002Fdbus\",\n                    \"type\": \"bind\",\n                    \"source\": volume['hostPath']['path'],\n                    \"options\": [\"rbind\", \"ro\"]\n                })\n\n        return mounts\n\n    def _start_container(self, container_id: str):\n        \"\"\"Start container.\"\"\"\n        print(f\"[Deploy] Starting container: {container_id}\")\n\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"task\", \"start\", \"-d\",\n            container_id\n        ]\n\n        subprocess.run(cmd, check=True)\n\n    def _parse_memory(self, mem_str: str) -> int:\n        \"\"\"Parse memory string to bytes.\"\"\"\n        units = {'Ki': 1024, 'Mi': 1024**2, 'Gi': 1024**3}\n\n        for unit, multiplier in units.items():\n            if mem_str.endswith(unit):\n                return int(mem_str[:-2]) * multiplier\n\n        return int(mem_str)\n\n    def _parse_cpu(self, cpu_str: str) -> int:\n        \"\"\"Parse CPU string to quota.\"\"\"\n        if cpu_str.endswith('m'):\n            millicores = int(cpu_str[:-1])\n            return millicores * 100  # quota in microseconds\n        else:\n            cores = float(cpu_str)\n            return int(cores * 100000)\n\n    def list_apps(self):\n        \"\"\"List deployed apps.\"\"\"\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"ls\"\n        ]\n\n        result = subprocess.run(cmd, capture_output=True, text=True)\n        print(result.stdout)\n\n    def stop_app(self, app_name: str):\n        \"\"\"Stop running app.\"\"\"\n        print(f\"[Deploy] Stopping app: {app_name}\")\n\n        # Stop task\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"task\", \"kill\", app_name,\n            \"SIGTERM\"\n        ]\n\n        subprocess.run(cmd, check=False)\n\n    def remove_app(self, app_name: str):\n        \"\"\"Remove app.\"\"\"\n        print(f\"[Deploy] Removing app: {app_name}\")\n\n        # Delete container\n        cmd = [\n            \"ctr\", \"-n\", self.namespace,\n            \"container\", \"rm\", app_name\n        ]\n\n        subprocess.run(cmd, check=True)\n\n\ndef main():\n    \"\"\"Main deployment script.\"\"\"\n    deployer = VehicleAppDeployer()\n\n    # Deploy app\n    deployer.deploy_app(\"spotify-app.yaml\")\n\n    # List apps\n    deployer.list_apps()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 5. Inter-Container Communication (D-Bus)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nD-Bus service for inter-container communication.\nAllows sandboxed apps to communicate with vehicle services.\n\"\"\"\n\nimport dbus\nimport dbus.service\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom gi.repository import GLib\n\n\nclass VehicleServiceBus(dbus.service.Object):\n    \"\"\"\n    D-Bus service for vehicle platform.\n\n    Provides APIs for apps to:\n    - Get vehicle state\n    - Control audio\n    - Receive user input (steering controls)\n    - Display notifications\n    \"\"\"\n\n    def __init__(self):\n        bus_name = dbus.service.BusName('com.vehicle.Platform',\n                                       bus=dbus.SystemBus())\n        dbus.service.Object.__init__(self, bus_name, '\u002Fcom\u002Fvehicle\u002FPlatform')\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='', out_signature='a{sv}')\n    def GetVehicleState(self):\n        \"\"\"Get current vehicle state.\"\"\"\n        return {\n            'speed': dbus.Double(65.0),  # km\u002Fh\n            'batterySoc': dbus.Double(75.0),  # %\n            'range': dbus.Double(300.0),  # km\n            'gear': dbus.String('D'),\n            'isMoving': dbus.Boolean(True)\n        }\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='s', out_signature='b')\n    def PlayAudio(self, url):\n        \"\"\"Play audio from URL.\"\"\"\n        print(f\"[D-Bus] Playing audio: {url}\")\n        # Integrate with vehicle audio system\n        return True\n\n    @dbus.service.signal('com.vehicle.Platform', signature='s')\n    def SteeringControlEvent(self, action):\n        \"\"\"Signal for steering control events.\"\"\"\n        print(f\"[D-Bus] Steering control: {action}\")\n\n    @dbus.service.method('com.vehicle.Platform',\n                        in_signature='ss', out_signature='b')\n    def ShowNotification(self, title, message):\n        \"\"\"Display notification in vehicle cluster.\"\"\"\n        print(f\"[D-Bus] Notification: {title} - {message}\")\n        # Send to instrument cluster\n        return True\n\n\ndef main():\n    \"\"\"Start D-Bus service.\"\"\"\n    DBusGMainLoop(set_as_default=True)\n\n    service = VehicleServiceBus()\n    print(\"[D-Bus] Vehicle service bus started\")\n\n    # Run main loop\n    loop = GLib.MainLoop()\n    loop.run()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Real-World Examples\n\n### Tesla Container Strategy\n- **Native apps**: Tesla apps run directly on Linux (no containers yet)\n- **Future plans**: Exploring containers for third-party apps\n- **Steam integration**: Games run in isolated environment\n\n### GM Ultifi Platform\n- **Full container orchestration**: Kubernetes-based\n- **App marketplace**: Third-party containerized apps\n- **Resource isolation**: CPU\u002Fmemory limits per app\n- **OTA updates**: Update containers independently\n\n### Rivian App Platform\n- **Docker-based**: Uses Docker for app isolation\n- **Custom runtime**: Modified Docker daemon for automotive\n- **Safety constraints**: Apps can't access CAN bus directly\n- **Fleet deployment**: Kubernetes for managing app fleet\n\n### Android Automotive\n- **Container-like isolation**: APK sandboxing similar to containers\n- **Resource limits**: Memory\u002FCPU limits per app\n- **Permission model**: Fine-grained permissions\n- **Update mechanism**: Individual app updates\n\n## Best Practices\n\n1. **Use containerd**: Lightweight, industry-standard\n2. **Resource limits**: Always set CPU\u002Fmemory limits\n3. **Read-only root**: Immutable container filesystem\n4. **Drop capabilities**: Minimal Linux capabilities\n5. **Network isolation**: Isolate app network traffic\n6. **Health checks**: Liveness and readiness probes\n7. **Graceful shutdown**: Handle SIGTERM properly\n8. **Persistent data**: Use volumes for app data\n9. **Image scanning**: Scan images for vulnerabilities\n10. **Update strategy**: Rolling updates with rollback\n\n## Security Considerations\n\n- **User namespaces**: Run containers as non-root\n- **Seccomp profiles**: Restrict system calls\n- **AppArmor\u002FSELinux**: Mandatory access control\n- **Image signing**: Verify container image signatures\n- **Network policies**: Restrict inter-container communication\n- **Audit logging**: Log container lifecycle events\n- **Resource quotas**: Prevent resource exhaustion\n\n## References\n\n- **containerd**: https:\u002F\u002Fcontainerd.io\u002F\n- **OCI Runtime Spec**: https:\u002F\u002Fgithub.com\u002Fopencontainers\u002Fruntime-spec\n- **K3s**: https:\u002F\u002Fk3s.io\u002F\n- **Podman**: https:\u002F\u002Fpodman.io\u002F\n- **Balena Engine**: https:\u002F\u002Fwww.balena.io\u002Fengine\u002F\n\n---\n\n## Digital Twin Vehicles\n\n# Digital Twin Vehicles — Virtual Vehicle Representations\n\nExpert knowledge of digital twin architecture, real-time synchronization, simulation for testing, predictive maintenance, virtual testing environments, and CI\u002FCD for vehicle software.\n\n## Core Concepts\n\n### Digital Twin Architecture\n\n1. **Physical Twin**: Actual vehicle with sensors and actuators\n2. **Digital Twin**: Virtual representation in cloud\u002Fedge\n3. **Bi-directional Sync**: Real-time data flow both ways\n4. **Simulation Engine**: Physics-based vehicle model\n5. **Analytics Layer**: ML\u002FAI for predictions\n\n### Use Cases\n\n- **Predictive Maintenance**: Predict failures before they occur\n- **Virtual Testing**: Test software without physical vehicle\n- **Fleet Optimization**: Optimize routing, charging, maintenance\n- **Development**: Rapid prototyping and testing\n- **Training**: Train ML models on simulated data\n\n## Production-Ready Implementation\n\n### 1. Digital Twin Engine (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nDigital Twin Engine for vehicle simulation and synchronization.\n\"\"\"\n\nimport json\nimport time\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\nfrom typing import Dict, List, Optional\nimport numpy as np\nfrom scipy.integrate import odeint\nimport paho.mqtt.client as mqtt\n\n\n@dataclass\nclass VehicleState:\n    \"\"\"Complete vehicle state.\"\"\"\n    vin: str\n    timestamp: float\n\n    # Powertrain\n    battery_soc: float  # State of charge (%)\n    battery_voltage: float  # Volts\n    battery_current: float  # Amps\n    battery_temperature: float  # Celsius\n    motor_speed: float  # RPM\n    motor_torque: float  # Nm\n\n    # Dynamics\n    speed: float  # km\u002Fh\n    acceleration: float  # m\u002Fs^2\n    position: tuple  # (latitude, longitude)\n    heading: float  # degrees\n\n    # Environment\n    ambient_temperature: float  # Celsius\n    road_grade: float  # %\n\n    # Diagnostics\n    odometer: float  # km\n    energy_consumed: float  # kWh\n    regeneration_energy: float  # kWh\n\n\nclass VehiclePhysicsModel:\n    \"\"\"\n    Physics-based vehicle simulation model.\n\n    Models:\n    - Battery dynamics (charge\u002Fdischarge, thermal)\n    - Electric motor efficiency\n    - Vehicle dynamics (acceleration, drag, rolling resistance)\n    - Energy consumption\n    \"\"\"\n\n    def __init__(self, vehicle_params: dict):\n        self.params = vehicle_params\n\n        # Vehicle parameters\n        self.mass = vehicle_params['mass']  # kg\n        self.drag_coefficient = vehicle_params['drag_coefficient']  # Cd\n        self.frontal_area = vehicle_params['frontal_area']  # m^2\n        self.rolling_resistance = vehicle_params['rolling_resistance']  # Crr\n        self.wheel_radius = vehicle_params['wheel_radius']  # m\n\n        # Battery parameters\n        self.battery_capacity = vehicle_params['battery_capacity']  # kWh\n        self.battery_resistance = vehicle_params['battery_resistance']  # Ohms\n        self.battery_thermal_mass = vehicle_params['battery_thermal_mass']  # J\u002FK\n\n        # Motor parameters\n        self.motor_max_power = vehicle_params['motor_max_power']  # kW\n        self.motor_efficiency_map = vehicle_params['motor_efficiency_map']\n\n        # Constants\n        self.air_density = 1.225  # kg\u002Fm^3\n        self.gravity = 9.81  # m\u002Fs^2\n\n    def simulate_step(self, state: VehicleState, throttle: float,\n                     dt: float) -> VehicleState:\n        \"\"\"\n        Simulate one time step.\n\n        Args:\n            state: Current vehicle state\n            throttle: Throttle input (-1 to 1, negative for regen)\n            dt: Time step (seconds)\n\n        Returns:\n            Updated vehicle state\n        \"\"\"\n        # Convert speed to m\u002Fs\n        speed_mps = state.speed \u002F 3.6\n\n        # Calculate forces\n        drag_force = 0.5 * self.air_density * self.drag_coefficient * \\\n                     self.frontal_area * speed_mps**2\n\n        rolling_resistance_force = self.rolling_resistance * self.mass * \\\n                                  self.gravity * np.cos(np.radians(state.road_grade))\n\n        grade_force = self.mass * self.gravity * np.sin(np.radians(state.road_grade))\n\n        # Calculate required power\n        if throttle > 0:\n            # Acceleration\n            motor_torque = throttle * self._calculate_max_torque(state.motor_speed)\n            motor_power = motor_torque * state.motor_speed * 2 * np.pi \u002F 60 \u002F 1000  # kW\n\n            # Motor efficiency\n            efficiency = self._get_motor_efficiency(motor_power, state.motor_speed)\n            battery_power = motor_power \u002F efficiency\n\n        else:\n            # Regenerative braking\n            regen_power = abs(throttle) * self.motor_max_power * 0.7  # 70% max regen\n            battery_power = -regen_power * 0.85  # 85% regen efficiency\n            motor_power = -regen_power\n\n        # Battery dynamics\n        battery_current = battery_power * 1000 \u002F state.battery_voltage\n        voltage_drop = battery_current * self.battery_resistance\n        state.battery_voltage = self._calculate_ocv(state.battery_soc) - voltage_drop\n\n        # Energy consumed\u002Fregenerated\n        energy_delta = battery_power * dt \u002F 3600  # kWh\n        state.battery_soc -= (energy_delta \u002F self.battery_capacity) * 100\n\n        if battery_power > 0:\n            state.energy_consumed += energy_delta\n        else:\n            state.regeneration_energy += abs(energy_delta)\n\n        # Battery thermal model\n        heat_generation = battery_current**2 * self.battery_resistance  # Watts\n        cooling_rate = (state.battery_temperature - state.ambient_temperature) * 50  # W\n        temp_delta = (heat_generation - cooling_rate) * dt \u002F self.battery_thermal_mass\n        state.battery_temperature += temp_delta\n\n        # Vehicle dynamics\n        net_force = (motor_power * 1000 \u002F max(speed_mps, 0.1)) - \\\n                   drag_force - rolling_resistance_force - grade_force\n\n        acceleration = net_force \u002F self.mass\n        speed_mps += acceleration * dt\n        speed_mps = max(0, speed_mps)  # Can't go backwards\n\n        state.speed = speed_mps * 3.6  # Convert to km\u002Fh\n        state.acceleration = acceleration\n\n        # Update position (simplified)\n        distance_delta = speed_mps * dt \u002F 1000  # km\n        state.odometer += distance_delta\n\n        # Update motor state\n        state.motor_speed = speed_mps \u002F (2 * np.pi * self.wheel_radius) * 60  # RPM\n        state.motor_torque = motor_power * 1000 \u002F (state.motor_speed * 2 * np.pi \u002F 60) \\\n                           if state.motor_speed > 0 else 0\n\n        state.battery_current = battery_current\n        state.timestamp = time.time()\n\n        return state\n\n    def _calculate_max_torque(self, motor_speed: float) -> float:\n        \"\"\"Calculate maximum available torque at given speed.\"\"\"\n        if motor_speed \u003C 3000:\n            return 400  # Nm (constant torque region)\n        else:\n            # Constant power region\n            max_power = self.motor_max_power * 1000  # W\n            return max_power \u002F (motor_speed * 2 * np.pi \u002F 60)\n\n    def _get_motor_efficiency(self, power: float, speed: float) -> float:\n        \"\"\"Get motor efficiency from efficiency map.\"\"\"\n        # Simplified efficiency model\n        # In production, use lookup table\n        if power \u003C 0.1 * self.motor_max_power:\n            return 0.85\n        elif power \u003C 0.5 * self.motor_max_power:\n            return 0.93\n        elif power \u003C 0.8 * self.motor_max_power:\n            return 0.95\n        else:\n            return 0.92\n\n    def _calculate_ocv(self, soc: float) -> float:\n        \"\"\"Calculate open-circuit voltage from SOC.\"\"\"\n        # Simplified polynomial fit\n        # In production, use actual OCV curve\n        return 300 + 100 * (soc \u002F 100)\n\n\nclass DigitalTwin:\n    \"\"\"\n    Digital twin of vehicle with bi-directional synchronization.\n\n    Features:\n    - Real-time sync with physical vehicle\n    - Physics-based simulation\n    - Predictive analytics\n    - Virtual testing\n    \"\"\"\n\n    def __init__(self, vin: str, vehicle_params: dict, cloud_config: dict):\n        self.vin = vin\n        self.physics_model = VehiclePhysicsModel(vehicle_params)\n        self.cloud_config = cloud_config\n\n        # Initialize state\n        self.state = VehicleState(\n            vin=vin,\n            timestamp=time.time(),\n            battery_soc=100.0,\n            battery_voltage=400.0,\n            battery_current=0.0,\n            battery_temperature=25.0,\n            motor_speed=0.0,\n            motor_torque=0.0,\n            speed=0.0,\n            acceleration=0.0,\n            position=(0.0, 0.0),\n            heading=0.0,\n            ambient_temperature=25.0,\n            road_grade=0.0,\n            odometer=0.0,\n            energy_consumed=0.0,\n            regeneration_energy=0.0\n        )\n\n        # MQTT connection\n        self.mqtt_client = None\n        self.sync_enabled = True\n        self.simulation_mode = False\n\n        # Analytics\n        self.state_history = []\n        self.predictions = {}\n\n    def connect_to_cloud(self):\n        \"\"\"Connect to cloud platform for synchronization.\"\"\"\n        self.mqtt_client = mqtt.Client(client_id=f\"twin-{self.vin}\")\n\n        self.mqtt_client.username_pw_set(\n            self.cloud_config['mqtt_username'],\n            self.cloud_config['mqtt_password']\n        )\n\n        self.mqtt_client.on_connect = self._on_connect\n        self.mqtt_client.on_message = self._on_message\n\n        self.mqtt_client.connect(\n            self.cloud_config['mqtt_broker'],\n            self.cloud_config['mqtt_port']\n        )\n\n        self.mqtt_client.loop_start()\n\n    def _on_connect(self, client, userdata, flags, rc):\n        \"\"\"Handle MQTT connection.\"\"\"\n        print(f\"[Twin] Connected to cloud (VIN: {self.vin})\")\n\n        # Subscribe to physical vehicle telemetry\n        client.subscribe(f\"vehicles\u002F{self.vin}\u002Ftelemetry\u002F#\")\n\n        # Subscribe to commands\n        client.subscribe(f\"twins\u002F{self.vin}\u002Fcommands\u002F#\")\n\n    def _on_message(self, client, userdata, msg):\n        \"\"\"Handle incoming messages.\"\"\"\n        topic_parts = msg.topic.split('\u002F')\n\n        if 'telemetry' in topic_parts:\n            # Update from physical vehicle\n            self._sync_from_physical(json.loads(msg.payload))\n\n        elif 'commands' in topic_parts:\n            # Command from cloud\n            command = topic_parts[-1]\n            self._handle_command(command, json.loads(msg.payload))\n\n    def _sync_from_physical(self, telemetry: dict):\n        \"\"\"Synchronize state from physical vehicle.\"\"\"\n        if not self.sync_enabled:\n            return\n\n        print(f\"[Twin] Syncing from physical vehicle\")\n\n        # Update state from telemetry\n        message_type = telemetry.get('message_type')\n        data = telemetry.get('data', {})\n\n        if message_type == 'battery':\n            self.state.battery_soc = data.get('soc', self.state.battery_soc)\n            self.state.battery_voltage = data.get('voltage', self.state.battery_voltage)\n            self.state.battery_current = data.get('current', self.state.battery_current)\n            self.state.battery_temperature = data.get('temperature',\n                                                     self.state.battery_temperature)\n\n        elif message_type == 'speed':\n            self.state.speed = data.get('speed', self.state.speed)\n            self.state.odometer = data.get('odometer', self.state.odometer)\n\n        elif message_type == 'location':\n            self.state.position = (data.get('latitude', 0), data.get('longitude', 0))\n            self.state.heading = data.get('heading', self.state.heading)\n\n        # Publish updated twin state\n        self._publish_twin_state()\n\n    def _publish_twin_state(self):\n        \"\"\"Publish digital twin state to cloud.\"\"\"\n        if self.mqtt_client and self.mqtt_client.is_connected():\n            topic = f\"twins\u002F{self.vin}\u002Fstate\"\n            payload = json.dumps(asdict(self.state))\n            self.mqtt_client.publish(topic, payload, qos=0)\n\n    def run_simulation(self, drive_cycle: List[dict], dt: float = 0.1):\n        \"\"\"\n        Run simulation with given drive cycle.\n\n        Args:\n            drive_cycle: List of {'time': t, 'throttle': x, 'grade': y}\n            dt: Time step (seconds)\n        \"\"\"\n        print(f\"[Twin] Starting simulation (duration: {drive_cycle[-1]['time']}s)\")\n\n        self.simulation_mode = True\n        self.state_history = []\n\n        for i, cycle_point in enumerate(drive_cycle[:-1]):\n            next_point = drive_cycle[i + 1]\n\n            # Interpolate throttle\n            throttle = cycle_point['throttle']\n            self.state.road_grade = cycle_point.get('grade', 0)\n\n            # Simulate\n            self.state = self.physics_model.simulate_step(self.state, throttle, dt)\n\n            # Store history\n            self.state_history.append(asdict(self.state))\n\n            # Publish periodically\n            if i % 10 == 0:\n                self._publish_twin_state()\n\n            time.sleep(dt)\n\n        self.simulation_mode = False\n        print(f\"[Twin] Simulation complete\")\n\n        # Analyze results\n        self._analyze_simulation()\n\n    def _analyze_simulation(self):\n        \"\"\"Analyze simulation results.\"\"\"\n        if not self.state_history:\n            return\n\n        final_state = self.state_history[-1]\n\n        print(f\"\\n[Twin] Simulation Results:\")\n        print(f\"  Distance: {final_state['odometer']:.2f} km\")\n        print(f\"  Energy consumed: {final_state['energy_consumed']:.2f} kWh\")\n        print(f\"  Regeneration: {final_state['regeneration_energy']:.2f} kWh\")\n        print(f\"  Final SOC: {final_state['battery_soc']:.1f}%\")\n        print(f\"  Efficiency: {final_state['odometer'] \u002F final_state['energy_consumed']:.2f} km\u002FkWh\")\n\n    def predict_range(self) -> float:\n        \"\"\"\n        Predict remaining range based on current state and driving pattern.\n\n        Returns:\n            Predicted range in km\n        \"\"\"\n        # Simple model: current SOC * typical efficiency\n        # In production, use ML model trained on historical data\n\n        typical_efficiency = 5.0  # km\u002FkWh\n        remaining_energy = self.state.battery_soc \u002F 100 * self.physics_model.battery_capacity\n\n        predicted_range = remaining_energy * typical_efficiency\n\n        print(f\"[Twin] Predicted range: {predicted_range:.1f} km\")\n        return predicted_range\n\n    def predict_maintenance(self) -> Dict:\n        \"\"\"\n        Predict maintenance needs using anomaly detection.\n\n        Returns:\n            Dictionary of predicted maintenance items\n        \"\"\"\n        predictions = {\n            'battery_health': 95.0,  # %\n            'estimated_degradation': 5.0,  # %\n            'cycles_remaining': 1500,\n            'recommendations': []\n        }\n\n        # Check battery temperature trends\n        if len(self.state_history) > 100:\n            recent_temps = [s['battery_temperature'] for s in self.state_history[-100:]]\n            avg_temp = np.mean(recent_temps)\n\n            if avg_temp > 45:\n                predictions['recommendations'].append(\n                    \"Battery running hot. Check cooling system.\"\n                )\n\n        # Check energy consumption anomalies\n        if self.state.energy_consumed > 0:\n            efficiency = self.state.odometer \u002F self.state.energy_consumed\n\n            if efficiency \u003C 4.0:  # Below expected\n                predictions['recommendations'].append(\n                    \"Low efficiency detected. Check tire pressure and alignment.\"\n                )\n\n        return predictions\n\n    def _handle_command(self, command: str, params: dict):\n        \"\"\"Handle commands from cloud.\"\"\"\n        print(f\"[Twin] Received command: {command}\")\n\n        if command == 'simulate':\n            # Run simulation with provided drive cycle\n            drive_cycle = params.get('drive_cycle', [])\n            self.run_simulation(drive_cycle)\n\n        elif command == 'predict_range':\n            # Predict range\n            range_km = self.predict_range()\n            self.mqtt_client.publish(\n                f\"twins\u002F{self.vin}\u002Fpredictions\u002Frange\",\n                json.dumps({'range_km': range_km})\n            )\n\n        elif command == 'predict_maintenance':\n            # Predict maintenance\n            predictions = self.predict_maintenance()\n            self.mqtt_client.publish(\n                f\"twins\u002F{self.vin}\u002Fpredictions\u002Fmaintenance\",\n                json.dumps(predictions)\n            )\n\n    def export_state_history(self, filename: str):\n        \"\"\"Export state history to file for analysis.\"\"\"\n        with open(filename, 'w') as f:\n            json.dump(self.state_history, f, indent=2)\n\n        print(f\"[Twin] State history exported to {filename}\")\n\n\n# Example usage\ndef main():\n    \"\"\"Example digital twin usage.\"\"\"\n\n    # Vehicle parameters (Tesla Model 3 Long Range approximate)\n    vehicle_params = {\n        'mass': 1847,  # kg\n        'drag_coefficient': 0.23,\n        'frontal_area': 2.22,  # m^2\n        'rolling_resistance': 0.01,\n        'wheel_radius': 0.368,  # m (18\" wheels)\n        'battery_capacity': 82,  # kWh\n        'battery_resistance': 0.05,  # Ohms\n        'battery_thermal_mass': 50000,  # J\u002FK\n        'motor_max_power': 258,  # kW (combined front+rear)\n        'motor_efficiency_map': {}\n    }\n\n    cloud_config = {\n        'mqtt_broker': 'mqtt.example.com',\n        'mqtt_port': 8883,\n        'mqtt_username': 'twin-client',\n        'mqtt_password': 'password'\n    }\n\n    # Create digital twin\n    twin = DigitalTwin('VIN123456789', vehicle_params, cloud_config)\n    twin.connect_to_cloud()\n\n    # Example drive cycle (WLTP-like)\n    drive_cycle = []\n    for t in range(0, 1800, 10):  # 30 minutes\n        if t \u003C 600:\n            throttle = 0.3  # City driving\n        elif t \u003C 1200:\n            throttle = 0.5  # Highway\n        else:\n            throttle = 0.2  # Slow down\n\n        drive_cycle.append({\n            'time': t,\n            'throttle': throttle,\n            'grade': 0\n        })\n\n    # Run simulation\n    twin.run_simulation(drive_cycle, dt=10.0)\n\n    # Predictions\n    twin.predict_range()\n    twin.predict_maintenance()\n\n    # Export data\n    twin.export_state_history('twin_history.json')\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. Azure Digital Twins Integration\n\n```yaml\n# Azure Digital Twins model definition (DTDL)\n# File: vehicle-model.json\n\n{\n  \"@context\": \"dtmi:dtdl:context;2\",\n  \"@id\": \"dtmi:com:example:Vehicle;1\",\n  \"@type\": \"Interface\",\n  \"displayName\": \"Electric Vehicle\",\n  \"contents\": [\n    {\n      \"@type\": \"Property\",\n      \"name\": \"vin\",\n      \"schema\": \"string\",\n      \"description\": \"Vehicle Identification Number\"\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"battery\",\n      \"schema\": {\n        \"@type\": \"Object\",\n        \"fields\": [\n          {\n            \"name\": \"soc\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"voltage\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"current\",\n            \"schema\": \"double\"\n          },\n          {\n            \"name\": \"temperature\",\n            \"schema\": \"double\"\n          }\n        ]\n      }\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"location\",\n      \"schema\": \"geopoint\"\n    },\n    {\n      \"@type\": \"Telemetry\",\n      \"name\": \"speed\",\n      \"schema\": \"double\"\n    },\n    {\n      \"@type\": \"Command\",\n      \"name\": \"predictRange\",\n      \"response\": {\n        \"name\": \"rangeResult\",\n        \"schema\": \"double\"\n      }\n    },\n    {\n      \"@type\": \"Command\",\n      \"name\": \"simulateDriveCycle\",\n      \"request\": {\n        \"name\": \"driveCycleData\",\n        \"schema\": \"string\"\n      }\n    }\n  ]\n}\n```\n\n### 3. CI\u002FCD Pipeline for Digital Twin\n\n```yaml\n# File: .github\u002Fworkflows\u002Fdigital-twin-ci.yml\n\nname: Digital Twin CI\u002FCD\n\non:\n  push:\n    branches: [main, develop]\n  pull_request:\n    branches: [main]\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v4\n        with:\n          python-version: '3.9'\n\n      - name: Install dependencies\n        run: |\n          pip install -r requirements.txt\n          pip install pytest pytest-cov\n\n      - name: Run unit tests\n        run: |\n          pytest tests\u002F --cov=digital_twin --cov-report=xml\n\n      - name: Run physics model validation\n        run: |\n          python tests\u002Fvalidate_physics.py\n\n      - name: Upload coverage\n        uses: codecov\u002Fcodecov-action@v3\n        with:\n          file: .\u002Fcoverage.xml\n\n  simulate:\n    runs-on: ubuntu-latest\n    needs: test\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Run simulation tests\n        run: |\n          python digital_twin.py --mode simulation \\\n            --drive-cycle tests\u002Fwltp_cycle.json \\\n            --output results\u002F\n\n      - name: Validate results\n        run: |\n          python tests\u002Fvalidate_simulation.py results\u002F\n\n      - name: Upload artifacts\n        uses: actions\u002Fupload-artifact@v3\n        with:\n          name: simulation-results\n          path: results\u002F\n\n  deploy:\n    runs-on: ubuntu-latest\n    needs: [test, simulate]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n\n    steps:\n      - uses: actions\u002Fcheckout@v3\n\n      - name: Configure AWS credentials\n        uses: aws-actions\u002Fconfigure-aws-credentials@v2\n        with:\n          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          aws-region: us-west-2\n\n      - name: Deploy to AWS IoT\n        run: |\n          aws iot create-thing --thing-name digital-twin-${{ github.sha }}\n          aws lambda update-function-code \\\n            --function-name vehicle-digital-twin \\\n            --zip-file fileb:\u002F\u002Fdigital_twin.zip\n```\n\n## Real-World Examples\n\n### Tesla Digital Twin\n- **Fleet learning**: Aggregate shadow mode data for Autopilot\n- **Battery degradation modeling**: Predict range loss over time\n- **Virtual testing**: Test new software on digital fleet before OTA\n- **Predictive maintenance**: Schedule service based on digital twin analysis\n\n### BMW Digital Twin\n- **Production line**: Digital twin during manufacturing\n- **Lifetime tracking**: Track vehicle from production to end-of-life\n- **Service optimization**: Predict maintenance needs\n- **Retrofit planning**: Test compatibility of new features\n\n### Rivian Adventure Network\n- **Route optimization**: Simulate range on planned routes\n- **Charging strategy**: Optimize charging stops\n- **Off-road capability**: Simulate vehicle performance on trails\n- **Load planning**: Test vehicle with different cargo\u002Ftrailer loads\n\n## Best Practices\n\n1. **High-fidelity physics**: Use validated physics models\n2. **Real-time sync**: Keep twin synchronized with physical vehicle\n3. **Historical data**: Store state history for analytics\n4. **Predictive models**: Use ML for maintenance predictions\n5. **Virtual testing**: Test software on twins before deployment\n6. **CI\u002FCD integration**: Automate testing with digital twins\n7. **Fleet-wide insights**: Aggregate data across all twins\n8. **Privacy protection**: Anonymize sensitive data\n9. **Model validation**: Continuously validate against real-world data\n10. **Scalability**: Design for millions of twins\n\n## Security Considerations\n\n- **Authentication**: Secure twin-to-cloud communication\n- **Data encryption**: Encrypt state data and telemetry\n- **Access control**: Limit who can command twins\n- **Audit logging**: Track all twin operations\n- **Simulation isolation**: Sandbox simulation environments\n- **Model protection**: Protect proprietary physics models\n\n## References\n\n- **Azure Digital Twins**: https:\u002F\u002Fazure.microsoft.com\u002Fen-us\u002Fproducts\u002Fdigital-twins\u002F\n- **AWS IoT TwinMaker**: https:\u002F\u002Faws.amazon.com\u002Fiot-twinmaker\u002F\n- **Eclipse Ditto**: https:\u002F\u002Fwww.eclipse.org\u002Fditto\u002F\n- **Digital Twin Consortium**: https:\u002F\u002Fwww.digitaltwinconsortium.org\u002F\n\n---\n\n## Ota Update Systems\n\n# OTA Update Systems — Over-The-Air Updates for Vehicles\n\nExpert knowledge of OTA (Over-The-Air) update architecture, A\u002FB partitioning, differential updates, rollback mechanisms, secure boot chain, and update orchestration across ECUs.\n\n## Core Concepts\n\n### Update Architecture Patterns\n\n1. **Full Image Updates**: Complete partition replacement\n2. **Differential Updates**: Binary diffs to minimize bandwidth\n3. **Component Updates**: Individual ECU\u002Fapplication updates\n4. **Atomic Updates**: All-or-nothing update transactions\n5. **Staged Rollouts**: Phased deployment across fleet\n\n### Security Requirements\n\n- **Uptane Framework**: Industry standard for secure vehicle updates\n- **TUF (The Update Framework)**: Metadata and signature verification\n- **Secure Boot Chain**: UEFI\u002FU-Boot signature validation\n- **Hardware Root of Trust**: TPM\u002FHSM for key storage\n- **Rollback Protection**: Anti-rollback counters\n\n## Production-Ready Implementations\n\n### 1. Uptane-Compliant Update Client (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nUptane-compliant OTA update client for automotive ECUs.\nImplements Director and Image repository verification.\n\"\"\"\n\nimport hashlib\nimport json\nimport os\nimport subprocess\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\nimport requests\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import padding, rsa\nfrom cryptography.hazmat.backends import default_backend\n\n\n@dataclass\nclass UpdateMetadata:\n    \"\"\"Update metadata from Director repository.\"\"\"\n    version: str\n    targets: Dict[str, dict]\n    signatures: List[dict]\n    expires: str\n\n    @classmethod\n    def from_json(cls, data: dict):\n        return cls(\n            version=data[\"signed\"][\"version\"],\n            targets=data[\"signed\"][\"targets\"],\n            signatures=data[\"signatures\"],\n            expires=data[\"signed\"][\"expires\"]\n        )\n\n\nclass UptaneClient:\n    \"\"\"\n    Uptane OTA update client.\n\n    Supports:\n    - Dual Director\u002FImage repository verification\n    - Signature validation with threshold\n    - Differential update download\n    - A\u002FB partition switching\n    - Automatic rollback on boot failure\n    \"\"\"\n\n    def __init__(self, config_path: str = \"\u002Fetc\u002Fota\u002Fuptane-config.json\"):\n        self.config = self._load_config(config_path)\n        self.ecu_serial = self._get_ecu_serial()\n        self.current_version = self._get_current_version()\n        self.director_url = self.config[\"director_url\"]\n        self.image_repo_url = self.config[\"image_repo_url\"]\n        self.root_keys = self._load_root_keys()\n\n    def _load_config(self, path: str) -> dict:\n        \"\"\"Load Uptane configuration.\"\"\"\n        with open(path, 'r') as f:\n            return json.load(f)\n\n    def _get_ecu_serial(self) -> str:\n        \"\"\"Get unique ECU serial number.\"\"\"\n        # Read from secure storage (TPM, EEPROM, etc.)\n        serial_path = Path(\"\u002Fsys\u002Ffirmware\u002Fdevicetree\u002Fbase\u002Fserial-number\")\n        if serial_path.exists():\n            return serial_path.read_text().strip()\n        return os.uname().nodename  # Fallback\n\n    def _get_current_version(self) -> str:\n        \"\"\"Get currently running software version.\"\"\"\n        version_path = Path(\"\u002Fetc\u002Fota\u002Fcurrent-version\")\n        if version_path.exists():\n            return version_path.read_text().strip()\n        return \"unknown\"\n\n    def _load_root_keys(self) -> List[rsa.RSAPublicKey]:\n        \"\"\"Load root public keys for signature verification.\"\"\"\n        keys = []\n        for key_file in self.config[\"root_keys\"]:\n            with open(key_file, 'rb') as f:\n                key = serialization.load_pem_public_key(\n                    f.read(),\n                    backend=default_backend()\n                )\n                keys.append(key)\n        return keys\n\n    def verify_signature(self, data: bytes, signature: bytes,\n                        public_key: rsa.RSAPublicKey) -> bool:\n        \"\"\"Verify RSA signature on data.\"\"\"\n        try:\n            public_key.verify(\n                signature,\n                data,\n                padding.PSS(\n                    mgf=padding.MGF1(hashes.SHA256()),\n                    salt_length=padding.PSS.MAX_LENGTH\n                ),\n                hashes.SHA256()\n            )\n            return True\n        except Exception as e:\n            print(f\"Signature verification failed: {e}\")\n            return False\n\n    def check_for_updates(self) -> Optional[UpdateMetadata]:\n        \"\"\"\n        Check Director repository for available updates.\n\n        Returns:\n            UpdateMetadata if update available, None otherwise\n        \"\"\"\n        print(f\"[OTA] Checking for updates (ECU: {self.ecu_serial}, \"\n              f\"Version: {self.current_version})\")\n\n        # Fetch Director metadata\n        url = f\"{self.director_url}\u002Fmetadata\u002F{self.ecu_serial}\u002Ftargets.json\"\n        try:\n            response = requests.get(url, timeout=30)\n            response.raise_for_status()\n            metadata = UpdateMetadata.from_json(response.json())\n\n            # Verify signatures (threshold: 2\u002F3)\n            verified_sigs = 0\n            for sig_data in metadata.signatures:\n                sig_bytes = bytes.fromhex(sig_data[\"sig\"])\n                # Verify against root keys\n                for key in self.root_keys:\n                    if self.verify_signature(\n                        json.dumps(response.json()[\"signed\"]).encode(),\n                        sig_bytes,\n                        key\n                    ):\n                        verified_sigs += 1\n                        break\n\n            if verified_sigs \u003C self.config.get(\"signature_threshold\", 2):\n                raise ValueError(f\"Insufficient signatures: {verified_sigs}\")\n\n            # Check if update is newer\n            for target_name, target_info in metadata.targets.items():\n                if target_info[\"custom\"].get(\"ecu_identifier\") == self.ecu_serial:\n                    target_version = target_info[\"custom\"][\"version\"]\n                    if target_version != self.current_version:\n                        print(f\"[OTA] Update available: {target_version}\")\n                        return metadata\n\n            print(\"[OTA] No updates available\")\n            return None\n\n        except Exception as e:\n            print(f\"[OTA] Error checking for updates: {e}\")\n            return None\n\n    def download_update(self, metadata: UpdateMetadata) -> Optional[Path]:\n        \"\"\"\n        Download update image from Image repository.\n\n        Uses differential updates if available.\n\n        Returns:\n            Path to downloaded update file\n        \"\"\"\n        for target_name, target_info in metadata.targets.items():\n            if target_info[\"custom\"].get(\"ecu_identifier\") != self.ecu_serial:\n                continue\n\n            # Check for differential update\n            if \"delta_from\" in target_info[\"custom\"]:\n                if target_info[\"custom\"][\"delta_from\"] == self.current_version:\n                    print(\"[OTA] Downloading differential update...\")\n                    url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}.delta\"\n                else:\n                    print(\"[OTA] Delta not applicable, downloading full image\")\n                    url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}\"\n            else:\n                print(\"[OTA] Downloading full update image...\")\n                url = f\"{self.image_repo_url}\u002Ftargets\u002F{target_name}\"\n\n            # Download with progress\n            download_path = Path(f\"\u002Ftmp\u002Fota-update-{target_name}\")\n            try:\n                with requests.get(url, stream=True, timeout=300) as r:\n                    r.raise_for_status()\n                    total_size = int(r.headers.get('content-length', 0))\n                    downloaded = 0\n\n                    with open(download_path, 'wb') as f:\n                        for chunk in r.iter_content(chunk_size=8192):\n                            f.write(chunk)\n                            downloaded += len(chunk)\n                            progress = (downloaded \u002F total_size * 100) if total_size else 0\n                            print(f\"\\r[OTA] Download progress: {progress:.1f}%\", end='')\n\n                    print()  # New line after progress\n\n                # Verify hash\n                expected_hash = target_info[\"hashes\"][\"sha256\"]\n                actual_hash = self._compute_sha256(download_path)\n\n                if actual_hash != expected_hash:\n                    raise ValueError(f\"Hash mismatch: {actual_hash} != {expected_hash}\")\n\n                print(f\"[OTA] Download complete: {download_path}\")\n                return download_path\n\n            except Exception as e:\n                print(f\"[OTA] Download failed: {e}\")\n                if download_path.exists():\n                    download_path.unlink()\n                return None\n\n        return None\n\n    def _compute_sha256(self, file_path: Path) -> str:\n        \"\"\"Compute SHA256 hash of file.\"\"\"\n        sha256 = hashlib.sha256()\n        with open(file_path, 'rb') as f:\n            for chunk in iter(lambda: f.read(8192), b''):\n                sha256.update(chunk)\n        return sha256.hexdigest()\n\n    def install_update(self, update_path: Path) -> bool:\n        \"\"\"\n        Install update to inactive partition.\n\n        Uses A\u002FB partition switching for atomic updates.\n\n        Returns:\n            True if installation successful\n        \"\"\"\n        print(\"[OTA] Installing update...\")\n\n        try:\n            # Determine inactive partition\n            current_slot = self._get_current_boot_slot()\n            inactive_slot = 'b' if current_slot == 'a' else 'a'\n            inactive_partition = f\"\u002Fdev\u002Fmmcblk0p{2 if inactive_slot == 'b' else 1}\"\n\n            print(f\"[OTA] Current slot: {current_slot}, \"\n                  f\"Installing to: {inactive_slot}\")\n\n            # Write update to inactive partition\n            cmd = f\"dd if={update_path} of={inactive_partition} bs=4M status=progress\"\n            subprocess.run(cmd, shell=True, check=True)\n\n            # Set boot slot to inactive (will become active on next boot)\n            self._set_boot_slot(inactive_slot)\n\n            # Mark for boot attempt counter (rollback if boot fails 3 times)\n            self._set_boot_counter(3)\n\n            print(f\"[OTA] Update installed to slot {inactive_slot}\")\n            return True\n\n        except Exception as e:\n            print(f\"[OTA] Installation failed: {e}\")\n            return False\n\n    def _get_current_boot_slot(self) -> str:\n        \"\"\"Get currently booted partition slot.\"\"\"\n        # Read from U-Boot environment or kernel command line\n        with open(\"\u002Fproc\u002Fcmdline\", 'r') as f:\n            cmdline = f.read()\n            if \"root=\u002Fdev\u002Fmmcblk0p1\" in cmdline:\n                return 'a'\n            elif \"root=\u002Fdev\u002Fmmcblk0p2\" in cmdline:\n                return 'b'\n        return 'a'  # Default\n\n    def _set_boot_slot(self, slot: str):\n        \"\"\"Set boot slot for next reboot.\"\"\"\n        # Write to U-Boot environment\n        cmd = f\"fw_setenv boot_slot {slot}\"\n        subprocess.run(cmd, shell=True, check=True)\n\n    def _set_boot_counter(self, count: int):\n        \"\"\"Set boot attempt counter for rollback protection.\"\"\"\n        cmd = f\"fw_setenv boot_counter {count}\"\n        subprocess.run(cmd, shell=True, check=True)\n\n    def apply_update(self) -> bool:\n        \"\"\"\n        Apply update by rebooting into new partition.\n\n        Returns:\n            True if reboot initiated\n        \"\"\"\n        print(\"[OTA] Applying update (rebooting)...\")\n        try:\n            subprocess.run([\"reboot\"], check=True)\n            return True\n        except Exception as e:\n            print(f\"[OTA] Reboot failed: {e}\")\n            return False\n\n    def verify_boot_success(self):\n        \"\"\"\n        Verify successful boot after update.\n\n        Called by systemd service on boot.\n        Confirms update success or triggers rollback.\n        \"\"\"\n        boot_counter_path = Path(\"\u002Fproc\u002Fdevice-tree\u002Fchosen\u002Fu-boot,boot-counter\")\n\n        if boot_counter_path.exists():\n            counter = int(boot_counter_path.read_text().strip())\n\n            if counter > 0:\n                # Boot successful, commit update\n                print(\"[OTA] Boot successful, committing update\")\n                self._set_boot_counter(0)  # Clear counter\n\n                # Update current version\n                new_version = self._detect_version()\n                Path(\"\u002Fetc\u002Fota\u002Fcurrent-version\").write_text(new_version)\n            else:\n                print(\"[OTA] Already committed\")\n        else:\n            print(\"[OTA] Boot counter not found (no pending update)\")\n\n    def _detect_version(self) -> str:\n        \"\"\"Detect software version from running system.\"\"\"\n        version_files = [\n            \"\u002Fetc\u002Fota\u002Fversion\",\n            \"\u002Fetc\u002Fos-release\"\n        ]\n\n        for path in version_files:\n            if Path(path).exists():\n                content = Path(path).read_text()\n                # Extract version from os-release\n                for line in content.split('\\n'):\n                    if line.startswith(\"VERSION=\"):\n                        return line.split('=')[1].strip('\"')\n\n        return \"unknown\"\n\n\ndef main():\n    \"\"\"OTA update client main loop.\"\"\"\n    client = UptaneClient()\n\n    # Check on boot\n    client.verify_boot_success()\n\n    # Periodic update check\n    while True:\n        metadata = client.check_for_updates()\n\n        if metadata:\n            update_path = client.download_update(metadata)\n\n            if update_path:\n                if client.install_update(update_path):\n                    print(\"[OTA] Update ready, will apply on next reboot\")\n                    # Optionally auto-reboot or wait for user confirmation\n                    # client.apply_update()\n\n        # Check every hour\n        time.sleep(3600)\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 2. A\u002FB Partition Configuration (U-Boot)\n\n```bash\n# U-Boot environment for A\u002FB partitioning\n# File: \u002Fetc\u002Ffw_env.config\n\n# Device              Offset    Size     Erasesize\n\u002Fdev\u002Fmtd1             0x0000    0x1000   0x1000\n\u002Fdev\u002Fmtd2             0x0000    0x1000   0x1000\n```\n\n```bash\n# U-Boot bootcmd script for A\u002FB boot\n# File: boot.cmd\n\n# Read boot slot from environment\nsetenv bootslot ${boot_slot}\nif test -z \"${bootslot}\"; then\n    setenv bootslot a\nfi\n\n# Read boot counter\nsetenv bootcount ${boot_counter}\nif test -z \"${bootcount}\"; then\n    setenv bootcount 0\nfi\n\n# Check rollback condition\nif test ${bootcount} -eq 0; then\n    echo \"Booting from slot ${bootslot}\"\nelse\n    # Decrement boot counter\n    setexpr bootcount ${bootcount} - 1\n    setenv boot_counter ${bootcount}\n    saveenv\n\n    # If counter reaches 0, rollback to other slot\n    if test ${bootcount} -eq 0; then\n        echo \"Boot failed 3 times, rolling back\"\n        if test \"${bootslot}\" = \"a\"; then\n            setenv bootslot b\n        else\n            setenv bootslot a\n        fi\n        setenv boot_slot ${bootslot}\n        saveenv\n    fi\nfi\n\n# Set root partition\nif test \"${bootslot}\" = \"a\"; then\n    setenv bootargs console=ttyS0,115200 root=\u002Fdev\u002Fmmcblk0p1 rw rootwait\n    load mmc 0:1 ${kernel_addr_r} \u002Fboot\u002FImage\n    load mmc 0:1 ${fdt_addr_r} \u002Fboot\u002Fdtb\nelse\n    setenv bootargs console=ttyS0,115200 root=\u002Fdev\u002Fmmcblk0p2 rw rootwait\n    load mmc 0:2 ${kernel_addr_r} \u002Fboot\u002FImage\n    load mmc 0:2 ${fdt_addr_r} \u002Fboot\u002Fdtb\nfi\n\n# Boot kernel\nbooti ${kernel_addr_r} - ${fdt_addr_r}\n```\n\n### 3. Differential Update Generator (Python)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nGenerate binary differential updates for OTA.\nUses bsdiff algorithm for efficient bandwidth usage.\n\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport subprocess\nimport sys\nfrom pathlib import Path\n\n\ndef generate_delta(old_image: Path, new_image: Path, output: Path):\n    \"\"\"\n    Generate binary diff between two images.\n\n    Args:\n        old_image: Path to old firmware image\n        new_image: Path to new firmware image\n        output: Path to output delta file\n    \"\"\"\n    print(f\"Generating delta: {old_image} -> {new_image}\")\n\n    # Use bsdiff for binary diffing\n    cmd = [\"bsdiff\", str(old_image), str(new_image), str(output)]\n\n    try:\n        subprocess.run(cmd, check=True)\n    except FileNotFoundError:\n        print(\"Error: bsdiff not found. Install with: apt-get install bsdiff\")\n        sys.exit(1)\n    except subprocess.CalledProcessError as e:\n        print(f\"Error generating delta: {e}\")\n        sys.exit(1)\n\n    # Calculate sizes and compression ratio\n    old_size = old_image.stat().st_size\n    new_size = new_image.stat().st_size\n    delta_size = output.stat().st_size\n\n    ratio = (1 - delta_size \u002F new_size) * 100\n\n    print(f\"Old image size: {old_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"New image size: {new_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"Delta size: {delta_size \u002F 1024 \u002F 1024:.2f} MB\")\n    print(f\"Bandwidth savings: {ratio:.1f}%\")\n\n    # Generate metadata\n    metadata = {\n        \"old_version\": old_image.stem,\n        \"new_version\": new_image.stem,\n        \"old_hash\": compute_sha256(old_image),\n        \"new_hash\": compute_sha256(new_image),\n        \"delta_hash\": compute_sha256(output),\n        \"delta_size\": delta_size,\n        \"compression_ratio\": ratio\n    }\n\n    metadata_path = output.with_suffix('.json')\n    with open(metadata_path, 'w') as f:\n        json.dump(metadata, f, indent=2)\n\n    print(f\"Metadata written to: {metadata_path}\")\n\n\ndef compute_sha256(path: Path) -> str:\n    \"\"\"Compute SHA256 hash of file.\"\"\"\n    sha256 = hashlib.sha256()\n    with open(path, 'rb') as f:\n        for chunk in iter(lambda: f.read(8192), b''):\n            sha256.update(chunk)\n    return sha256.hexdigest()\n\n\ndef apply_delta(old_image: Path, delta: Path, output: Path):\n    \"\"\"\n    Apply delta patch to old image.\n\n    Args:\n        old_image: Path to old firmware image\n        delta: Path to delta file\n        output: Path to output patched image\n    \"\"\"\n    print(f\"Applying delta: {old_image} + {delta} -> {output}\")\n\n    cmd = [\"bspatch\", str(old_image), str(output), str(delta)]\n\n    try:\n        subprocess.run(cmd, check=True)\n        print(f\"Patched image created: {output}\")\n    except FileNotFoundError:\n        print(\"Error: bspatch not found. Install with: apt-get install bsdiff\")\n        sys.exit(1)\n    except subprocess.CalledProcessError as e:\n        print(f\"Error applying delta: {e}\")\n        sys.exit(1)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"OTA differential update generator\")\n    subparsers = parser.add_subparsers(dest='command', help='Command to execute')\n\n    # Generate delta\n    gen_parser = subparsers.add_parser('generate', help='Generate delta update')\n    gen_parser.add_argument('--old', type=Path, required=True, help='Old image')\n    gen_parser.add_argument('--new', type=Path, required=True, help='New image')\n    gen_parser.add_argument('--output', type=Path, required=True, help='Output delta file')\n\n    # Apply delta\n    apply_parser = subparsers.add_parser('apply', help='Apply delta update')\n    apply_parser.add_argument('--old', type=Path, required=True, help='Old image')\n    apply_parser.add_argument('--delta', type=Path, required=True, help='Delta file')\n    apply_parser.add_argument('--output', type=Path, required=True, help='Output image')\n\n    args = parser.parse_args()\n\n    if args.command == 'generate':\n        generate_delta(args.old, args.new, args.output)\n    elif args.command == 'apply':\n        apply_delta(args.old, args.delta, args.output)\n    else:\n        parser.print_help()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### 4. OTA Update Service (systemd)\n\n```ini\n# File: \u002Fetc\u002Fsystemd\u002Fsystem\u002Fota-update.service\n\n[Unit]\nDescription=OTA Update Client\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nExecStart=\u002Fusr\u002Fbin\u002Fpython3 \u002Fusr\u002Flocal\u002Fbin\u002Fuptane-client.py\nRestart=always\nRestartSec=60\nUser=ota\nGroup=ota\n\n# Security hardening\nPrivateTmp=yes\nProtectSystem=strict\nProtectHome=yes\nReadWritePaths=\u002Ftmp \u002Fvar\u002Flib\u002Fota\nNoNewPrivileges=yes\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\n\n[Install]\nWantedBy=multi-user.target\n```\n\n```ini\n# File: \u002Fetc\u002Fsystemd\u002Fsystem\u002Fota-boot-verify.service\n\n[Unit]\nDescription=OTA Boot Verification\nDefaultDependencies=no\nAfter=local-fs.target\nBefore=sysinit.target\n\n[Service]\nType=oneshot\nExecStart=\u002Fusr\u002Fbin\u002Fpython3 -c \"from uptane_client import UptaneClient; UptaneClient().verify_boot_success()\"\nRemainAfterExit=yes\n\n[Install]\nWantedBy=sysinit.target\n```\n\n### 5. Mender Integration (Alternative Framework)\n\n```yaml\n# File: \u002Fetc\u002Fmender\u002Fmender.conf\n{\n  \"ServerURL\": \"https:\u002F\u002Fota.example.com\",\n  \"TenantToken\": \"TENANT_TOKEN_HERE\",\n  \"InventoryPollIntervalSeconds\": 28800,\n  \"UpdatePollIntervalSeconds\": 1800,\n  \"RetryPollIntervalSeconds\": 300,\n  \"RootfsPartA\": \"\u002Fdev\u002Fmmcblk0p2\",\n  \"RootfsPartB\": \"\u002Fdev\u002Fmmcblk0p3\",\n  \"ServerCertificate\": \"\u002Fetc\u002Fmender\u002Fserver.crt\",\n  \"DeviceTypeFile\": \"\u002Fvar\u002Flib\u002Fmender\u002Fdevice_type\"\n}\n```\n\n```bash\n# Mender artifact creation script\n#!\u002Fbin\u002Fbash\n# File: create-mender-artifact.sh\n\nset -e\n\nIMAGE_FILE=$1\nARTIFACT_NAME=$2\nDEVICE_TYPE=$3\n\nif [ -z \"$IMAGE_FILE\" ] || [ -z \"$ARTIFACT_NAME\" ] || [ -z \"$DEVICE_TYPE\" ]; then\n    echo \"Usage: $0 \u003Cimage-file> \u003Cartifact-name> \u003Cdevice-type>\"\n    exit 1\nfi\n\n# Create Mender artifact\nmender-artifact write rootfs-image \\\n    --file \"$IMAGE_FILE\" \\\n    --artifact-name \"$ARTIFACT_NAME\" \\\n    --device-type \"$DEVICE_TYPE\" \\\n    --output-path \"${ARTIFACT_NAME}.mender\"\n\necho \"Mender artifact created: ${ARTIFACT_NAME}.mender\"\n\n# Sign artifact (optional)\nif [ -f \"private.key\" ]; then\n    mender-artifact sign \"${ARTIFACT_NAME}.mender\" \\\n        --key private.key \\\n        --output-path \"${ARTIFACT_NAME}.signed.mender\"\n\n    echo \"Signed artifact created: ${ARTIFACT_NAME}.signed.mender\"\nfi\n```\n\n## Real-World Examples\n\n### Tesla OTA Architecture\n\n- **Full stack updates**: Entire OS, kernel, applications\n- **Dual-bank storage**: 2x storage for A\u002FB switching\n- **Cellular + WiFi**: Automatic download scheduling\n- **User control**: Schedule updates, defer if driving\n- **Rollback**: Automatic if vehicle fails self-test\n\n### VW.OS Update Strategy\n\n- **ECU orchestration**: Update multiple ECUs in sequence\n- **Safety constraints**: No updates to critical systems while driving\n- **Partial updates**: Update infotainment without touching ADAS\n- **Fleet rollout**: Phased deployment by region\u002Fmodel\n\n### GM Ultifi Platform\n\n- **Container-based**: Update individual apps without full reflash\n- **Middleware updates**: Update communication layer separately\n- **Third-party apps**: App store model with independent update cycle\n- **Cloud sync**: Configuration sync across vehicles\n\n## Best Practices\n\n1. **Always use A\u002FB partitioning**: Never update the running system\n2. **Implement rollback**: Automatic rollback after 3 boot failures\n3. **Verify signatures**: Multi-level signature verification (Uptane)\n4. **Use differential updates**: Reduce bandwidth by 70-90%\n5. **Stage fleet rollouts**: 1% -> 10% -> 100% deployment\n6. **Monitor success rates**: Track update success\u002Ffailure metrics\n7. **Preserve user data**: Never wipe data partitions\n8. **Test offline rollback**: Ensure rollback works without network\n9. **Schedule updates**: Respect user preferences and vehicle state\n10. **Log everything**: Comprehensive telemetry for debugging\n\n## Security Considerations\n\n- **Secure Boot**: Verify every component in boot chain\n- **Encrypted updates**: TLS for transport, encryption at rest\n- **Anti-rollback**: Prevent downgrade to vulnerable versions\n- **Time validity**: Reject updates with expired metadata\n- **Threshold signatures**: Require multiple signers (2 of 3)\n- **Hardware root of trust**: TPM or secure enclave for keys\n- **Audit logging**: Track all update attempts and outcomes\n\n## References\n\n- **Uptane**: https:\u002F\u002Fuptane.github.io\u002F\n- **Mender**: https:\u002F\u002Fmender.io\u002F\n- **SWUpdate**: https:\u002F\u002Fsbabic.github.io\u002Fswupdate\u002F\n- **RAUC**: https:\u002F\u002Frauc.io\u002F\n- **TUF Specification**: https:\u002F\u002Ftheupdateframework.io\u002F\n\n---\n\n## Vehicle App Stores\n\n# Vehicle App Stores — Automotive Application Platforms\n\nExpert knowledge of automotive app platforms, app lifecycle management, sandboxing, permissions model, revenue sharing, 3rd-party developer SDKs, and app certification.\n\n## Core Concepts\n\n### App Store Architecture\n\n1. **App Marketplace**: Discovery, purchase, installation\n2. **Developer Portal**: App submission, certification, analytics\n3. **Runtime Environment**: Sandboxed execution environment\n4. **Payment Integration**: In-app purchases, subscriptions\n5. **Update Management**: Automatic app updates\n\n### App Types\n\n- **Infotainment Apps**: Media, navigation, productivity\n- **ADAS Extensions**: Enhanced driver assistance features\n- **Telematics Apps**: Fleet management, usage tracking\n- **Comfort Apps**: Climate control, seat adjustments\n- **Diagnostic Tools**: Vehicle health monitoring\n\n## Production-Ready Implementation\n\n### 1. App Store Backend API (Python\u002FFastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVehicle App Store Backend API.\n\nHandles:\n- App catalog management\n- User authentication and purchases\n- App installation and updates\n- Developer portal integration\n\"\"\"\n\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom typing import List, Optional\nfrom fastapi import FastAPI, HTTPException, Depends, Security\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\nfrom pydantic import BaseModel, Field\nfrom sqlalchemy import create_engine, Column, String, Integer, Float, DateTime, Boolean, JSON\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, Session\nimport jwt\nimport hashlib\n\n\n# Database models\nBase = declarative_base()\n\n\nclass AppCategory(str, Enum):\n    \"\"\"App categories.\"\"\"\n    NAVIGATION = \"navigation\"\n    MEDIA = \"media\"\n    PRODUCTIVITY = \"productivity\"\n    GAMES = \"games\"\n    UTILITIES = \"utilities\"\n    ADAS = \"adas\"\n    DIAGNOSTICS = \"diagnostics\"\n\n\nclass AppStatus(str, Enum):\n    \"\"\"App certification status.\"\"\"\n    PENDING = \"pending\"\n    APPROVED = \"approved\"\n    REJECTED = \"rejected\"\n    SUSPENDED = \"suspended\"\n\n\nclass App(Base):\n    \"\"\"Application model.\"\"\"\n    __tablename__ = \"apps\"\n\n    id = Column(String, primary_key=True)\n    name = Column(String, nullable=False)\n    developer_id = Column(String, nullable=False)\n    category = Column(String, nullable=False)\n    version = Column(String, nullable=False)\n    description = Column(String)\n    price = Column(Float, default=0.0)\n    rating = Column(Float, default=0.0)\n    downloads = Column(Integer, default=0)\n    status = Column(String, default=AppStatus.PENDING.value)\n    manifest_url = Column(String)\n    icon_url = Column(String)\n    screenshots = Column(JSON, default=list)\n    permissions = Column(JSON, default=list)\n    min_platform_version = Column(String)\n    created_at = Column(DateTime, default=datetime.utcnow)\n    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)\n\n\nclass User(Base):\n    \"\"\"User model.\"\"\"\n    __tablename__ = \"users\"\n\n    id = Column(String, primary_key=True)\n    vin = Column(String, unique=True, nullable=False)  # Vehicle VIN\n    email = Column(String)\n    purchased_apps = Column(JSON, default=list)\n    installed_apps = Column(JSON, default=list)\n    created_at = Column(DateTime, default=datetime.utcnow)\n\n\nclass Purchase(Base):\n    \"\"\"Purchase transaction model.\"\"\"\n    __tablename__ = \"purchases\"\n\n    id = Column(String, primary_key=True)\n    user_id = Column(String, nullable=False)\n    app_id = Column(String, nullable=False)\n    amount = Column(Float)\n    transaction_date = Column(DateTime, default=datetime.utcnow)\n    status = Column(String, default=\"completed\")\n\n\n# Pydantic schemas\nclass AppCreate(BaseModel):\n    \"\"\"App creation schema.\"\"\"\n    name: str\n    developer_id: str\n    category: AppCategory\n    version: str\n    description: str\n    price: float = 0.0\n    manifest_url: str\n    icon_url: str\n    screenshots: List[str] = []\n    permissions: List[str] = []\n    min_platform_version: str = \"1.0.0\"\n\n\nclass AppResponse(BaseModel):\n    \"\"\"App response schema.\"\"\"\n    id: str\n    name: str\n    developer_id: str\n    category: str\n    version: str\n    description: str\n    price: float\n    rating: float\n    downloads: int\n    status: str\n    icon_url: str\n    screenshots: List[str]\n    permissions: List[str]\n    created_at: datetime\n\n    class Config:\n        from_attributes = True\n\n\nclass PurchaseRequest(BaseModel):\n    \"\"\"Purchase request schema.\"\"\"\n    app_id: str\n    payment_method: str = \"credit_card\"\n\n\nclass InstallRequest(BaseModel):\n    \"\"\"App installation request.\"\"\"\n    app_id: str\n\n\n# Initialize FastAPI\napp = FastAPI(title=\"Vehicle App Store API\", version=\"1.0.0\")\nsecurity = HTTPBearer()\n\n# Database setup\nDATABASE_URL = \"postgresql:\u002F\u002Fappstore:password@localhost\u002Fvehicle_appstore\"\nengine = create_engine(DATABASE_URL)\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n# JWT secret\nJWT_SECRET = \"your-secret-key-change-in-production\"\n\n\ndef get_db():\n    \"\"\"Database session dependency.\"\"\"\n    db = SessionLocal()\n    try:\n        yield db\n    finally:\n        db.close()\n\n\ndef verify_token(credentials: HTTPAuthorizationCredentials = Security(security)) -> dict:\n    \"\"\"Verify JWT token and extract user info.\"\"\"\n    try:\n        token = credentials.credentials\n        payload = jwt.decode(token, JWT_SECRET, algorithms=[\"HS256\"])\n        return payload\n    except jwt.ExpiredSignatureError:\n        raise HTTPException(status_code=401, detail=\"Token expired\")\n    except jwt.InvalidTokenError:\n        raise HTTPException(status_code=401, detail=\"Invalid token\")\n\n\n@app.post(\"\u002Fauth\u002Flogin\")\nasync def login(vin: str, db: Session = Depends(get_db)):\n    \"\"\"\n    Authenticate vehicle by VIN.\n\n    In production, this would verify VIN against manufacturer database.\n    \"\"\"\n    user = db.query(User).filter(User.vin == vin).first()\n\n    if not user:\n        # Create new user\n        user = User(id=hashlib.sha256(vin.encode()).hexdigest()[:16], vin=vin)\n        db.add(user)\n        db.commit()\n\n    # Generate JWT\n    token = jwt.encode(\n        {\n            \"user_id\": user.id,\n            \"vin\": user.vin,\n            \"exp\": datetime.utcnow() + timedelta(days=30)\n        },\n        JWT_SECRET,\n        algorithm=\"HS256\"\n    )\n\n    return {\"access_token\": token, \"token_type\": \"bearer\"}\n\n\n@app.get(\"\u002Fapps\", response_model=List[AppResponse])\nasync def list_apps(\n    category: Optional[AppCategory] = None,\n    search: Optional[str] = None,\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    List available apps.\n\n    Filters by category and search query.\n    Only returns approved apps.\n    \"\"\"\n    query = db.query(App).filter(App.status == AppStatus.APPROVED.value)\n\n    if category:\n        query = query.filter(App.category == category.value)\n\n    if search:\n        query = query.filter(App.name.ilike(f\"%{search}%\"))\n\n    apps = query.order_by(App.rating.desc(), App.downloads.desc()).limit(50).all()\n    return apps\n\n\n@app.get(\"\u002Fapps\u002F{app_id}\", response_model=AppResponse)\nasync def get_app(app_id: str, db: Session = Depends(get_db)):\n    \"\"\"Get app details.\"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    return app_obj\n\n\n@app.post(\"\u002Fapps\", response_model=AppResponse)\nasync def submit_app(\n    app_data: AppCreate,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Submit new app for certification.\n\n    Developer portal endpoint.\n    \"\"\"\n    app_id = hashlib.sha256(\n        f\"{app_data.name}{app_data.developer_id}{datetime.utcnow()}\".encode()\n    ).hexdigest()[:16]\n\n    app_obj = App(\n        id=app_id,\n        name=app_data.name,\n        developer_id=app_data.developer_id,\n        category=app_data.category.value,\n        version=app_data.version,\n        description=app_data.description,\n        price=app_data.price,\n        manifest_url=app_data.manifest_url,\n        icon_url=app_data.icon_url,\n        screenshots=app_data.screenshots,\n        permissions=app_data.permissions,\n        min_platform_version=app_data.min_platform_version,\n        status=AppStatus.PENDING.value\n    )\n\n    db.add(app_obj)\n    db.commit()\n    db.refresh(app_obj)\n\n    return app_obj\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Fpurchase\")\nasync def purchase_app(\n    app_id: str,\n    purchase_data: PurchaseRequest,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Purchase app.\n\n    Handles payment processing and license activation.\n    \"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    # Check if already purchased\n    if app_id in user.purchased_apps:\n        return {\"message\": \"App already purchased\", \"app_id\": app_id}\n\n    # Process payment (integrate with payment gateway)\n    # For demo purposes, assume payment succeeds\n    purchase_id = hashlib.sha256(\n        f\"{user.id}{app_id}{datetime.utcnow()}\".encode()\n    ).hexdigest()[:16]\n\n    purchase = Purchase(\n        id=purchase_id,\n        user_id=user.id,\n        app_id=app_id,\n        amount=app_obj.price,\n        status=\"completed\"\n    )\n\n    # Update user purchased apps\n    user.purchased_apps.append(app_id)\n\n    # Increment app downloads\n    app_obj.downloads += 1\n\n    db.add(purchase)\n    db.commit()\n\n    return {\n        \"message\": \"Purchase successful\",\n        \"purchase_id\": purchase_id,\n        \"app_id\": app_id,\n        \"amount\": app_obj.price\n    }\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Finstall\")\nasync def install_app(\n    app_id: str,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Install app to vehicle.\n\n    Returns manifest URL for vehicle runtime to download.\n    \"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    # Check if purchased\n    if app_id not in user.purchased_apps:\n        raise HTTPException(status_code=403, detail=\"App not purchased\")\n\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    # Add to installed apps\n    if app_id not in user.installed_apps:\n        user.installed_apps.append(app_id)\n        db.commit()\n\n    return {\n        \"message\": \"Installation initiated\",\n        \"app_id\": app_id,\n        \"manifest_url\": app_obj.manifest_url,\n        \"version\": app_obj.version\n    }\n\n\n@app.get(\"\u002Fapps\u002F{app_id}\u002Fupdates\")\nasync def check_app_updates(\n    app_id: str,\n    current_version: str,\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"\n    Check for app updates.\n\n    Returns latest version if newer than current.\n    \"\"\"\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    if not app_obj:\n        raise HTTPException(status_code=404, detail=\"App not found\")\n\n    if app_obj.version != current_version:\n        return {\n            \"update_available\": True,\n            \"latest_version\": app_obj.version,\n            \"manifest_url\": app_obj.manifest_url,\n            \"changelog\": f\"Updated to version {app_obj.version}\"\n        }\n\n    return {\"update_available\": False}\n\n\n@app.get(\"\u002Fuser\u002Fapps\")\nasync def get_user_apps(\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"Get user's purchased and installed apps.\"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    purchased = db.query(App).filter(App.id.in_(user.purchased_apps)).all()\n    installed = db.query(App).filter(App.id.in_(user.installed_apps)).all()\n\n    return {\n        \"purchased\": [AppResponse.from_orm(app) for app in purchased],\n        \"installed\": [AppResponse.from_orm(app) for app in installed]\n    }\n\n\n@app.post(\"\u002Fapps\u002F{app_id}\u002Frate\")\nasync def rate_app(\n    app_id: str,\n    rating: float = Field(..., ge=1.0, le=5.0),\n    user_info: dict = Depends(verify_token),\n    db: Session = Depends(get_db)\n):\n    \"\"\"Rate an app (1-5 stars).\"\"\"\n    user = db.query(User).filter(User.id == user_info[\"user_id\"]).first()\n\n    if app_id not in user.purchased_apps:\n        raise HTTPException(status_code=403, detail=\"Must own app to rate\")\n\n    app_obj = db.query(App).filter(App.id == app_id).first()\n\n    # Update rolling average (simplified)\n    # In production, store individual ratings\n    app_obj.rating = (app_obj.rating + rating) \u002F 2\n\n    db.commit()\n\n    return {\"message\": \"Rating submitted\", \"new_rating\": app_obj.rating}\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    Base.metadata.create_all(bind=engine)\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n### 2. App Manifest Format\n\n```yaml\n# App manifest - describes app metadata and requirements\n# File: app-manifest.yaml\n\napiVersion: vehicle.app\u002Fv1\nkind: VehicleApp\nmetadata:\n  name: spotify-automotive\n  version: 2.1.4\n  displayName: Spotify for Cars\n  developer:\n    id: spotify-inc\n    name: Spotify AB\n    email: automotive@spotify.com\n    website: https:\u002F\u002Fwww.spotify.com\n\nspec:\n  description: |\n    Stream millions of songs and podcasts directly in your vehicle.\n    Integrates with vehicle audio system and steering wheel controls.\n\n  category: media\n  price: 0.0  # Free with subscription\n  inAppPurchases: true\n\n  # Platform requirements\n  platform:\n    minVersion: \"2.0.0\"\n    targetVersion: \"3.1.0\"\n    architecture: [\"arm64\", \"x86_64\"]\n\n  # Permissions required\n  permissions:\n    - AUDIO_PLAYBACK\n    - INTERNET\n    - BLUETOOTH\n    - VEHICLE_SPEED  # For audio ducking when speed > 100mph\n    - STEERING_CONTROLS\n    - LOCATION  # For personalized recommendations\n\n  # Resource limits\n  resources:\n    memory: 512Mi\n    cpu: 500m\n    storage: 2Gi\n    bandwidth: 10Mbps\n\n  # Container configuration\n  container:\n    image: registry.spotify.com\u002Fautomotive\u002Fspotify:2.1.4\n    entrypoint: [\"\u002Fusr\u002Fbin\u002Fspotify-app\"]\n    environment:\n      - name: API_KEY\n        valueFrom:\n          secretRef:\n            name: spotify-api-credentials\n            key: api-key\n\n  # Service exposure\n  services:\n    - name: media-player\n      protocol: dbus\n      interface: org.mpris.MediaPlayer2\n      path: \u002Forg\u002Fmpris\u002FMediaPlayer2\u002Fspotify\n\n  # UI configuration\n  ui:\n    icon: https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Ficon-512.png\n    screenshots:\n      - https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Fscreenshot1.png\n      - https:\u002F\u002Fcdn.spotify.com\u002Fautomotive\u002Fscreenshot2.png\n    launchMode: fullscreen\n    displayInLauncher: true\n\n  # Integration points\n  integrations:\n    voiceAssistant:\n      enabled: true\n      wakeWords: [\"play music\", \"open spotify\"]\n    steeringControls:\n      enabled: true\n      actions: [play, pause, next, previous, volume]\n    clusterDisplay:\n      enabled: true\n      showNowPlaying: true\n\n  # Safety constraints\n  safety:\n    disableWhileDriving: false\n    touchInteractionLimit: true  # Limit UI interaction while moving\n    voiceControlRequired: false\n\n  # Analytics and telemetry\n  telemetry:\n    enabled: true\n    endpoint: https:\u002F\u002Ftelemetry.spotify.com\u002Fautomotive\n    dataTypes:\n      - usage_statistics\n      - crash_reports\n      - performance_metrics\n\n  # Update strategy\n  updatePolicy:\n    automatic: true\n    canRollback: true\n    maxDowntime: 30s\n```\n\n### 3. App Sandbox Runtime (Golang)\n\n```go\n\u002F\u002F Vehicle app sandbox runtime using containerd\n\u002F\u002F File: app-runtime.go\n\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"os\"\n    \"path\u002Ffilepath\"\n    \"syscall\"\n\n    \"github.com\u002Fcontainerd\u002Fcontainerd\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Fcio\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Fnamespaces\"\n    \"github.com\u002Fcontainerd\u002Fcontainerd\u002Foci\"\n    \"gopkg.in\u002Fyaml.v3\"\n)\n\n\u002F\u002F AppManifest represents vehicle app configuration\ntype AppManifest struct {\n    APIVersion string `yaml:\"apiVersion\"`\n    Kind       string `yaml:\"kind\"`\n    Metadata   struct {\n        Name        string `yaml:\"name\"`\n        Version     string `yaml:\"version\"`\n        DisplayName string `yaml:\"displayName\"`\n    } `yaml:\"metadata\"`\n    Spec struct {\n        Permissions []string `yaml:\"permissions\"`\n        Resources   struct {\n            Memory    string `yaml:\"memory\"`\n            CPU       string `yaml:\"cpu\"`\n            Storage   string `yaml:\"storage\"`\n            Bandwidth string `yaml:\"bandwidth\"`\n        } `yaml:\"resources\"`\n        Container struct {\n            Image       string   `yaml:\"image\"`\n            Entrypoint  []string `yaml:\"entrypoint\"`\n            Environment []struct {\n                Name  string `yaml:\"name\"`\n                Value string `yaml:\"value,omitempty\"`\n            } `yaml:\"environment\"`\n        } `yaml:\"container\"`\n        Safety struct {\n            DisableWhileDriving    bool `yaml:\"disableWhileDriving\"`\n            TouchInteractionLimit  bool `yaml:\"touchInteractionLimit\"`\n        } `yaml:\"safety\"`\n    } `yaml:\"spec\"`\n}\n\n\u002F\u002F AppRuntime manages vehicle app lifecycle\ntype AppRuntime struct {\n    client    *containerd.Client\n    namespace string\n}\n\n\u002F\u002F NewAppRuntime creates a new app runtime\nfunc NewAppRuntime() (*AppRuntime, error) {\n    client, err := containerd.New(\"\u002Frun\u002Fcontainerd\u002Fcontainerd.sock\")\n    if err != nil {\n        return nil, fmt.Errorf(\"failed to connect to containerd: %w\", err)\n    }\n\n    return &AppRuntime{\n        client:    client,\n        namespace: \"vehicle-apps\",\n    }, nil\n}\n\n\u002F\u002F InstallApp installs an app from manifest\nfunc (r *AppRuntime) InstallApp(manifestPath string) error {\n    \u002F\u002F Load manifest\n    manifest, err := r.loadManifest(manifestPath)\n    if err != nil {\n        return fmt.Errorf(\"failed to load manifest: %w\", err)\n    }\n\n    log.Printf(\"Installing app: %s v%s\", manifest.Metadata.Name, manifest.Metadata.Version)\n\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    \u002F\u002F Pull container image\n    image, err := r.client.Pull(ctx, manifest.Spec.Container.Image,\n        containerd.WithPullUnpack)\n    if err != nil {\n        return fmt.Errorf(\"failed to pull image: %w\", err)\n    }\n\n    log.Printf(\"Pulled image: %s\", image.Name())\n\n    \u002F\u002F Create container with security constraints\n    container, err := r.createSecureContainer(ctx, manifest, image)\n    if err != nil {\n        return fmt.Errorf(\"failed to create container: %w\", err)\n    }\n\n    log.Printf(\"App installed successfully: %s\", container.ID())\n    return nil\n}\n\n\u002F\u002F createSecureContainer creates a sandboxed container with security policies\nfunc (r *AppRuntime) createSecureContainer(\n    ctx context.Context,\n    manifest *AppManifest,\n    image containerd.Image,\n) (containerd.Container, error) {\n\n    appName := manifest.Metadata.Name\n\n    \u002F\u002F Define security policies based on permissions\n    opts := []oci.SpecOpts{\n        oci.WithImageConfig(image),\n        oci.WithEnv(r.buildEnvironment(manifest)),\n\n        \u002F\u002F Resource limits\n        oci.WithMemoryLimit(r.parseMemory(manifest.Spec.Resources.Memory)),\n        oci.WithCPUQuota(500000, 100000), \u002F\u002F 500m CPU\n\n        \u002F\u002F Security constraints\n        oci.WithNoNewPrivileges,\n        oci.WithPrivileged(false),\n\n        \u002F\u002F Read-only root filesystem\n        oci.WithRootFSReadonly(),\n\n        \u002F\u002F Drop all capabilities by default\n        oci.WithCapabilities([]string{}),\n\n        \u002F\u002F Add capabilities based on permissions\n        oci.WithAddedCapabilities(r.getCapabilities(manifest.Spec.Permissions)),\n\n        \u002F\u002F Mount tmpfs for writable directories\n        oci.WithMounts([]oci.Mount{\n            {\n                Type:        \"tmpfs\",\n                Source:      \"tmpfs\",\n                Destination: \"\u002Ftmp\",\n                Options:     []string{\"nosuid\", \"noexec\", \"nodev\"},\n            },\n            {\n                Type:        \"bind\",\n                Source:      filepath.Join(\"\u002Fvar\u002Flib\u002Fvehicle-apps\", appName, \"data\"),\n                Destination: \"\u002Fdata\",\n                Options:     []string{\"rbind\", \"rw\"},\n            },\n        }),\n\n        \u002F\u002F Namespace isolation\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"pid\",\n        }),\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"network\",\n        }),\n        oci.WithLinuxNamespace(oci.LinuxNamespace{\n            Type: \"ipc\",\n        }),\n    }\n\n    \u002F\u002F Permission-specific constraints\n    if !r.hasPermission(manifest.Spec.Permissions, \"INTERNET\") {\n        \u002F\u002F Block network access\n        opts = append(opts, oci.WithHostNamespace(oci.NetworkNamespace))\n    }\n\n    \u002F\u002F Create container\n    container, err := r.client.NewContainer(\n        ctx,\n        appName,\n        containerd.WithImage(image),\n        containerd.WithNewSnapshot(appName+\"-snapshot\", image),\n        containerd.WithNewSpec(opts...),\n    )\n\n    return container, err\n}\n\n\u002F\u002F StartApp starts an installed app\nfunc (r *AppRuntime) StartApp(appName string, manifest *AppManifest) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    \u002F\u002F Check safety constraints\n    if manifest.Spec.Safety.DisableWhileDriving {\n        if r.isVehicleMoving() {\n            return fmt.Errorf(\"app disabled while driving\")\n        }\n    }\n\n    \u002F\u002F Create task\n    task, err := container.NewTask(ctx, cio.NewCreator(cio.WithStdio))\n    if err != nil {\n        return fmt.Errorf(\"failed to create task: %w\", err)\n    }\n\n    \u002F\u002F Start task\n    if err := task.Start(ctx); err != nil {\n        return fmt.Errorf(\"failed to start task: %w\", err)\n    }\n\n    log.Printf(\"App started: %s (PID: %d)\", appName, task.Pid())\n    return nil\n}\n\n\u002F\u002F StopApp stops a running app\nfunc (r *AppRuntime) StopApp(appName string) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    task, err := container.Task(ctx, nil)\n    if err != nil {\n        return fmt.Errorf(\"failed to get task: %w\", err)\n    }\n\n    \u002F\u002F Graceful shutdown\n    if err := task.Kill(ctx, syscall.SIGTERM); err != nil {\n        return fmt.Errorf(\"failed to send SIGTERM: %w\", err)\n    }\n\n    \u002F\u002F Wait for exit (with timeout)\n    status, err := task.Wait(ctx)\n    if err != nil {\n        return fmt.Errorf(\"failed to wait for exit: %w\", err)\n    }\n\n    \u003C-status\n\n    log.Printf(\"App stopped: %s\", appName)\n    return nil\n}\n\n\u002F\u002F UninstallApp removes an installed app\nfunc (r *AppRuntime) UninstallApp(appName string) error {\n    ctx := namespaces.WithNamespace(context.Background(), r.namespace)\n\n    \u002F\u002F Stop if running\n    _ = r.StopApp(appName)\n\n    \u002F\u002F Delete container\n    container, err := r.client.LoadContainer(ctx, appName)\n    if err != nil {\n        return fmt.Errorf(\"failed to load container: %w\", err)\n    }\n\n    if err := container.Delete(ctx, containerd.WithSnapshotCleanup); err != nil {\n        return fmt.Errorf(\"failed to delete container: %w\", err)\n    }\n\n    log.Printf(\"App uninstalled: %s\", appName)\n    return nil\n}\n\n\u002F\u002F Helper functions\n\nfunc (r *AppRuntime) loadManifest(path string) (*AppManifest, error) {\n    data, err := os.ReadFile(path)\n    if err != nil {\n        return nil, err\n    }\n\n    var manifest AppManifest\n    if err := yaml.Unmarshal(data, &manifest); err != nil {\n        return nil, err\n    }\n\n    return &manifest, nil\n}\n\nfunc (r *AppRuntime) buildEnvironment(manifest *AppManifest) []string {\n    env := []string{}\n    for _, e := range manifest.Spec.Container.Environment {\n        env = append(env, fmt.Sprintf(\"%s=%s\", e.Name, e.Value))\n    }\n    return env\n}\n\nfunc (r *AppRuntime) parseMemory(mem string) uint64 {\n    \u002F\u002F Simple parser for Mi\u002FGi units\n    \u002F\u002F In production, use proper parsing\n    return 512 * 1024 * 1024 \u002F\u002F 512Mi\n}\n\nfunc (r *AppRuntime) getCapabilities(permissions []string) []string {\n    caps := []string{}\n\n    for _, perm := range permissions {\n        switch perm {\n        case \"INTERNET\":\n            caps = append(caps, \"CAP_NET_BIND_SERVICE\")\n        case \"BLUETOOTH\":\n            caps = append(caps, \"CAP_NET_ADMIN\")\n        case \"AUDIO_PLAYBACK\":\n            \u002F\u002F Allow access to audio devices\n        }\n    }\n\n    return caps\n}\n\nfunc (r *AppRuntime) hasPermission(permissions []string, perm string) bool {\n    for _, p := range permissions {\n        if p == perm {\n            return true\n        }\n    }\n    return false\n}\n\nfunc (r *AppRuntime) isVehicleMoving() bool {\n    \u002F\u002F Check vehicle speed from CAN bus\n    \u002F\u002F Placeholder implementation\n    return false\n}\n\nfunc main() {\n    runtime, err := NewAppRuntime()\n    if err != nil {\n        log.Fatalf(\"Failed to create runtime: %v\", err)\n    }\n\n    \u002F\u002F Example: Install and start app\n    if err := runtime.InstallApp(\"spotify-manifest.yaml\"); err != nil {\n        log.Fatalf(\"Failed to install app: %v\", err)\n    }\n\n    \u002F\u002F Load manifest for safety checks\n    manifest, _ := runtime.loadManifest(\"spotify-manifest.yaml\")\n\n    if err := runtime.StartApp(\"spotify-automotive\", manifest); err != nil {\n        log.Fatalf(\"Failed to start app: %v\", err)\n    }\n\n    log.Println(\"App runtime running...\")\n    select {} \u002F\u002F Keep running\n}\n```\n\n### 4. Developer SDK Example (TypeScript)\n\n```typescript\n\u002F\u002F Vehicle App Developer SDK\n\u002F\u002F File: vehicle-app-sdk.ts\n\n\u002F**\n * Vehicle App SDK for TypeScript\u002FJavaScript apps\n * Provides APIs for vehicle integration\n *\u002F\n\nexport enum Permission {\n  AUDIO_PLAYBACK = 'AUDIO_PLAYBACK',\n  INTERNET = 'INTERNET',\n  BLUETOOTH = 'BLUETOOTH',\n  VEHICLE_SPEED = 'VEHICLE_SPEED',\n  LOCATION = 'LOCATION',\n  STEERING_CONTROLS = 'STEERING_CONTROLS',\n  CLIMATE_CONTROL = 'CLIMATE_CONTROL',\n}\n\nexport interface VehicleState {\n  speed: number; \u002F\u002F km\u002Fh\n  gear: string;\n  isMoving: boolean;\n  batteryLevel: number; \u002F\u002F percentage\n  range: number; \u002F\u002F km\n}\n\nexport class VehicleAppSDK {\n  private readonly appId: string;\n  private readonly permissions: Permission[];\n  private ws: WebSocket | null = null;\n\n  constructor(appId: string, permissions: Permission[]) {\n    this.appId = appId;\n    this.permissions = permissions;\n  }\n\n  \u002F**\n   * Initialize SDK connection to vehicle platform\n   *\u002F\n  async initialize(): Promise\u003Cvoid> {\n    console.log(`Initializing SDK for app: ${this.appId}`);\n\n    \u002F\u002F Connect to vehicle platform via WebSocket\n    this.ws = new WebSocket('ws:\u002F\u002Fvehicle-platform:8080\u002Fapps\u002Fws');\n\n    return new Promise((resolve, reject) => {\n      this.ws!.onopen = () => {\n        console.log('Connected to vehicle platform');\n\n        \u002F\u002F Send authentication\n        this.ws!.send(JSON.stringify({\n          type: 'auth',\n          appId: this.appId,\n          permissions: this.permissions,\n        }));\n\n        resolve();\n      };\n\n      this.ws!.onerror = (error) => {\n        reject(new Error(`WebSocket error: ${error}`));\n      };\n    });\n  }\n\n  \u002F**\n   * Get current vehicle state\n   *\u002F\n  async getVehicleState(): Promise\u003CVehicleState> {\n    this.checkPermission(Permission.VEHICLE_SPEED);\n\n    return new Promise((resolve, reject) => {\n      const requestId = Date.now().toString();\n\n      this.ws!.send(JSON.stringify({\n        type: 'request',\n        requestId,\n        method: 'getVehicleState',\n      }));\n\n      const handler = (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        if (data.requestId === requestId) {\n          this.ws!.removeEventListener('message', handler);\n          resolve(data.result);\n        }\n      };\n\n      this.ws!.addEventListener('message', handler);\n\n      \u002F\u002F Timeout after 5 seconds\n      setTimeout(() => {\n        this.ws!.removeEventListener('message', handler);\n        reject(new Error('Request timeout'));\n      }, 5000);\n    });\n  }\n\n  \u002F**\n   * Subscribe to vehicle state changes\n   *\u002F\n  onVehicleStateChange(callback: (state: VehicleState) => void): void {\n    this.checkPermission(Permission.VEHICLE_SPEED);\n\n    this.ws!.addEventListener('message', (event) => {\n      const data = JSON.parse(event.data);\n      if (data.type === 'vehicleStateUpdate') {\n        callback(data.state);\n      }\n    });\n\n    \u002F\u002F Subscribe\n    this.ws!.send(JSON.stringify({\n      type: 'subscribe',\n      topic: 'vehicleState',\n    }));\n  }\n\n  \u002F**\n   * Control audio playback\n   *\u002F\n  async playAudio(url: string): Promise\u003Cvoid> {\n    this.checkPermission(Permission.AUDIO_PLAYBACK);\n\n    await this.sendRequest('playAudio', { url });\n  }\n\n  \u002F**\n   * Subscribe to steering control events\n   *\u002F\n  onSteeringControl(callback: (action: string) => void): void {\n    this.checkPermission(Permission.STEERING_CONTROLS);\n\n    this.ws!.addEventListener('message', (event) => {\n      const data = JSON.parse(event.data);\n      if (data.type === 'steeringControl') {\n        callback(data.action); \u002F\u002F 'next', 'previous', 'play', 'pause'\n      }\n    });\n\n    this.ws!.send(JSON.stringify({\n      type: 'subscribe',\n      topic: 'steeringControls',\n    }));\n  }\n\n  \u002F**\n   * Display notification in vehicle cluster\n   *\u002F\n  async showNotification(title: string, message: string): Promise\u003Cvoid> {\n    await this.sendRequest('showNotification', { title, message });\n  }\n\n  \u002F**\n   * Get current location\n   *\u002F\n  async getLocation(): Promise\u003C{ latitude: number; longitude: number }> {\n    this.checkPermission(Permission.LOCATION);\n\n    const result = await this.sendRequest('getLocation', {});\n    return result as { latitude: number; longitude: number };\n  }\n\n  private checkPermission(permission: Permission): void {\n    if (!this.permissions.includes(permission)) {\n      throw new Error(`Permission not granted: ${permission}`);\n    }\n  }\n\n  private async sendRequest(method: string, params: any): Promise\u003Cany> {\n    return new Promise((resolve, reject) => {\n      const requestId = Date.now().toString();\n\n      this.ws!.send(JSON.stringify({\n        type: 'request',\n        requestId,\n        method,\n        params,\n      }));\n\n      const handler = (event: MessageEvent) => {\n        const data = JSON.parse(event.data);\n        if (data.requestId === requestId) {\n          this.ws!.removeEventListener('message', handler);\n\n          if (data.error) {\n            reject(new Error(data.error));\n          } else {\n            resolve(data.result);\n          }\n        }\n      };\n\n      this.ws!.addEventListener('message', handler);\n\n      setTimeout(() => {\n        this.ws!.removeEventListener('message', handler);\n        reject(new Error('Request timeout'));\n      }, 5000);\n    });\n  }\n}\n\n\u002F\u002F Example app using SDK\nasync function exampleApp() {\n  const sdk = new VehicleAppSDK('spotify-automotive', [\n    Permission.AUDIO_PLAYBACK,\n    Permission.STEERING_CONTROLS,\n    Permission.VEHICLE_SPEED,\n  ]);\n\n  await sdk.initialize();\n\n  \u002F\u002F Get vehicle state\n  const state = await sdk.getVehicleState();\n  console.log(`Vehicle speed: ${state.speed} km\u002Fh`);\n\n  \u002F\u002F Subscribe to steering controls\n  sdk.onSteeringControl((action) => {\n    console.log(`Steering control: ${action}`);\n    if (action === 'play') {\n      sdk.playAudio('https:\u002F\u002Fcdn.spotify.com\u002Ftrack\u002F123.mp3');\n    }\n  });\n\n  \u002F\u002F Monitor vehicle state\n  sdk.onVehicleStateChange((state) => {\n    if (state.speed > 100) {\n      \u002F\u002F Duck audio volume at high speeds\n      console.log('High speed detected, reducing volume');\n    }\n  });\n}\n```\n\n## Real-World Examples\n\n### Tesla App Store Strategy\n- **Built-in apps**: Native Tesla apps (Netflix, YouTube, Spotify)\n- **No third-party yet**: Closed ecosystem for quality control\n- **Game integration**: Steam integration announced for Model S\u002FX\n- **API access**: Limited fleet API for developers\n\n### GM Ultifi Platform\n- **Open developer program**: Third-party app marketplace\n- **Revenue sharing**: 70\u002F30 split (developer\u002FGM)\n- **SDK availability**: Public SDK with APIs for vehicle data\n- **Categories**: Navigation, media, productivity, games\n\n### VW.OS App Store\n- **Phased rollout**: Starting with MEB platform (ID. series)\n- **Partner apps**: Curated partners initially\n- **In-car payment**: Integrated billing system\n- **Cross-brand**: Shared across VW Group brands\n\n### Rivian App Shop\n- **Adventure focus**: Apps for off-road, camping, outdoor\n- **Fleet integration**: Apps for commercial R1T owners\n- **OTA updates**: Apps update independently of vehicle software\n\n## Best Practices\n\n1. **Strict permission model**: Request only necessary permissions\n2. **Sandboxed execution**: Isolate apps from vehicle systems\n3. **Resource limits**: Enforce memory, CPU, bandwidth limits\n4. **Safety first**: Disable\u002Flimit apps while driving\n5. **Certification process**: Manual security review before approval\n6. **Privacy protection**: Transparent data collection policies\n7. **Offline functionality**: Apps should work without connectivity\n8. **Graceful degradation**: Handle missing permissions elegantly\n9. **Update mechanism**: Automatic updates for security patches\n10. **Rollback support**: Ability to rollback problematic updates\n\n## Security Considerations\n\n- **Code signing**: All apps must be signed by developer\n- **Runtime verification**: Verify signatures before execution\n- **Capability-based security**: Grant minimal capabilities\n- **Network isolation**: Apps cannot access vehicle CAN bus directly\n- **Data encryption**: Encrypt app data at rest\n- **Audit logging**: Log all permission requests and usage\n- **Kill switch**: Remote ability to disable compromised apps\n\n## References\n\n- **Android Automotive**: https:\u002F\u002Fsource.android.com\u002Fdevices\u002Fautomotive\n- **COVESA**: https:\u002F\u002Fcovesa.global\u002F\n- **GENIVI**: https:\u002F\u002Fwww.genivi.org\u002F\n- **Eclipse SDV**: https:\u002F\u002Fsdv.eclipse.org\u002F\n\n---\n\n## Vehicle Middleware Platforms\n\n# Vehicle Middleware Platforms — SDV Middleware Stacks\n\nExpert knowledge of SDV middleware stacks (COVESA VSS, Eclipse SDV, AUTOSAR Adaptive), data models (VSS\u002FVISS), pub-sub brokers, and service mesh for vehicles.\n\n## Core Concepts\n\n### Middleware Components\n\n1. **Data Abstraction**: VSS (Vehicle Signal Specification)\n2. **Service Communication**: SOME\u002FIP, DDS, MQTT\n3. **Service Discovery**: mDNS, service registries\n4. **Security**: TLS, authentication, authorization\n5. **Orchestration**: Lifecycle management\n\n### Key Standards\n\n- **COVESA VSS**: Standardized vehicle data model\n- **COVESA VISS**: Vehicle Information Service Specification (API)\n- **Eclipse SDV**: Open-source SDV components\n- **AUTOSAR Adaptive**: Service-oriented automotive architecture\n\n## Production-Ready Implementation\n\n### 1. VSS Data Model Implementation\n\n```yaml\n# Vehicle Signal Specification (VSS) tree\n# File: vehicle-signals.vspec\n\nVehicle:\n  description: Top-level vehicle\n  type: branch\n\nVehicle.Speed:\n  datatype: float\n  type: sensor\n  unit: km\u002Fh\n  description: Vehicle speed\n  min: 0\n  max: 300\n\nVehicle.Powertrain:\n  type: branch\n  description: Powertrain signals\n\nVehicle.Powertrain.Battery:\n  type: branch\n  description: Battery system\n\nVehicle.Powertrain.Battery.StateOfCharge:\n  datatype: float\n  type: sensor\n  unit: percent\n  description: Battery state of charge\n  min: 0\n  max: 100\n\nVehicle.Powertrain.Battery.Voltage:\n  datatype: float\n  type: sensor\n  unit: V\n  description: Battery voltage\n  min: 0\n  max: 800\n\nVehicle.Powertrain.Battery.Current:\n  datatype: float\n  type: sensor\n  unit: A\n  description: Battery current (positive = charging)\n  min: -400\n  max: 400\n\nVehicle.Powertrain.Battery.Temperature:\n  datatype: float\n  type: sensor\n  unit: celsius\n  description: Battery temperature\n  min: -40\n  max: 80\n\nVehicle.Cabin:\n  type: branch\n  description: Cabin signals\n\nVehicle.Cabin.HVAC:\n  type: branch\n  description: HVAC system\n\nVehicle.Cabin.HVAC.IsAirConditioningActive:\n  datatype: boolean\n  type: actuator\n  description: Air conditioning status\n\nVehicle.Cabin.HVAC.AmbientAirTemperature:\n  datatype: float\n  type: sensor\n  unit: celsius\n  description: Ambient temperature\n\nVehicle.Body:\n  type: branch\n  description: Body signals\n\nVehicle.Body.Doors:\n  type: branch\n  instances:\n    - Row1Left\n    - Row1Right\n    - Row2Left\n    - Row2Right\n\nVehicle.Body.Doors.IsLocked:\n  datatype: boolean\n  type: actuator\n  description: Door lock status\n\nVehicle.Body.Doors.IsOpen:\n  datatype: boolean\n  type: sensor\n  description: Door open status\n\nVehicle.ADAS:\n  type: branch\n  description: ADAS signals\n\nVehicle.ADAS.CruiseControl:\n  type: branch\n  description: Cruise control\n\nVehicle.ADAS.CruiseControl.IsActive:\n  datatype: boolean\n  type: actuator\n  description: Cruise control active\n\nVehicle.ADAS.CruiseControl.SpeedSet:\n  datatype: float\n  type: actuator\n  unit: km\u002Fh\n  description: Set cruise control speed\n```\n\n### 2. VSS Data Broker (Rust)\n\n```rust\n\u002F\u002F VSS data broker implementation\n\u002F\u002F File: vss-broker\u002Fsrc\u002Fmain.rs\n\nuse tokio;\nuse std::collections::HashMap;\nuse std::sync::{Arc, RwLock};\nuse serde::{Deserialize, Serialize};\nuse warp::Filter;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\nstruct VehicleSignal {\n    path: String,\n    value: SignalValue,\n    timestamp: u64,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\nenum SignalValue {\n    Float(f64),\n    Int(i64),\n    Bool(bool),\n    String(String),\n}\n\n#[derive(Clone)]\nstruct DataBroker {\n    signals: Arc\u003CRwLock\u003CHashMap\u003CString, VehicleSignal>>>,\n    subscribers: Arc\u003CRwLock\u003CHashMap\u003CString, Vec\u003Ctokio::sync::mpsc::UnboundedSender\u003CVehicleSignal>>>>>,\n}\n\nimpl DataBroker {\n    fn new() -> Self {\n        DataBroker {\n            signals: Arc::new(RwLock::new(HashMap::new())),\n            subscribers: Arc::new(RwLock::new(HashMap::new())),\n        }\n    }\n\n    \u002F\u002F\u002F Get signal value\n    fn get(&self, path: &str) -> Option\u003CVehicleSignal> {\n        let signals = self.signals.read().unwrap();\n        signals.get(path).cloned()\n    }\n\n    \u002F\u002F\u002F Set signal value\n    fn set(&self, signal: VehicleSignal) {\n        let path = signal.path.clone();\n\n        \u002F\u002F Store signal\n        {\n            let mut signals = self.signals.write().unwrap();\n            signals.insert(path.clone(), signal.clone());\n        }\n\n        \u002F\u002F Notify subscribers\n        self.notify_subscribers(&path, signal);\n    }\n\n    \u002F\u002F\u002F Subscribe to signal updates\n    fn subscribe(&self, path: String) -> tokio::sync::mpsc::UnboundedReceiver\u003CVehicleSignal> {\n        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();\n\n        let mut subscribers = self.subscribers.write().unwrap();\n        subscribers.entry(path).or_insert_with(Vec::new).push(tx);\n\n        rx\n    }\n\n    \u002F\u002F\u002F Notify subscribers of signal update\n    fn notify_subscribers(&self, path: &str, signal: VehicleSignal) {\n        let subscribers = self.subscribers.read().unwrap();\n\n        if let Some(subs) = subscribers.get(path) {\n            for tx in subs {\n                let _ = tx.send(signal.clone());\n            }\n        }\n\n        \u002F\u002F Also notify wildcard subscribers (path.*)\n        let parts: Vec\u003C&str> = path.split('.').collect();\n        for i in 0..parts.len() {\n            let wildcard_path = format!(\"{}.*\", parts[..i].join(\".\"));\n            if let Some(subs) = subscribers.get(&wildcard_path) {\n                for tx in subs {\n                    let _ = tx.send(signal.clone());\n                }\n            }\n        }\n    }\n\n    \u002F\u002F\u002F Batch get signals\n    fn get_batch(&self, paths: Vec\u003CString>) -> HashMap\u003CString, VehicleSignal> {\n        let signals = self.signals.read().unwrap();\n        let mut result = HashMap::new();\n\n        for path in paths {\n            if let Some(signal) = signals.get(&path) {\n                result.insert(path, signal.clone());\n            }\n        }\n\n        result\n    }\n}\n\n#[tokio::main]\nasync fn main() {\n    let broker = DataBroker::new();\n    let broker = Arc::new(broker);\n\n    \u002F\u002F REST API routes\n    let broker_filter = warp::any().map(move || broker.clone());\n\n    \u002F\u002F GET \u002Fapi\u002Fsignals\u002F{path}\n    let get_signal = warp::path!(\"api\" \u002F \"signals\" \u002F String)\n        .and(warp::get())\n        .and(broker_filter.clone())\n        .map(|path: String, broker: Arc\u003CDataBroker>| {\n            match broker.get(&path) {\n                Some(signal) => warp::reply::json(&signal),\n                None => warp::reply::json(&serde_json::json!({\n                    \"error\": \"Signal not found\"\n                })),\n            }\n        });\n\n    \u002F\u002F POST \u002Fapi\u002Fsignals\n    let set_signal = warp::path!(\"api\" \u002F \"signals\")\n        .and(warp::post())\n        .and(warp::body::json())\n        .and(broker_filter.clone())\n        .map(|signal: VehicleSignal, broker: Arc\u003CDataBroker>| {\n            broker.set(signal.clone());\n            warp::reply::json(&serde_json::json!({\n                \"status\": \"ok\",\n                \"path\": signal.path\n            }))\n        });\n\n    \u002F\u002F WebSocket \u002Fapi\u002Fsubscribe\n    let subscribe = warp::path!(\"api\" \u002F \"subscribe\")\n        .and(warp::ws())\n        .and(broker_filter.clone())\n        .map(|ws: warp::ws::Ws, broker: Arc\u003CDataBroker>| {\n            ws.on_upgrade(move |socket| handle_websocket(socket, broker))\n        });\n\n    let routes = get_signal\n        .or(set_signal)\n        .or(subscribe);\n\n    println!(\"[VSS Broker] Starting on 0.0.0.0:8080\");\n    warp::serve(routes)\n        .run(([0, 0, 0, 0], 8080))\n        .await;\n}\n\nasync fn handle_websocket(\n    websocket: warp::ws::WebSocket,\n    broker: Arc\u003CDataBroker>\n) {\n    use futures::{StreamExt, SinkExt};\n\n    let (mut tx, mut rx) = websocket.split();\n\n    \u002F\u002F Handle incoming subscription requests\n    while let Some(result) = rx.next().await {\n        let msg = match result {\n            Ok(msg) => msg,\n            Err(e) => {\n                eprintln!(\"WebSocket error: {}\", e);\n                break;\n            }\n        };\n\n        if let Ok(text) = msg.to_str() {\n            \u002F\u002F Parse subscription request\n            if let Ok(req) = serde_json::from_str::\u003Cserde_json::Value>(text) {\n                if let Some(path) = req[\"path\"].as_str() {\n                    let path = path.to_string();\n                    let mut signal_rx = broker.subscribe(path.clone());\n\n                    \u002F\u002F Send updates\n                    tokio::spawn(async move {\n                        while let Some(signal) = signal_rx.recv().await {\n                            let json = serde_json::to_string(&signal).unwrap();\n                            if tx.send(warp::ws::Message::text(json)).await.is_err() {\n                                break;\n                            }\n                        }\n                    });\n                }\n            }\n        }\n    }\n}\n```\n\n### 3. VISS Server (Python\u002FFastAPI)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nVISS (Vehicle Information Service Specification) server.\nRESTful and WebSocket API for VSS data access.\n\"\"\"\n\nfrom fastapi import FastAPI, WebSocket, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\nfrom typing import Optional, List, Dict, Any\nimport asyncio\nimport json\nfrom datetime import datetime\n\n\napp = FastAPI(title=\"VISS Server\", version=\"2.0.0\")\n\n\nclass VehicleSignal(BaseModel):\n    \"\"\"Vehicle signal data model.\"\"\"\n    path: str\n    value: Any\n    timestamp: Optional[int] = None\n\n\nclass GetRequest(BaseModel):\n    \"\"\"VISS GET request.\"\"\"\n    action: str = \"get\"\n    path: str\n    requestId: str\n\n\nclass SetRequest(BaseModel):\n    \"\"\"VISS SET request.\"\"\"\n    action: str = \"set\"\n    path: str\n    value: Any\n    requestId: str\n\n\nclass SubscribeRequest(BaseModel):\n    \"\"\"VISS SUBSCRIBE request.\"\"\"\n    action: str = \"subscribe\"\n    path: str\n    subscriptionId: str\n\n\n# In-memory signal storage (replace with Redis in production)\nsignals_db: Dict[str, VehicleSignal] = {}\n\n# WebSocket subscriptions\nsubscriptions: Dict[str, List[WebSocket]] = {}\n\n\n@app.get(\"\u002Fvss\u002Fapi\u002Fv2\u002F{path:path}\")\nasync def get_signal_rest(path: str):\n    \"\"\"\n    Get signal value via REST API.\n\n    Example: GET \u002Fvss\u002Fapi\u002Fv2\u002FVehicle\u002FSpeed\n    \"\"\"\n    if path not in signals_db:\n        raise HTTPException(status_code=404, detail=\"Signal not found\")\n\n    signal = signals_db[path]\n\n    return JSONResponse({\n        \"action\": \"get\",\n        \"path\": path,\n        \"value\": signal.value,\n        \"timestamp\": signal.timestamp or int(datetime.utcnow().timestamp() * 1000),\n        \"requestId\": \"rest-\" + str(int(datetime.utcnow().timestamp()))\n    })\n\n\n@app.put(\"\u002Fvss\u002Fapi\u002Fv2\u002F{path:path}\")\nasync def set_signal_rest(path: str, value: Any):\n    \"\"\"\n    Set signal value via REST API.\n\n    Example: PUT \u002Fvss\u002Fapi\u002Fv2\u002FVehicle\u002FCabin\u002FHVAC\u002FIsAirConditioningActive\n    Body: {\"value\": true}\n    \"\"\"\n    signal = VehicleSignal(\n        path=path,\n        value=value,\n        timestamp=int(datetime.utcnow().timestamp() * 1000)\n    )\n\n    signals_db[path] = signal\n\n    # Notify subscribers\n    await notify_subscribers(path, signal)\n\n    return JSONResponse({\n        \"action\": \"set\",\n        \"path\": path,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": \"rest-\" + str(int(datetime.utcnow().timestamp()))\n    })\n\n\n@app.websocket(\"\u002Fvss\u002Fapi\u002Fv2\")\nasync def websocket_endpoint(websocket: WebSocket):\n    \"\"\"\n    VISS WebSocket endpoint for real-time communication.\n\n    Supports:\n    - GET: Get signal value\n    - SET: Set signal value\n    - SUBSCRIBE: Subscribe to signal updates\n    - UNSUBSCRIBE: Unsubscribe from signal\n    \"\"\"\n    await websocket.accept()\n\n    try:\n        while True:\n            # Receive request\n            data = await websocket.receive_text()\n            request = json.loads(data)\n\n            action = request.get(\"action\")\n\n            if action == \"get\":\n                await handle_get(websocket, request)\n            elif action == \"set\":\n                await handle_set(websocket, request)\n            elif action == \"subscribe\":\n                await handle_subscribe(websocket, request)\n            elif action == \"unsubscribe\":\n                await handle_unsubscribe(websocket, request)\n            else:\n                await websocket.send_json({\n                    \"error\": {\"number\": 400, \"message\": \"Invalid action\"},\n                    \"requestId\": request.get(\"requestId\", \"unknown\")\n                })\n\n    except Exception as e:\n        print(f\"[VISS] WebSocket error: {e}\")\n    finally:\n        # Clean up subscriptions\n        for path, subs in subscriptions.items():\n            if websocket in subs:\n                subs.remove(websocket)\n\n\nasync def handle_get(websocket: WebSocket, request: dict):\n    \"\"\"Handle GET request.\"\"\"\n    path = request[\"path\"]\n\n    if path not in signals_db:\n        await websocket.send_json({\n            \"action\": \"get\",\n            \"error\": {\"number\": 404, \"message\": \"Signal not found\"},\n            \"requestId\": request[\"requestId\"]\n        })\n        return\n\n    signal = signals_db[path]\n\n    await websocket.send_json({\n        \"action\": \"get\",\n        \"path\": path,\n        \"value\": signal.value,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": request[\"requestId\"]\n    })\n\n\nasync def handle_set(websocket: WebSocket, request: dict):\n    \"\"\"Handle SET request.\"\"\"\n    path = request[\"path\"]\n    value = request[\"value\"]\n\n    signal = VehicleSignal(\n        path=path,\n        value=value,\n        timestamp=int(datetime.utcnow().timestamp() * 1000)\n    )\n\n    signals_db[path] = signal\n\n    # Notify subscribers\n    await notify_subscribers(path, signal)\n\n    await websocket.send_json({\n        \"action\": \"set\",\n        \"path\": path,\n        \"timestamp\": signal.timestamp,\n        \"requestId\": request[\"requestId\"]\n    })\n\n\nasync def handle_subscribe(websocket: WebSocket, request: dict):\n    \"\"\"Handle SUBSCRIBE request.\"\"\"\n    path = request[\"path\"]\n    subscription_id = request[\"subscriptionId\"]\n\n    # Add to subscriptions\n    if path not in subscriptions:\n        subscriptions[path] = []\n\n    subscriptions[path].append(websocket)\n\n    # Send confirmation\n    await websocket.send_json({\n        \"action\": \"subscribe\",\n        \"subscriptionId\": subscription_id,\n        \"timestamp\": int(datetime.utcnow().timestamp() * 1000)\n    })\n\n\nasync def handle_unsubscribe(websocket: WebSocket, request: dict):\n    \"\"\"Handle UNSUBSCRIBE request.\"\"\"\n    subscription_id = request[\"subscriptionId\"]\n\n    # Remove from subscriptions\n    for path, subs in subscriptions.items():\n        if websocket in subs:\n            subs.remove(websocket)\n\n    await websocket.send_json({\n        \"action\": \"unsubscribe\",\n        \"subscriptionId\": subscription_id,\n        \"timestamp\": int(datetime.utcnow().timestamp() * 1000)\n    })\n\n\nasync def notify_subscribers(path: str, signal: VehicleSignal):\n    \"\"\"Notify all subscribers of signal update.\"\"\"\n    if path in subscriptions:\n        notification = {\n            \"action\": \"subscription\",\n            \"path\": path,\n            \"value\": signal.value,\n            \"timestamp\": signal.timestamp\n        }\n\n        # Send to all subscribers\n        dead_sockets = []\n        for websocket in subscriptions[path]:\n            try:\n                await websocket.send_json(notification)\n            except Exception:\n                dead_sockets.append(websocket)\n\n        # Remove dead sockets\n        for ws in dead_sockets:\n            subscriptions[path].remove(ws)\n\n\n# Populate some initial data\n@app.on_event(\"startup\")\nasync def populate_initial_data():\n    \"\"\"Populate initial vehicle signals.\"\"\"\n    initial_signals = [\n        VehicleSignal(path=\"Vehicle.Speed\", value=0.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.StateOfCharge\", value=80.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.Voltage\", value=400.0),\n        VehicleSignal(path=\"Vehicle.Powertrain.Battery.Current\", value=0.0),\n        VehicleSignal(path=\"Vehicle.Cabin.HVAC.IsAirConditioningActive\", value=False),\n        VehicleSignal(path=\"Vehicle.Body.Doors.Row1Left.IsLocked\", value=True),\n        VehicleSignal(path=\"Vehicle.ADAS.CruiseControl.IsActive\", value=False),\n    ]\n\n    for signal in initial_signals:\n        signal.timestamp = int(datetime.utcnow().timestamp() * 1000)\n        signals_db[signal.path] = signal\n\n    print(\"[VISS] Initial signals populated\")\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n```\n\n### 4. Service Mesh Configuration (Istio-like for Automotive)\n\n```yaml\n# Service mesh configuration for vehicle platform\n# File: vehicle-service-mesh.yaml\n\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: service-mesh-config\n  namespace: vehicle-platform\ndata:\n  mesh-config.yaml: |\n    # Global mesh configuration\n    defaultConfig:\n      discoveryAddress: mesh-pilot.vehicle-platform.svc:15010\n      tracing:\n        zipkin:\n          address: zipkin.vehicle-platform.svc:9411\n      proxyMetadata:\n        ISTIO_META_DNS_CAPTURE: \"true\"\n        ISTIO_META_DNS_AUTO_ALLOCATE: \"true\"\n\n    # Access logging\n    accessLogFile: \u002Fdev\u002Fstdout\n    accessLogEncoding: JSON\n\n    # mTLS configuration\n    enableAutoMtls: true\n\n    # Trust domain\n    trustDomain: vehicle.local\n\n    # Service discovery\n    defaultServiceExportTo:\n      - \"*\"\n\n---\napiVersion: networking.istio.io\u002Fv1alpha3\nkind: VirtualService\nmetadata:\n  name: vss-broker\nspec:\n  hosts:\n    - vss-broker.vehicle-platform.svc\n  http:\n    - match:\n        - uri:\n            prefix: \u002Fapi\u002Fsignals\n      route:\n        - destination:\n            host: vss-broker.vehicle-platform.svc\n            port:\n              number: 8080\n      timeout: 5s\n      retries:\n        attempts: 3\n        perTryTimeout: 2s\n\n---\napiVersion: networking.istio.io\u002Fv1alpha3\nkind: DestinationRule\nmetadata:\n  name: vss-broker\nspec:\n  host: vss-broker.vehicle-platform.svc\n  trafficPolicy:\n    loadBalancer:\n      simple: ROUND_ROBIN\n    connectionPool:\n      tcp:\n        maxConnections: 100\n      http:\n        http1MaxPendingRequests: 50\n        http2MaxRequests: 100\n    outlierDetection:\n      consecutiveErrors: 5\n      interval: 30s\n      baseEjectionTime: 60s\n      maxEjectionPercent: 50\n\n---\napiVersion: security.istio.io\u002Fv1beta1\nkind: PeerAuthentication\nmetadata:\n  name: default\n  namespace: vehicle-platform\nspec:\n  mtls:\n    mode: STRICT\n\n---\napiVersion: security.istio.io\u002Fv1beta1\nkind: AuthorizationPolicy\nmetadata:\n  name: vss-access-control\n  namespace: vehicle-platform\nspec:\n  selector:\n    matchLabels:\n      app: vss-broker\n  action: ALLOW\n  rules:\n    - from:\n        - source:\n            principals: [\"cluster.local\u002Fns\u002Finfotainment\u002Fsa\u002Fspotify\"]\n      to:\n        - operation:\n            methods: [\"GET\"]\n            paths: [\"\u002Fapi\u002Fsignals\u002FVehicle\u002FSpeed\"]\n```\n\n### 5. Eclipse Kuksa Integration\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nEclipse Kuksa.VAL integration for VSS data access.\n\"\"\"\n\nimport asyncio\nfrom kuksa_client.grpc import VSSClient\nfrom kuksa_client.grpc.aio import VSSClientAsync\n\n\nasync def main():\n    \"\"\"Example Kuksa.VAL client.\"\"\"\n\n    # Connect to Kuksa databroker\n    async with VSSClientAsync('127.0.0.1', 55555) as client:\n        print(\"[Kuksa] Connected to data broker\")\n\n        # Set signal value\n        await client.set_current_values({\n            'Vehicle.Speed': 65.5,\n            'Vehicle.Powertrain.Battery.StateOfCharge': 75.0\n        })\n\n        print(\"[Kuksa] Signals set\")\n\n        # Get signal value\n        response = await client.get_current_values([\n            'Vehicle.Speed',\n            'Vehicle.Powertrain.Battery.StateOfCharge'\n        ])\n\n        for entry in response.entries:\n            print(f\"[Kuksa] {entry.path} = {entry.value.double}\")\n\n        # Subscribe to signal\n        async for updates in client.subscribe_current_values([\n            'Vehicle.Speed'\n        ]):\n            for update in updates.updates:\n                print(f\"[Kuksa] Update: {update.entry.path} = {update.entry.value.double}\")\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## Real-World Examples\n\n### COVESA (Connected Vehicle Systems Alliance)\n- **VSS Standard**: De facto vehicle data model\n- **VISS API**: RESTful and WebSocket access to VSS\n- **Industry adoption**: BMW, Ford, Tesla, VW all exploring VSS\n\n### Eclipse SDV Working Group\n- **Kuksa.VAL**: Reference VSS data broker\n- **Eclipse Leda**: SDV platform distribution\n- **Eclipse Ankaios**: Workload orchestrator\n- **Eclipse Zenoh**: Unified communication middleware\n\n### AUTOSAR Adaptive\n- **Service-oriented**: Pub\u002Fsub and RPC services\n- **SOME\u002FIP**: Scalable service-oriented middleware\n- **Ara::Com**: Communication management API\n- **Service discovery**: Dynamic service registration\n\n### Apex.AI\n- **ROS 2 for automotive**: Safe, real-time ROS 2\n- **DDS middleware**: OMG Data Distribution Service\n- **Apex.OS**: Automotive-grade Linux + ROS 2\n\n## Best Practices\n\n1. **Use VSS**: Standardize on VSS data model\n2. **Service mesh**: Use service mesh for inter-service communication\n3. **mTLS everywhere**: Mutual TLS for all service communication\n4. **API gateway**: Centralized API management\n5. **Rate limiting**: Protect services from overload\n6. **Circuit breakers**: Handle service failures gracefully\n7. **Observability**: Distributed tracing (Zipkin, Jaeger)\n8. **Service discovery**: Dynamic service registration\n9. **Version management**: API versioning strategy\n10. **Documentation**: OpenAPI specs for all services\n\n## Security Considerations\n\n- **mTLS**: Mutual authentication between services\n- **RBAC**: Role-based access control for VSS signals\n- **API keys**: Authenticate app access to services\n- **Rate limiting**: Prevent abuse\n- **Audit logging**: Log all signal access\n- **Encryption**: Encrypt sensitive signals at rest\n- **Network policies**: Restrict service-to-service communication\n\n## References\n\n- **COVESA VSS**: https:\u002F\u002Fcovesa.global\u002F\n- **Eclipse Kuksa**: https:\u002F\u002Fwww.eclipse.org\u002Fkuksa\u002F\n- **Eclipse SDV**: https:\u002F\u002Fsdv.eclipse.org\u002F\n- **AUTOSAR Adaptive**: https:\u002F\u002Fwww.autosar.org\u002Fstandards\u002Fadaptive-platform\u002F\n- **SOME\u002FIP**: https:\u002F\u002Fsome-ip.com\u002F\n- **Zenoh**: https:\u002F\u002Fzenoh.io\u002F\n",{"name":5,"tags":23,"description":25},[24,5],"automotive","Automotive Sdv expertise. Covers 6 topics: Cloud Vehicle Integration, Containerized Vehicle Apps, Digital Twin Vehicles, Ota Update Systems, Vehicle App Stores.\n","main","764e05645935fe0d4c219ab3786883289700a063","skills\u002Fautomotive-sdv",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-sdv",{"tool":39,"command":40},"bunx","bunx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-sdv",{"tool":42,"command":43},"pnpm","pnpm dlx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-sdv","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-sdv\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",[],[]]