[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7E9VABK8EAQ83EW4KEJC9YA":3,"skill-same:01M7E9VABK8EAQ83EW4KEJC9YA":92},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":72,"commitSha":73,"skillDirectory":74,"forksCount":14,"repositoryHtmlUrl":75,"repositoryHomepageUrl":75,"ownerHtmlUrl":76,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":77,"install":78,"resources":91},"01M7E9VABK8EAQ83EW4KEJC9YA","automotive-middleware",null,"Expert in AMQP (Advanced Message Queuing Protocol) middleware for automotive enterprise integration using RabbitMQ and Azure Service Bus. Covers 6 topics across middleware domain. Includes 6 skill files covering AMQP 1.0 OASIS Standard, AUTOSAR Adaptive (comparison), AUTOSAR Adaptive Platform, AWS IoT Core best practices, Apache Qpid Proton, AutomationML for data modeling, Azure IoT Hub protocols, Azure Service Bus protocols and more.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fautomotive\u002Fautomotive-middleware\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: automotive-middleware\ndescription: >\n  Expert in AMQP (Advanced Message Queuing Protocol) middleware for automotive enterprise integration using RabbitMQ and Azure Service Bus. Covers 6 topics across middleware domain. Includes 6 skill files covering AMQP 1.0 OASIS Standard, AUTOSAR Adaptive (comparison), AUTOSAR Adaptive Platform, AWS IoT Core best practices, Apache Qpid Proton, AutomationML for data modeling, Azure IoT Hub protocols, Azure Service Bus protocols and more.\ntags: [adas, amqp, automotive, automotive-middleware, autonomous-driving, autosar, aws, azure, battery, cloud, coap, constrained, dds, digital-twin, dtls, embedded, enterprise, fleet-management, industrial, industry-4.0, iot, iso-26262, manufacturing, mes, middleware, mqtt, opcua, ota, plc, pub-sub, rabbitmq, real-time, robotics, ros2, scada, sensor-fusion, simulation, slam, supply-chain, telemetry, tpms, udp, v2x]\nsource: \"https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\"\nsource_repository: \"pangzhenying2025\u002Fhermes-automotive-skills\"\nsource_path: \"skills\u002Fautomotive-middleware\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n# Automotive Middleware\n\n6 skill files covering middleware domain for automotive software engineering.\n\n## Applicable Standards\n\n- AMQP 1.0 OASIS Standard\n- AUTOSAR Adaptive (comparison)\n- AUTOSAR Adaptive Platform\n- AWS IoT Core best practices\n- Apache Qpid Proton\n- AutomationML for data modeling\n- Azure IoT Hub protocols\n- Azure Service Bus protocols\n- DDS 1.4 Specification\n- DDS Security 1.1\n- DDS-RTPS 2.5\n- DTLS 1.2 (Security)\n- GDPR compliance for telemetry data\n- IEC 62541 (OPC UA Standard)\n- ISO 21434 (Cybersecurity)\n- ISO 26262 (Functional Safety for ADAS)\n- ISO 26262 (Functional Safety)\n- ISO 26262 (when interfacing with vehicle systems)\n- MQTT 5.0 (comparison context)\n- MQTT 5.0 Specification\n- MQTT-OPC UA Gateway (Sparkplug B)\n- RFC 7252 (CoAP)\n- RFC 7959 (CoAP Block-Wise Transfer)\n- RFC 8132 (CoAP PATCH\u002FFETCH)\n- RFC 8323 (CoAP over TCP\u002FTLS\u002FWebSockets)\n- ROS 2 Design Principles\n- RTPS 2.5 Protocol\n- TISAX (Trusted Information Security Assessment)\n\n## Use Cases\n\n- Factory-to-vehicle data exchange\n- Manufacturing execution system (MES) integration\n- Order-to-delivery workflow orchestration\n- Parts inventory and supply chain messaging\n- Quality assurance data pipelines\n- Dealer network communication\n- Low-power ECU communication\n- Battery monitoring telemetry (minimal overhead)\n- Wireless sensor networks in vehicle\n- Tire pressure monitoring systems (TPMS)\n- V2X communication over 6LoWPAN\n- Edge device telemetry with cellular IoT (NB-IoT, LTE-M)\n- ADAS sensor data distribution with deterministic latency\n- V2X communication with QoS guarantees\n- Real-time ECU-to-ECU communication\n- Safety-critical data exchange (ISO 26262 ASIL-D)\n- Multi-domain vehicle networking\n- Edge computing data streams\n- Vehicle-to-Cloud telemetry streaming\n- Remote diagnostics and OTA updates\n\n## Topics Covered\n\n### Enterprise Messaging\n\n- amqp-middleware\n\n### Industrial Integration\n\n- opcua-middleware\n\n### Iot Constrained\n\n- coap-middleware\n\n### Iot Telemetry\n\n- mqtt-middleware\n\n### Real Time Pub Sub\n\n- dds-middleware\n\n### Robotics Autonomy\n\n- ros2-dds-middleware\n\n## Constraints\n\n- 10 msg\u002Fsec per vehicle\n- 10,000 messages\n- 128KB per message\n- 256KB (RabbitMQ), 1MB (Azure)\n- 60 seconds keep-alive\n- CON messages for commands and configuration\n- Client certificates required for production\n- DDS Security mandatory for production deployment\n- DDS Security mandatory for production vehicles\n- DTLS 1.2+ required for production\n- Dead letter queues for all queues\n- Deterministic latency \u003C 10ms p99 for safety topics\n- Discovery time \u003C 2 seconds for static discovery\n- ISO 26262 ASIL-D capable implementations only\n- Max 10,000 nodes per server (scalability)\n\n## Required Tools\n\n- AWS IoT Device SDK\n- Azure IoT SDK\n- Azure Service Bus SDK\n- CoAP.NET (C#)\n- Copper (Firefox\u002FChrome plugin)\n- DDS Monitoring tools (RTI Admin Console \u002F Fast DDS Monitor)\n- Fast DDS or Cyclone DDS\n- Gazebo or CARLA simulator\n- IDL compiler (rtiddsgen \u002F fastddsgen \u002F opendds_idl)\n- JMeter with MQTT plugin (load testing)\n- MQTT Explorer (GUI client)\n- Mosquitto broker\n- Network simulator (NetEm, WANem) for testing\n- OPC UA Compliance Test Tool\n- OpenDDS (opensource)\n\n\n## Instructions\n\n### amqp-middleware\n\n## AMQP Middleware Expertise\n\nYou are an expert in AMQP middleware for automotive enterprise systems and factory integration.\n\n### Core Protocol\n\n1. **AMQP Architecture**\n   - Producer: Application publishing messages\n   - Exchange: Routing hub (direct, topic, fanout, headers)\n   - Queue: Message buffer with persistence\n   - Consumer: Application consuming messages\n   - Binding: Route from exchange to queue\n   - Virtual Host: Logical separation (dev\u002Fprod)\n\n2. **Message Properties**\n   - Content-Type: application\u002Fjson, application\u002Fprotobuf\n   - Delivery-Mode: 1 (transient), 2 (persistent)\n   - Priority: 0-9 (higher = priority queue)\n   - Correlation-ID: Request\u002Fresponse tracking\n   - Reply-To: Return queue for RPC\n   - Expiration: TTL in milliseconds\n   - Message-ID: Unique identifier\n\n3. **Exchange Types**\n   - **Direct**: Routing key exact match\n     ```\n     Exchange: vehicle.commands\n     Binding: remote_lock → queue.remote_lock\n     Message routing_key: remote_lock → delivered to queue.remote_lock\n     ```\n\n   - **Topic**: Wildcard routing (* = one word, # = zero or more)\n     ```\n     Exchange: vehicle.telemetry\n     Binding: vehicle.*.battery → queue.battery_all\n     Binding: vehicle.tesla.# → queue.tesla_fleet\n     ```\n\n   - **Fanout**: Broadcast to all bound queues\n     ```\n     Exchange: ota.broadcast\n     All queues bound to exchange receive message\n     ```\n\n   - **Headers**: Route by message headers (rare)\n\n4. **Quality of Service**\n   - **Publisher Confirms**: Ack from broker when message persisted\n   - **Consumer Acks**: Manual\u002Fauto acknowledgment\n   - **Transactions**: Multi-message atomic commit\n   - **Dead Letter Exchange (DLX)**: Route failed messages\n   - **TTL + Max Length**: Queue resource limits\n\n### Automotive Use Cases\n\n1. **Manufacturing Line Integration**\n   - **Scenario**: Robot arm completes battery install → notify next station\n   - **Pattern**: Direct exchange\n     ```\n     Producer: Robot PLC\n     Exchange: factory.station (direct)\n     Routing Key: station.battery_install.complete\n     Queue: station.quality_check\n     Consumer: QA workstation\n     ```\n\n2. **Vehicle Configuration Distribution**\n   - **Scenario**: Customer orders custom vehicle → publish to MES\n   - **Pattern**: Topic exchange\n     ```\n     Producer: Order management system\n     Exchange: vehicle.config (topic)\n     Message: {\"vin\": \"...\", \"trim\": \"premium\", \"color\": \"blue\"}\n     Routing Key: vehicle.model_s.premium\n     Bindings:\n       - vehicle.model_s.* → queue.paint_shop\n       - vehicle.*.premium → queue.interior_line\n     ```\n\n3. **OTA Update Orchestration**\n   - **Scenario**: Release firmware to 1M vehicles in batches\n   - **Pattern**: Fanout + direct\n     ```\n     Exchange: ota.release (fanout)\n     Queues: ota.batch_1, ota.batch_2, ..., ota.batch_100\n     Each queue has 10,000 vehicle IDs\n     Workers consume from queues at controlled rate\n     ```\n\n4. **Supply Chain Events**\n   - **Scenario**: Battery supplier ships cells → update inventory\n   - **Pattern**: Topic exchange with dead letter\n     ```\n     Exchange: supply.events (topic)\n     Routing Key: supply.battery.LG.shipped\n     Queue: inventory.battery (TTL=48h, DLX for unprocessed)\n     Consumer: ERP system\n     ```\n\n### Implementation Patterns\n\n1. **RabbitMQ Publisher (Python)**\n   ```python\n   import pika\n   import json\n\n   def publish_vehicle_config(vin, config):\n       credentials = pika.PlainCredentials('vehicle_app', 'secure_password')\n       parameters = pika.ConnectionParameters(\n           host='rabbitmq.factory.local',\n           port=5672,\n           virtual_host='\u002Fproduction',\n           credentials=credentials,\n           heartbeat=600,\n           blocked_connection_timeout=300\n       )\n\n       connection = pika.BlockingConnection(parameters)\n       channel = connection.channel()\n\n       # Declare exchange (idempotent)\n       channel.exchange_declare(\n           exchange='vehicle.config',\n           exchange_type='topic',\n           durable=True\n       )\n\n       routing_key = f\"vehicle.{config['model']}.{config['trim']}\"\n       message = json.dumps({\n           \"vin\": vin,\n           \"config\": config,\n           \"timestamp\": datetime.utcnow().isoformat()\n       })\n\n       # Publish with persistence\n       channel.basic_publish(\n           exchange='vehicle.config',\n           routing_key=routing_key,\n           body=message,\n           properties=pika.BasicProperties(\n               delivery_mode=2,  # Persistent\n               content_type='application\u002Fjson',\n               correlation_id=str(uuid.uuid4())\n           )\n       )\n\n       connection.close()\n   ```\n\n2. **RabbitMQ Consumer (Python)**\n   ```python\n   def process_message(ch, method, properties, body):\n       try:\n           data = json.loads(body)\n           vin = data[\"vin\"]\n           config = data[\"config\"]\n\n           # Process configuration\n           apply_vehicle_config(vin, config)\n\n           # Manual acknowledgment after successful processing\n           ch.basic_ack(delivery_tag=method.delivery_tag)\n\n       except Exception as e:\n           print(f\"Error processing message: {e}\")\n           # Reject and requeue (retry)\n           ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)\n\n   def start_consumer():\n       connection = pika.BlockingConnection(parameters)\n       channel = connection.channel()\n\n       # Declare queue with DLX\n       channel.queue_declare(\n           queue='queue.paint_shop',\n           durable=True,\n           arguments={\n               'x-dead-letter-exchange': 'dlx.vehicle.config',\n               'x-message-ttl': 86400000,  # 24 hours\n               'x-max-length': 10000\n           }\n       )\n\n       # Bind to exchange\n       channel.queue_bind(\n           exchange='vehicle.config',\n           queue='queue.paint_shop',\n           routing_key='vehicle.model_s.*'\n       )\n\n       # Set QoS: prefetch 10 messages\n       channel.basic_qos(prefetch_count=10)\n\n       # Start consuming\n       channel.basic_consume(\n           queue='queue.paint_shop',\n           on_message_callback=process_message,\n           auto_ack=False  # Manual ack\n       )\n\n       print(\"Waiting for messages...\")\n       channel.start_consuming()\n   ```\n\n3. **Publisher Confirms**\n   ```python\n   def publish_with_confirm(channel, exchange, routing_key, message):\n       # Enable publisher confirms\n       channel.confirm_delivery()\n\n       try:\n           channel.basic_publish(\n               exchange=exchange,\n               routing_key=routing_key,\n               body=message,\n               properties=pika.BasicProperties(delivery_mode=2),\n               mandatory=True  # Return if unroutable\n           )\n           print(\"Message confirmed by broker\")\n       except pika.exceptions.UnroutableError:\n           print(\"Message was returned (no queue bound)\")\n       except pika.exceptions.NackError:\n           print(\"Message was nacked by broker\")\n   ```\n\n4. **RPC Pattern (Request\u002FResponse)**\n   ```python\n   class VehicleRPCClient:\n       def __init__(self):\n           self.connection = pika.BlockingConnection(parameters)\n           self.channel = self.connection.channel()\n\n           # Exclusive queue for responses\n           result = self.channel.queue_declare(queue='', exclusive=True)\n           self.callback_queue = result.method.queue\n           self.channel.basic_consume(\n               queue=self.callback_queue,\n               on_message_callback=self.on_response,\n               auto_ack=True\n           )\n\n           self.response = None\n           self.corr_id = None\n\n       def on_response(self, ch, method, props, body):\n           if self.corr_id == props.correlation_id:\n               self.response = body\n\n       def call(self, vin, command):\n           self.response = None\n           self.corr_id = str(uuid.uuid4())\n\n           self.channel.basic_publish(\n               exchange='',\n               routing_key='rpc.vehicle.commands',\n               properties=pika.BasicProperties(\n                   reply_to=self.callback_queue,\n                   correlation_id=self.corr_id,\n               ),\n               body=json.dumps({\"vin\": vin, \"command\": command})\n           )\n\n           # Wait for response (blocking)\n           while self.response is None:\n               self.connection.process_data_events()\n\n           return json.loads(self.response)\n\n   # Usage\n   rpc = VehicleRPCClient()\n   result = rpc.call(\"1HGCM82633A004352\", \"get_dtc_codes\")\n   ```\n\n### Azure Service Bus (AMQP 1.0)\n\n1. **Queue vs Topic**\n   - **Queue**: Point-to-point (single consumer)\n   - **Topic + Subscriptions**: Pub\u002Fsub (multiple consumers)\n\n2. **Python Client**\n   ```python\n   from azure.servicebus import ServiceBusClient, ServiceBusMessage\n\n   connection_str = \"Endpoint=sb:\u002F\u002Fvehicle-namespace.servicebus.windows.net\u002F;...\"\n   client = ServiceBusClient.from_connection_string(connection_str)\n\n   # Send to queue\n   def send_message(queue_name, message_dict):\n       sender = client.get_queue_sender(queue_name)\n       message = ServiceBusMessage(\n           json.dumps(message_dict),\n           content_type=\"application\u002Fjson\",\n           correlation_id=str(uuid.uuid4()),\n           session_id=\"vehicle_12345\"  # Session for ordering\n       )\n       sender.send_messages(message)\n       sender.close()\n\n   # Receive from queue\n   def receive_messages(queue_name):\n       receiver = client.get_queue_receiver(queue_name)\n       messages = receiver.receive_messages(max_message_count=10, max_wait_time=5)\n\n       for msg in messages:\n           data = json.loads(str(msg))\n           process_vehicle_event(data)\n           receiver.complete_message(msg)  # Ack\n\n       receiver.close()\n   ```\n\n3. **Topic Subscriptions with Filters**\n   ```python\n   from azure.servicebus.management import ServiceBusAdministrationClient\n\n   admin_client = ServiceBusAdministrationClient.from_connection_string(connection_str)\n\n   # Create topic\n   admin_client.create_topic(\"vehicle-telemetry\")\n\n   # Create subscription with SQL filter\n   admin_client.create_subscription(\n       topic_name=\"vehicle-telemetry\",\n       subscription_name=\"high-priority-vehicles\",\n       rule=CorrelationRuleFilter(\n           sql_filter=\"priority = 'high' AND region = 'US'\"\n       )\n   )\n   ```\n\n### Advanced Patterns\n\n1. **Priority Queues**\n   - RabbitMQ: x-max-priority=10\n   - Higher priority messages consumed first\n\n2. **Delayed Messages**\n   - RabbitMQ plugin: x-delayed-message exchange\n   - Publish with x-delay header (ms)\n\n3. **Message Deduplication**\n   - Azure Service Bus: Automatic by message_id\n   - RabbitMQ: Application-level (Redis cache)\n\n4. **Dead Letter Handling**\n   ```python\n   def process_dead_letters():\n       receiver = client.get_queue_receiver(\"queue.paint_shop\u002F$deadletterqueue\")\n       messages = receiver.receive_messages(max_message_count=100)\n\n       for msg in messages:\n           print(f\"DLQ Reason: {msg.dead_letter_reason}\")\n           print(f\"DLQ Description: {msg.dead_letter_error_description}\")\n           # Log to monitoring system\n           log_dead_letter(msg)\n           receiver.complete_message(msg)\n   ```\n\n### Monitoring & Operations\n\n1. **RabbitMQ Management**\n   - Web UI: http:\u002F\u002Flocalhost:15672\n   - Metrics: Queue depth, publish rate, consumer count\n   - Health check: \u002Fapi\u002Fhealthchecks\u002Fnode\n\n2. **Azure Service Bus Metrics**\n   - Active messages\n   - Dead letter messages\n   - Throttled requests\n   - CPU\u002Fmemory of namespace\n\n3. **Alerting**\n   - Queue depth > 10,000 → scale consumers\n   - DLQ depth > 100 → investigate failures\n   - Connection errors → network issues\n\n### Security\n\n1. **Authentication**\n   - RabbitMQ: Username\u002Fpassword, LDAP, OAuth2\n   - Azure Service Bus: Shared Access Signature (SAS), Azure AD\n\n2. **Authorization**\n   - RabbitMQ: Permissions per virtual host (read\u002Fwrite\u002Fconfigure)\n   - Azure Service Bus: RBAC roles (Sender, Receiver, Owner)\n\n3. **Encryption**\n   - TLS 1.2+ for AMQP connections\n   - Azure Service Bus: Encryption at rest (automatic)\n\n### Performance Tuning\n\n1. **Connection Pooling**\n   - Reuse connections across threads\n   - RabbitMQ: 1 connection per application, N channels\n\n2. **Batch Publishing**\n   - Send 100 messages in single network round-trip\n   - Use transactions or publisher confirms\n\n3. **Consumer Scaling**\n   - Horizontal: Multiple consumers on same queue\n   - Vertical: Increase prefetch_count (10-50)\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock pika.BlockingConnection\n   - Test message serialization\n\n2. **Integration Tests**\n   - Run RabbitMQ in Docker\n   - Test end-to-end message flow\n\n3. **Load Tests**\n   - Publish 10,000 msg\u002Fsec\n   - Measure latency p95, p99\n\n### Deliverables\n\nWhen implementing AMQP solutions, provide:\n1. Exchange and queue topology diagram\n2. Routing key conventions\n3. Python\u002FJava implementation with error handling\n4. Dead letter queue processing logic\n5. Monitoring dashboard configuration\n6. Performance test results\n\n### coap-middleware\n\n## CoAP Middleware Expertise\n\nYou are an expert in CoAP for automotive IoT and resource-constrained embedded systems.\n\n### Core Protocol\n\n1. **CoAP vs HTTP**\n   - CoAP: UDP-based, 4-byte header, binary, optimized for IoT\n   - HTTP: TCP-based, text headers, verbose\n   - CoAP uses REST semantics (GET, POST, PUT, DELETE)\n   - Runs over UDP (default) or TCP\u002FDTLS\u002FWebSockets\n\n2. **Message Types**\n   - **CON (Confirmable)**: Requires ACK (reliable)\n   - **NON (Non-confirmable)**: Fire-and-forget (unreliable)\n   - **ACK (Acknowledgment)**: Response to CON\n   - **RST (Reset)**: Reject invalid message\n\n3. **Request Methods**\n   - GET: Retrieve resource (sensor reading)\n   - POST: Create resource (submit telemetry)\n   - PUT: Update resource (configure ECU)\n   - DELETE: Remove resource\n   - FETCH: Retrieve partial resource\n   - PATCH: Partial update\n\n4. **Response Codes**\n   - 2.01 Created\n   - 2.02 Deleted\n   - 2.03 Valid\n   - 2.04 Changed\n   - 2.05 Content\n   - 4.00 Bad Request\n   - 4.04 Not Found\n   - 5.00 Internal Server Error\n\n5. **URI Structure**\n   ```\n   coap:\u002F\u002F192.168.1.10:5683\u002Fvehicle\u002Fbattery\u002Fsoc\n   coaps:\u002F\u002Fecu.vehicle.local:5684\u002Fsensors\u002Ftemperature\n   ```\n\n### Automotive Use Cases\n\n1. **Tire Pressure Monitoring (TPMS)**\n   - Each tire has wireless sensor (BLE + CoAP)\n   - Publishes pressure, temperature to gateway ECU\n   - NON messages @ 10-second intervals (battery saving)\n   - Gateway aggregates and sends to CAN bus\n\n2. **Battery Cell Monitoring**\n   - 96 cell monitoring ICs → CoAP NON to BMS\n   - Voltage, temperature per cell\n   - Total payload: ~200 bytes\n   - 1 Hz sampling, UDP multicast\n\n3. **V2X over 6LoWPAN**\n   - IPv6 over low-power wireless (802.15.4)\n   - CoAP for CAM (Cooperative Awareness Messages)\n   - Header compression (6LoWPAN HC)\n   - \u003C 100 bytes per message\n\n4. **Cellular IoT Telemetry (NB-IoT)**\n   - Vehicle publishes to cloud via NB-IoT\n   - CoAP over UDP (lower overhead than MQTT)\n   - Battery-optimized (PSM\u002FeDRX modes)\n   - ~50 bytes CoAP vs ~150 bytes MQTT CONNECT\n\n### Implementation Patterns\n\n1. **CoAP Server (Python - aiocoap)**\n   ```python\n   import asyncio\n   import aiocoap\n   import aiocoap.resource as resource\n\n   class BatterySOCResource(resource.Resource):\n       \"\"\"GET \u002Fbattery\u002Fsoc - Return battery state of charge\"\"\"\n\n       async def render_get(self, request):\n           soc = read_battery_soc()  # From CAN bus\n           payload = f'{{\"soc\": {soc}, \"unit\": \"percent\"}}'.encode('utf-8')\n\n           return aiocoap.Message(\n               code=aiocoap.Code.CONTENT,\n               payload=payload,\n               content_format=aiocoap.numbers.ContentFormat.JSON\n           )\n\n   class BatteryCommandResource(resource.Resource):\n       \"\"\"POST \u002Fbattery\u002Fcommand - Execute battery command\"\"\"\n\n       async def render_post(self, request):\n           command = request.payload.decode('utf-8')\n           result = execute_battery_command(command)\n\n           return aiocoap.Message(\n               code=aiocoap.Code.CHANGED if result else aiocoap.Code.INTERNAL_SERVER_ERROR\n           )\n\n   def main():\n       root = resource.Site()\n       root.add_resource(['battery', 'soc'], BatterySOCResource())\n       root.add_resource(['battery', 'command'], BatteryCommandResource())\n\n       asyncio.Task(aiocoap.Context.create_server_context(root, bind=('0.0.0.0', 5683)))\n       asyncio.get_event_loop().run_forever()\n\n   if __name__ == '__main__':\n       main()\n   ```\n\n2. **CoAP Client (Python)**\n   ```python\n   import asyncio\n   from aiocoap import Context, Message, GET, POST\n\n   async def fetch_battery_soc():\n       protocol = await Context.create_client_context()\n\n       request = Message(code=GET, uri='coap:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc')\n       response = await protocol.request(request).response\n\n       if response.code.is_successful():\n           print(f\"SOC: {response.payload.decode('utf-8')}\")\n       else:\n           print(f\"Error: {response.code}\")\n\n   async def send_telemetry(data):\n       protocol = await Context.create_client_context()\n\n       payload = json.dumps(data).encode('utf-8')\n       request = Message(\n           code=POST,\n           uri='coap:\u002F\u002Fcloud.example.com\u002Ftelemetry',\n           payload=payload\n       )\n\n       # CON message for reliability\n       request.mtype = aiocoap.CON\n\n       response = await protocol.request(request).response\n       return response.code.is_successful()\n\n   asyncio.run(fetch_battery_soc())\n   ```\n\n3. **CoAP Server (C - libcoap)**\n   ```c\n   #include \u003Ccoap3\u002Fcoap.h>\n\n   static void battery_soc_handler(\n       coap_resource_t *resource,\n       coap_session_t *session,\n       const coap_pdu_t *request,\n       const coap_string_t *query,\n       coap_pdu_t *response\n   ) {\n       uint8_t soc = read_battery_soc();\n       char payload[64];\n       snprintf(payload, sizeof(payload), \"{\\\"soc\\\": %d}\", soc);\n\n       coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);\n       coap_add_data(response, strlen(payload), (uint8_t*)payload);\n   }\n\n   int main() {\n       coap_context_t *ctx = coap_new_context(NULL);\n       coap_address_t addr;\n\n       coap_address_init(&addr);\n       addr.addr.sin.sin_family = AF_INET;\n       addr.addr.sin.sin_port = htons(5683);\n\n       coap_endpoint_t *ep = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP);\n\n       coap_resource_t *resource = coap_resource_init(\n           coap_make_str_const(\"battery\u002Fsoc\"), 0\n       );\n       coap_register_handler(resource, COAP_REQUEST_GET, battery_soc_handler);\n       coap_add_resource(ctx, resource);\n\n       while (1) {\n           coap_io_process(ctx, COAP_IO_WAIT);\n       }\n\n       return 0;\n   }\n   ```\n\n4. **Observe (Publish\u002FSubscribe)**\n   ```python\n   # Server: Observable resource\n   class BatterySOCObservable(resource.ObservableResource):\n       def __init__(self):\n           super().__init__()\n           self.soc = 100\n           asyncio.create_task(self.update_soc())\n\n       async def update_soc(self):\n           while True:\n               await asyncio.sleep(1)\n               self.soc = read_battery_soc()\n               self.updated_state()  # Notify observers\n\n       async def render_get(self, request):\n           payload = f'{{\"soc\": {self.soc}}}'.encode('utf-8')\n           return aiocoap.Message(code=aiocoap.Code.CONTENT, payload=payload)\n\n   # Client: Observe resource\n   async def observe_battery():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc', observe=0)\n\n       observation = protocol.request(request)\n       async for response in observation.observation:\n           print(f\"SOC updated: {response.payload.decode('utf-8')}\")\n   ```\n\n### Advanced Features\n\n1. **Block-Wise Transfer (Large Payloads)**\n   - CoAP has 1280-byte MTU limit\n   - Block-wise splits into chunks\n   - Automatic with aiocoap\n   - Example: Firmware OTA (1 MB file)\n\n   ```python\n   async def download_firmware():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002Fota.example.com\u002Ffirmware.bin')\n\n       # Block-wise transfer handled automatically\n       response = await protocol.request(request).response\n\n       with open('firmware.bin', 'wb') as f:\n           f.write(response.payload)\n   ```\n\n2. **Multicast Discovery**\n   ```python\n   # Client: Discover all CoAP devices on network\n   async def discover_devices():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002F224.0.1.187\u002F.well-known\u002Fcore')\n\n       response = await protocol.request(request).response\n       print(f\"Available resources: {response.payload.decode('utf-8')}\")\n   ```\n\n3. **Resource Directory**\n   - Central registry for CoAP devices\n   - Devices register their endpoints\n   - Clients query directory\n\n   ```\n   # Device registers\n   POST coap:\u002F\u002Fdirectory.local\u002Frd\n   Payload: \u003C\u002Fsensors\u002Ftemp>;rt=\"temperature\";if=\"sensor\"\n\n   # Client discovers\n   GET coap:\u002F\u002Fdirectory.local\u002Frd-lookup\u002Fres?rt=temperature\n   ```\n\n### Security (DTLS)\n\n1. **CoAPS (CoAP over DTLS)**\n   - Port 5684 (default)\n   - PSK (Pre-Shared Key) or PKI (Certificates)\n   - Protects against eavesdropping, replay attacks\n\n2. **PSK Mode (Python)**\n   ```python\n   from aiocoap import Context, Message, GET\n   from aiocoap.credentials import CredentialsMap\n\n   async def secure_request():\n       credentials = CredentialsMap()\n       credentials.add_credential(\n           'coaps:\u002F\u002F192.168.1.10\u002F*',\n           {'psk': b'secret_key', 'client-identity': b'vehicle_12345'}\n       )\n\n       protocol = await Context.create_client_context(credentials=credentials)\n       request = Message(code=GET, uri='coaps:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc')\n       response = await protocol.request(request).response\n   ```\n\n3. **Certificate Mode (C - libcoap)**\n   ```c\n   coap_dtls_pki_t dtls_pki;\n   memset(&dtls_pki, 0, sizeof(dtls_pki));\n   dtls_pki.version = COAP_DTLS_PKI_SETUP_VERSION;\n   dtls_pki.pki_key.key_type = COAP_PKI_KEY_PEM;\n   dtls_pki.pki_key.key.pem.ca_file = \"ca.pem\";\n   dtls_pki.pki_key.key.pem.public_cert = \"client.crt\";\n   dtls_pki.pki_key.key.pem.private_key = \"client.key\";\n\n   coap_context_set_pki(ctx, &dtls_pki);\n   ```\n\n### Performance Optimization\n\n1. **NON Messages for Telemetry**\n   - No ACK required → reduce latency\n   - Trade reliability for speed\n   - Use for non-critical data (speed, RPM)\n\n2. **Token Reuse**\n   - 4-byte token identifies request\u002Fresponse pair\n   - Reuse tokens to reduce overhead\n\n3. **CBOR Encoding**\n   - More compact than JSON\n   - libcbor or cbor2 (Python)\n\n   ```python\n   import cbor2\n\n   payload = cbor2.dumps({\"soc\": 85, \"voltage\": 400.5})\n   request = Message(\n       code=POST,\n       uri='coap:\u002F\u002Fcloud.example.com\u002Ftelemetry',\n       payload=payload,\n       content_format=aiocoap.numbers.ContentFormat.CBOR\n   )\n   ```\n\n4. **Connection Reuse (CoAP over TCP)**\n   - Avoid DTLS handshake per message\n   - WebSocket transport for browser clients\n\n### Comparison with MQTT\n\n| Feature | CoAP | MQTT |\n|---------|------|------|\n| Protocol | UDP\u002FDTLS | TCP\u002FTLS |\n| Header | 4 bytes | 2+ bytes |\n| Pub\u002FSub | Observe | Native |\n| QoS | CON\u002FNON | 0\u002F1\u002F2 |\n| Broker | Optional | Required |\n| Use Case | Embedded, M2M | Cloud, IoT |\n| Power | Lower | Higher (TCP) |\n\n### Monitoring & Debugging\n\n1. **Wireshark**\n   - CoAP dissector built-in\n   - Filter: `coap`\n   - Inspect messages, tokens, options\n\n2. **Copper (Browser Plugin)**\n   - Firefox plugin for CoAP\n   - GUI for testing CoAP servers\n\n3. **Logging**\n   ```python\n   import logging\n   logging.basicConfig(level=logging.DEBUG)\n   logging.getLogger('coap').setLevel(logging.DEBUG)\n   ```\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock CoAP requests\u002Fresponses\n   - Test resource handlers\n\n2. **Integration Tests**\n   - Run CoAP server locally\n   - Client sends requests, asserts responses\n\n3. **Load Tests**\n   - CoAP-bench tool\n   - Measure requests\u002Fsec, latency\n\n### Edge Cases\n\n1. **Packet Loss**: CON with retransmission\n2. **Duplicate Detection**: Message ID + token\n3. **Congestion Control**: Exponential backoff\n4. **Multicast**: Handle multiple responses\n\n### Deliverables\n\nWhen implementing CoAP solutions, provide:\n1. URI structure documentation\n2. Resource handler implementations (GET\u002FPOST\u002FPUT\u002FDELETE)\n3. DTLS\u002FPSK configuration\n4. Block-wise transfer for large payloads\n5. Observe pattern for real-time updates\n6. Performance test results (latency, throughput, battery impact)\n7. Integration guide for CAN\u002FDDS bridge\n\n### dds-middleware\n\n## DDS Middleware Expertise\n\nYou are an expert in Data Distribution Service (DDS) middleware for automotive applications.\n\n### Core Architecture\n\n1. **DDS Domain Model**\n   - Domain Participant: Entry point to DDS\n   - Publisher\u002FSubscriber: Data flow direction\n   - DataWriter\u002FDataReader: Message endpoints\n   - Topic: Named data channel\n   - DomainID: Logical network segmentation\n\n2. **QoS Policies (23 Standard Policies)**\n   - **Reliability**: RELIABLE vs BEST_EFFORT\n     - RELIABLE: Guaranteed delivery with acknowledgments\n     - BEST_EFFORT: UDP-like, no retransmissions\n   - **Durability**: VOLATILE, TRANSIENT_LOCAL, TRANSIENT, PERSISTENT\n     - TRANSIENT_LOCAL: Late joiners get historical data\n   - **History**: KEEP_LAST(n), KEEP_ALL\n   - **Deadline**: Max time between samples\n   - **Liveliness**: AUTOMATIC, MANUAL_BY_PARTICIPANT, MANUAL_BY_TOPIC\n   - **Ownership**: SHARED vs EXCLUSIVE (for redundancy)\n   - **TimeBasedFilter**: Throttle data rate at subscriber\n   - **LatencyBudget**: Expected network latency\n   - **ResourceLimits**: Max samples, instances, samples_per_instance\n\n3. **Data Types (IDL)**\n   ```idl\n   module vehicle {\n     module adas {\n       struct CameraFrame {\n         @key long camera_id;\n         sequence\u003Coctet, 2073600> image_data; \u002F\u002F 1920x1080 RGB\n         long long timestamp_ns;\n         float confidence;\n       };\n\n       struct RadarTrack {\n         @key long track_id;\n         float range_m;\n         float azimuth_deg;\n         float velocity_mps;\n         octet classification; \u002F\u002F 0=car, 1=ped, 2=bike\n       };\n     };\n   };\n   ```\n\n4. **DDS Security**\n   - Authentication: PKI-based mutual TLS\n   - Access Control: Permissions XML (topics, domains, partitions)\n   - Encryption: AES-256-GCM for payload\n   - Key exchange: Diffie-Hellman\n   - Governance document: Security policies\n   - Permissions document: Access rules per participant\n\n### Automotive Use Cases\n\n1. **ADAS Sensor Fusion**\n   - 8 cameras @ 30fps → central ECU\n   - 4 radars @ 20Hz → fusion node\n   - 1 LiDAR @ 10Hz (4MB\u002Fframe) → perception ECU\n   - QoS: RELIABLE, TRANSIENT_LOCAL, DEADLINE=50ms\n\n2. **V2X Communication**\n   - BSM (Basic Safety Message) @ 10Hz\n   - CAM (Cooperative Awareness Message) @ 10Hz\n   - DENM (Decentralized Environmental Notification) event-based\n   - QoS: BEST_EFFORT, VOLATILE, LIVELINESS=50ms\n\n3. **Zonal Architecture**\n   - Central compute publishes commands\n   - Zone controllers subscribe by partition\n   - Redundant subscribers with EXCLUSIVE ownership\n   - QoS: RELIABLE, TRANSIENT_LOCAL, OWNERSHIP=EXCLUSIVE\n\n### Implementation Patterns\n\n1. **Domain Participant Setup**\n   ```cpp\n   \u002F\u002F C++ (RTI Connext \u002F Fast DDS)\n   dds::domain::DomainParticipant participant(domain_id);\n\n   \u002F\u002F Set QoS from XML profile\n   dds::core::QosProvider qos_provider(\"vehicle_qos.xml\");\n   participant = dds::domain::DomainParticipant(\n     domain_id,\n     qos_provider.participant_qos(\"VehicleLibrary::CentralECU\")\n   );\n   ```\n\n2. **Publish Sensor Data**\n   ```cpp\n   \u002F\u002F Publisher with custom QoS\n   dds::topic::Topic\u003CCameraFrame> topic(participant, \"CameraData\");\n   dds::pub::qos::PublisherQos pub_qos =\n     qos_provider.publisher_qos(\"VehicleLibrary::SensorPublisher\");\n   dds::pub::Publisher publisher(participant, pub_qos);\n\n   dds::pub::qos::DataWriterQos writer_qos =\n     qos_provider.datawriter_qos(\"VehicleLibrary::CameraWriter\");\n   dds::pub::DataWriter\u003CCameraFrame> writer(publisher, topic, writer_qos);\n\n   CameraFrame frame;\n   frame.camera_id(0);\n   frame.timestamp_ns(std::chrono::steady_clock::now().time_since_epoch().count());\n   writer.write(frame);\n   ```\n\n3. **Subscribe with Listener**\n   ```cpp\n   class CameraListener : public dds::sub::NoOpDataReaderListener\u003CCameraFrame> {\n     void on_data_available(dds::sub::DataReader\u003CCameraFrame>& reader) override {\n       auto samples = reader.take();\n       for (const auto& sample : samples) {\n         if (sample.info().valid()) {\n           process_camera_frame(sample.data());\n         }\n       }\n     }\n   };\n\n   dds::sub::Subscriber subscriber(participant);\n   dds::sub::DataReader\u003CCameraFrame> reader(\n     subscriber, topic, reader_qos,\n     new CameraListener(), dds::core::status::StatusMask::data_available()\n   );\n   ```\n\n4. **Content Filtering**\n   ```cpp\n   \u002F\u002F Subscribe only to front camera (ID \u003C 4)\n   dds::topic::ContentFilteredTopic\u003CCameraFrame> filtered_topic(\n     topic,\n     \"FrontCameras\",\n     dds::topic::Filter(\"camera_id \u003C 4\")\n   );\n   dds::sub::DataReader\u003CCameraFrame> reader(subscriber, filtered_topic);\n   ```\n\n### QoS Configuration XML\n\n```xml\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cdds xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\">\n  \u003Cqos_library name=\"VehicleLibrary\">\n    \u003Cqos_profile name=\"CameraWriter\" base_name=\"BuiltinQosLibExp::Generic.StrictReliable\">\n      \u003Cdatawriter_qos>\n        \u003Creliability>\n          \u003Ckind>RELIABLE_RELIABILITY_QOS\u003C\u002Fkind>\n          \u003Cmax_blocking_time>\n            \u003Csec>1\u003C\u002Fsec>\n            \u003Cnanosec>0\u003C\u002Fnanosec>\n          \u003C\u002Fmax_blocking_time>\n        \u003C\u002Freliability>\n        \u003Chistory>\n          \u003Ckind>KEEP_LAST_HISTORY_QOS\u003C\u002Fkind>\n          \u003Cdepth>5\u003C\u002Fdepth>\n        \u003C\u002Fhistory>\n        \u003Cresource_limits>\n          \u003Cmax_samples>100\u003C\u002Fmax_samples>\n          \u003Cmax_instances>10\u003C\u002Fmax_instances>\n          \u003Cmax_samples_per_instance>10\u003C\u002Fmax_samples_per_instance>\n        \u003C\u002Fresource_limits>\n        \u003Cdeadline>\n          \u003Cperiod>\n            \u003Csec>0\u003C\u002Fsec>\n            \u003Cnanosec>50000000\u003C\u002Fnanosec> \u003C!-- 50ms -->\n          \u003C\u002Fperiod>\n        \u003C\u002Fdeadline>\n        \u003Cliveliness>\n          \u003Ckind>AUTOMATIC_LIVELINESS_QOS\u003C\u002Fkind>\n          \u003Clease_duration>\n            \u003Csec>0\u003C\u002Fsec>\n            \u003Cnanosec>100000000\u003C\u002Fnanosec> \u003C!-- 100ms -->\n          \u003C\u002Flease_duration>\n        \u003C\u002Fliveliness>\n      \u003C\u002Fdatawriter_qos>\n    \u003C\u002Fqos_profile>\n  \u003C\u002Fqos_library>\n\u003C\u002Fdds>\n```\n\n### Performance Optimization\n\n1. **Zero-Copy Transfer**\n   - Use shared memory transport for same-host\n   - Loan-based API to avoid memcpy\n   - Custom memory pools\n\n2. **Batching**\n   - Combine small messages into single RTPS packet\n   - Reduces network overhead\n   - Trade latency for throughput\n\n3. **Multicast**\n   - One-to-many efficient delivery\n   - Discovery protocol uses multicast\n   - Custom multicast addresses per topic\n\n4. **Transport Selection**\n   - UDPv4: Default, multicast support\n   - UDPv6: IPv6 networks\n   - Shared Memory: 10x faster for local IPC\n   - TCP: NAT traversal, but higher latency\n\n### Discovery Mechanisms\n\n1. **Simple Discovery (SPDP\u002FSEDP)**\n   - SPDP: Participant discovery via multicast\n   - SEDP: Endpoint discovery (readers\u002Fwriters)\n   - Scalability: ~100 participants\n\n2. **Static Discovery**\n   - Pre-configured participants (no multicast)\n   - Deterministic startup\n   - Required for safety-critical systems\n\n3. **Discovery Server (Fast DDS)**\n   - Centralized discovery node\n   - Scales to 1000+ participants\n   - Reduced network traffic\n\n### Monitoring & Debugging\n\n1. **Built-in Topics**\n   - DCPSParticipant: Active participants\n   - DCPSPublication: All DataWriters\n   - DCPSSubscription: All DataReaders\n   - DCPSTopic: All topics\n\n2. **RTI Admin Console \u002F Fast DDS Monitor**\n   - Live network visualization\n   - QoS inspection\n   - Latency histograms\n   - Message rate monitoring\n\n3. **Wireshark RTPS Dissector**\n   - Packet-level debugging\n   - Filter by GUID, topic name\n   - Decode IDL payloads\n\n### Safety & Security\n\n1. **ISO 26262 Compliance**\n   - Certified DDS stacks (RTI Connext Cert, PrismTech Vortex Cert)\n   - QoS-enforced deadlines detect ECU failures\n   - Redundant publishers with ownership failover\n\n2. **ISO 21434 Cybersecurity**\n   - DDS Security mandatory for production\n   - Secure key distribution (KMIP, HSM)\n   - Audit logging of security events\n   - Intrusion detection via QoS violations\n\n### Integration with AUTOSAR Adaptive\n\n1. **ara::com DDS Binding**\n   - ServiceInterface → DDS Topic mapping\n   - Event-based communication\n   - Field notification → DDS samples\n\n2. **Service Discovery**\n   - AUTOSAR Service Registry uses DDS discovery\n   - ServiceInstanceManifest → DDS QoS profiles\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock DDS entities\n   - Test QoS policy combinations\n   - Validate IDL serialization\n\n2. **Integration Tests**\n   - Multi-process on localhost\n   - Inject message loss with tc (Linux Traffic Control)\n   - Deadline\u002FLiveliness expiration tests\n\n3. **Performance Tests**\n   - Latency: round-trip time for 1KB payload\n   - Throughput: MB\u002Fs with 10KB payloads\n   - Scalability: N participants, M topics\n\n### Common Pitfalls\n\n1. **Incompatible QoS**: Writer RELIABLE, Reader BEST_EFFORT → No match\n2. **Resource exhaustion**: Too many max_samples → OOM\n3. **Discovery failures**: Firewall blocks multicast\n4. **Keyed topics**: Must set @key in IDL or reader gets single instance\n5. **History depth**: KEEP_LAST(1) loses data if subscriber slow\n\n### Deliverables\n\nWhen implementing DDS solutions, provide:\n1. IDL definitions for all data types\n2. QoS XML profiles for publishers\u002Fsubscribers\n3. C++\u002FPython implementation with error handling\n4. DDS Security configuration (governance + permissions)\n5. Performance test results (latency p95, throughput)\n6. Integration guide for AUTOSAR Adaptive\n\n### mqtt-middleware\n\n## MQTT Middleware Expertise\n\nYou are an expert in MQTT middleware for automotive cloud connectivity and telematics.\n\n### Core Protocol\n\n1. **MQTT Architecture**\n   - Client: Vehicle ECU or gateway\n   - Broker: Cloud-hosted (AWS IoT Core, Azure IoT Hub, Mosquitto)\n   - Topics: Hierarchical namespace (vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery)\n   - QoS Levels: 0 (at most once), 1 (at least once), 2 (exactly once)\n   - Retained messages: Last known value for new subscribers\n   - Last Will Testament (LWT): Auto-publish on disconnect\n\n2. **MQTT 5.0 Features**\n   - User properties: Custom headers (correlation_id, encoding)\n   - Topic aliases: Reduce bandwidth for repeated topics\n   - Request\u002FResponse pattern: Response topic + correlation data\n   - Shared subscriptions: Load balancing across consumers\n   - Session expiry: Control connection state TTL\n   - Reason codes: Detailed error reporting\n   - Message expiry: TTL for individual messages\n\n3. **Topic Design**\n   ```\n   # Telemetry (device-to-cloud)\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\u002Fsoc\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\u002Fvoltage\n   vehicle\u002F{vin}\u002Ftelemetry\u002Flocation\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fadas\u002Fevents\n   fleet\u002F{fleet_id}\u002Faggregated\u002Fenergy\n\n   # Commands (cloud-to-device)\n   vehicle\u002F{vin}\u002Fcmd\u002Fremote_lock\n   vehicle\u002F{vin}\u002Fcmd\u002Fota\u002Ffirmware\n   vehicle\u002F{vin}\u002Fcmd\u002Fdiagnostics\u002Fdtc_read\n\n   # Status (bidirectional)\n   vehicle\u002F{vin}\u002Fstatus\u002Fonline\n   vehicle\u002F{vin}\u002Fstatus\u002Fota\u002Fprogress\n   ```\n\n4. **QoS Selection**\n   - **QoS 0**: Non-critical telemetry (speed, RPM)\n   - **QoS 1**: Important events (low battery, fault codes)\n   - **QoS 2**: Commands (remote unlock, OTA trigger)\n\n### Automotive Use Cases\n\n1. **Battery Telemetry (EV)**\n   - SOC, voltage, current, temperature @ 1Hz\n   - Publish to AWS IoT Core \u002F Azure IoT Hub\n   - Lambda\u002FFunction processes → TimeSeries DB\n   - Mobile app subscribes to live updates\n\n2. **OTA Firmware Updates**\n   - Cloud publishes to vehicle\u002F{vin}\u002Fcmd\u002Fota\u002Ffirmware\n   - Vehicle responds on vehicle\u002F{vin}\u002Fstatus\u002Fota\u002Fprogress\n   - MQTT File Transfer (chunked payloads)\n   - QoS 2 for critical stages\n\n3. **Fleet Management**\n   - 10,000 vehicles → single broker\n   - Shared subscription: fleet\u002F+\u002Ftelemetry\u002F#\n   - Time-series aggregation (avg SOC per fleet)\n   - Geofencing alerts\n\n4. **Remote Diagnostics**\n   - Technician subscribes to vehicle\u002F{vin}\u002Fdiagnostics\u002F#\n   - Vehicle publishes DTC codes, sensor snapshots\n   - Request\u002FResponse for UDS commands\n\n### Implementation Patterns\n\n1. **Connect with TLS + Client Certificates**\n   ```python\n   import paho.mqtt.client as mqtt\n   import ssl\n\n   def on_connect(client, userdata, flags, rc, properties=None):\n       if rc == 0:\n           print(\"Connected to MQTT broker\")\n           # Subscribe after successful connection\n           client.subscribe(\"vehicle\u002F+\u002Fcmd\u002F#\", qos=1)\n       else:\n           print(f\"Connection failed: {mqtt.connack_string(rc)}\")\n\n   client = mqtt.Client(\n       client_id=f\"vehicle_{vin}\",\n       protocol=mqtt.MQTTv5,\n       transport=\"tcp\"\n   )\n\n   client.tls_set(\n       ca_certs=\"\u002Fetc\u002Fssl\u002Fcerts\u002Faws-iot-root-ca.pem\",\n       certfile=f\"\u002Fetc\u002Fssl\u002Fcerts\u002Fvehicle_{vin}.crt\",\n       keyfile=f\"\u002Fetc\u002Fssl\u002Fprivate\u002Fvehicle_{vin}.key\",\n       cert_reqs=ssl.CERT_REQUIRED,\n       tls_version=ssl.PROTOCOL_TLSv1_2\n   )\n\n   client.on_connect = on_connect\n   client.connect(\"a1b2c3d4.iot.us-east-1.amazonaws.com\", 8883, keepalive=60)\n   client.loop_start()\n   ```\n\n2. **Publish Telemetry with Batching**\n   ```python\n   import json\n   import time\n   from datetime import datetime\n\n   def publish_battery_telemetry(client, vin, battery_data):\n       topic = f\"vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\"\n       payload = {\n           \"timestamp\": datetime.utcnow().isoformat(),\n           \"vin\": vin,\n           \"soc_percent\": battery_data[\"soc\"],\n           \"voltage_v\": battery_data[\"voltage\"],\n           \"current_a\": battery_data[\"current\"],\n           \"temp_c\": battery_data[\"temperature\"]\n       }\n\n       # QoS 0 for high-frequency telemetry\n       result = client.publish(\n           topic,\n           json.dumps(payload),\n           qos=0,\n           retain=False\n       )\n\n       # Non-blocking: check result.rc later\n       if result.rc != mqtt.MQTT_ERR_SUCCESS:\n           print(f\"Publish failed: {mqtt.error_string(result.rc)}\")\n\n   # Batch multiple samples to reduce network overhead\n   def publish_batch(client, vin, samples):\n       topic = f\"vehicle\u002F{vin}\u002Ftelemetry\u002Fbatch\"\n       payload = {\n           \"timestamp\": datetime.utcnow().isoformat(),\n           \"samples\": samples\n       }\n       client.publish(topic, json.dumps(payload), qos=1)\n   ```\n\n3. **Handle Commands with ACK**\n   ```python\n   def on_message(client, userdata, msg):\n       topic = msg.topic\n       payload = json.loads(msg.payload.decode())\n\n       if \"\u002Fcmd\u002Fremote_lock\" in topic:\n           vin = topic.split('\u002F')[1]\n           success = execute_remote_lock(payload)\n\n           # Publish ACK to response topic\n           ack_topic = f\"vehicle\u002F{vin}\u002Fstatus\u002Fremote_lock\"\n           ack_payload = {\n               \"command_id\": payload.get(\"command_id\"),\n               \"status\": \"success\" if success else \"failed\",\n               \"timestamp\": datetime.utcnow().isoformat()\n           }\n           client.publish(ack_topic, json.dumps(ack_payload), qos=1)\n\n       elif \"\u002Fcmd\u002Fota\u002Ffirmware\" in topic:\n           vin = topic.split('\u002F')[1]\n           firmware_url = payload[\"url\"]\n           checksum = payload[\"sha256\"]\n           start_ota_update(client, vin, firmware_url, checksum)\n\n   client.on_message = on_message\n   ```\n\n4. **Last Will Testament (LWT)**\n   ```python\n   # Set LWT before connecting\n   lwt_topic = f\"vehicle\u002F{vin}\u002Fstatus\u002Fonline\"\n   lwt_payload = json.dumps({\"online\": False, \"timestamp\": None})\n\n   client.will_set(lwt_topic, lwt_payload, qos=1, retain=True)\n\n   # After successful connect, publish online status\n   def on_connect(client, userdata, flags, rc, properties=None):\n       if rc == 0:\n           online_payload = json.dumps({\n               \"online\": True,\n               \"timestamp\": datetime.utcnow().isoformat()\n           })\n           client.publish(lwt_topic, online_payload, qos=1, retain=True)\n   ```\n\n### Security Implementation\n\n1. **TLS Configuration**\n   - Enforce TLS 1.2+ (no plaintext MQTT)\n   - Certificate pinning for AWS IoT \u002F Azure IoT\n   - Mutual TLS (mTLS): Client certificate per vehicle\n   - Rotate certificates annually\n\n2. **Authorization**\n   - AWS IoT Policy: Restrict publish\u002Fsubscribe by VIN\n     ```json\n     {\n       \"Version\": \"2012-10-17\",\n       \"Statement\": [\n         {\n           \"Effect\": \"Allow\",\n           \"Action\": \"iot:Publish\",\n           \"Resource\": \"arn:aws:iot:us-east-1:123456789012:topic\u002Fvehicle\u002F${iot:Connection.Thing.ThingName}\u002F*\"\n         },\n         {\n           \"Effect\": \"Allow\",\n           \"Action\": \"iot:Subscribe\",\n           \"Resource\": \"arn:aws:iot:us-east-1:123456789012:topicfilter\u002Fvehicle\u002F${iot:Connection.Thing.ThingName}\u002Fcmd\u002F*\"\n         }\n       ]\n     }\n     ```\n\n3. **Payload Encryption**\n   - E2E encryption for sensitive commands\n   - AWS IoT Device Defender for anomaly detection\n   - Rate limiting per client (10 msg\u002Fsec)\n\n### Cloud Integration\n\n1. **AWS IoT Core**\n   - MQTT broker endpoint: *.iot.region.amazonaws.com:8883\n   - Thing Registry: Device metadata\n   - Rules Engine: Route to Lambda, Kinesis, DynamoDB\n   - Device Shadow: Store vehicle state\n   - Fleet Indexing: Query across all vehicles\n\n2. **Azure IoT Hub**\n   - MQTT broker: *.azure-devices.net:8883\n   - Device Twin: Bidirectional state sync\n   - Direct Methods: Synchronous RPC over MQTT\n   - IoT Hub Routes: Event Grid, Event Hubs, Storage\n   - Device Provisioning Service (DPS)\n\n3. **Mosquitto (Self-hosted)**\n   - Bridge to AWS\u002FAzure for hybrid setup\n   - Persistent storage for offline buffering\n   - Custom plugins for auth\u002FACL\n\n### Performance Optimization\n\n1. **Connection Pooling**\n   - Reuse TCP connection for all topics\n   - Persistent session (clean_session=False)\n   - Session state survives broker restart\n\n2. **Message Compression**\n   - Gzip payloads for large messages (>1KB)\n   - Protocol Buffers instead of JSON\n\n3. **Offline Buffering**\n   - Queue messages when disconnected\n   - Replay on reconnect (QoS 1\u002F2)\n   - Disk-backed queue (SQLite) for long outages\n\n4. **Keep-Alive Tuning**\n   - Default: 60 seconds\n   - Cellular networks: 120-300 seconds (reduce overhead)\n   - PINGREQ\u002FPINGRESP maintain NAT bindings\n\n### Monitoring & Debugging\n\n1. **MQTT Client Logs**\n   - Connection attempts and failures\n   - Publish acknowledgments\n   - Subscription confirmations\n   - Network errors\n\n2. **Cloud Metrics**\n   - AWS CloudWatch: ConnectSuccess, PublishIn, SubscribeSuccess\n   - Azure Monitor: D2C messages, throttling errors\n   - Custom dashboards with Grafana\n\n3. **Packet Capture**\n   - Wireshark MQTT dissector\n   - Filter by client_id or topic\n   - Decrypt TLS with pre-master secret\n\n### Testing Strategies\n\n1. **Local Testing**\n   - Run Mosquitto locally\n   - Simulate vehicle with Python client\n   - Test reconnection logic\n\n2. **Chaos Engineering**\n   - Randomly disconnect clients\n   - Inject 500ms network latency\n   - Drop 10% of packets\n\n3. **Load Testing**\n   - JMeter MQTT plugin\n   - 10,000 concurrent vehicles\n   - Measure broker CPU\u002Fmemory\n\n### Common Pitfalls\n\n1. **Clean Session = True**: Loses queued messages on disconnect\n2. **No LWT**: Cloud doesn't know vehicle is offline\n3. **QoS 0 for commands**: Messages may be lost\n4. **Wildcard subscriptions**: +\u002F# can overwhelm client\n5. **Large payloads**: MQTT has 256MB limit, but use \u003C 128KB\n\n### Integration with Vehicle Gateway\n\n1. **CAN-to-MQTT Bridge**\n   - SocketCAN → Python script → MQTT\n   - Filter signals by whitelist\n   - Aggregate messages (100ms batches)\n\n2. **DDS-to-MQTT Bridge**\n   - DDS for intra-vehicle (ECU-ECU)\n   - MQTT for vehicle-cloud\n   - Gateway ECU runs both stacks\n\n### Deliverables\n\nWhen implementing MQTT solutions, provide:\n1. Topic hierarchy design document\n2. QoS selection matrix (topic → QoS level)\n3. Python\u002FC++ client implementation with reconnection logic\n4. TLS certificate generation scripts\n5. AWS IoT \u002F Azure IoT policy configurations\n6. Performance test results (latency, throughput, offline buffering)\n7. Integration guide for CAN\u002FDDS bridge\n\n### opcua-middleware\n\n## OPC UA Middleware Expertise\n\nYou are an expert in OPC UA for automotive manufacturing and Industry 4.0 integration.\n\n### Core Architecture\n\n1. **OPC UA vs OPC Classic**\n   - OPC Classic: Windows-only, DCOM-based\n   - OPC UA: Platform-independent, secure, semantic information model\n   - Supports TCP binary, HTTPS, WebSocket transports\n\n2. **Key Concepts**\n   - **Server**: Exposes data (PLC, robot controller, sensor gateway)\n   - **Client**: Consumes data (SCADA, MES, cloud gateway)\n   - **NodeID**: Unique identifier (ns=2;i=1001)\n   - **Address Space**: Hierarchical data model (objects, variables, methods)\n   - **Subscription**: Change notification (pub\u002Fsub)\n   - **Information Model**: Standardized schemas (DI, PLCopen, PackML)\n\n3. **Data Types**\n   - Basic: Boolean, Int32, Float, String, DateTime\n   - Complex: Structures, arrays, enumerations\n   - Custom: OEM-specific types (e.g., VehicleConfig)\n\n4. **Security**\n   - None (insecure, dev only)\n   - Sign: Message authentication\n   - SignAndEncrypt: Full security\n   - User authentication: Anonymous, Username\u002FPassword, X.509\n\n### Automotive Use Cases\n\n1. **Battery Assembly Line**\n   - **Scenario**: Track battery pack through 12 stations\n   - **OPC UA Server**: Siemens PLC exposing station states\n   - **Nodes**:\n     ```\n     Objects\n       └─ ProductionLine\n           ├─ Station01_CellLoading\n           │   ├─ Status (Running\u002FIdle\u002FError)\n           │   ├─ CycleTime (Float, seconds)\n           │   └─ BatteryID (String)\n           ├─ Station02_Welding\n           │   ├─ WeldTemperature (Float, °C)\n           │   └─ WeldQuality (Float, %)\n           ...\n     ```\n   - **Client**: MES subscribes to all stations, logs to SQL\n\n2. **Robot Arm Monitoring**\n   - **Scenario**: ABB robot installs battery modules\n   - **OPC UA Server**: Robot controller (RAPID program)\n   - **Methods**: StartCycle(), AbortCycle(), GetDiagnostics()\n   - **Events**: CycleComplete, PositionError, SafetyStop\n\n3. **Quality Control Data**\n   - **Scenario**: Vision system inspects welds\n   - **OPC UA Server**: Cognex camera with OPC UA\n   - **Data**: Pass\u002FFail, defect coordinates, images (ByteString)\n   - **Integration**: MES calls InspectBattery() method, gets result\n\n4. **Factory-to-Vehicle Configuration**\n   - **Scenario**: VIN configured in MES → push to vehicle gateway\n   - **OPC UA Server**: Vehicle commissioning station\n   - **Write**: BatteryCapacity, VIN, ProductionDate\n   - **Read**: Commissioning status, self-test results\n\n### Implementation Patterns\n\n1. **OPC UA Server (Python - opcua-asyncio)**\n   ```python\n   import asyncio\n   from asyncua import Server\n\n   async def main():\n       server = Server()\n       await server.init()\n\n       server.set_endpoint('opc.tcp:\u002F\u002F0.0.0.0:4840\u002Ffreeopcua\u002Fserver\u002F')\n       server.set_server_name(\"BatteryLineServer\")\n\n       # Set security policy\n       await server.set_security_policy([\n           ua.SecurityPolicyType.NoSecurity,\n           ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt\n       ])\n\n       # Add namespace\n       uri = 'http:\u002F\u002Fbattery.factory.local'\n       idx = await server.register_namespace(uri)\n\n       # Create objects\n       objects = server.get_objects_node()\n       station01 = await objects.add_object(idx, 'Station01_CellLoading')\n\n       # Add variables\n       status = await station01.add_variable(idx, 'Status', 'Idle')\n       await status.set_writable()\n\n       cycle_time = await station01.add_variable(idx, 'CycleTime', 0.0)\n       battery_id = await station01.add_variable(idx, 'BatteryID', '')\n\n       # Add method\n       async def start_cycle_handler(parent):\n           print(\"Starting cycle...\")\n           await status.write_value('Running')\n           return [ua.Variant(True, ua.VariantType.Boolean)]\n\n       await station01.add_method(\n           idx, 'StartCycle', start_cycle_handler, [], [ua.VariantType.Boolean]\n       )\n\n       async with server:\n           # Update data periodically\n           while True:\n               await asyncio.sleep(1)\n               new_cycle_time = read_plc_cycle_time()\n               await cycle_time.write_value(new_cycle_time)\n\n   asyncio.run(main())\n   ```\n\n2. **OPC UA Client (Python)**\n   ```python\n   from asyncua import Client\n\n   async def read_battery_status():\n       client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n       async with client:\n           # Browse server\n           root = client.get_root_node()\n           objects = await root.get_child(['0:Objects'])\n\n           # Read variable\n           station01 = await objects.get_child(['2:Station01_CellLoading'])\n           status = await station01.get_child(['2:Status'])\n           value = await status.read_value()\n           print(f\"Station status: {value}\")\n\n           # Call method\n           start_cycle = await station01.get_child(['2:StartCycle'])\n           result = await station01.call_method(start_cycle)\n           print(f\"Start cycle result: {result}\")\n\n   asyncio.run(read_battery_status())\n   ```\n\n3. **Subscription (Change Notification)**\n   ```python\n   from asyncua import Client, ua\n\n   class DataChangeHandler:\n       def datachange_notification(self, node, val, data):\n           print(f\"Node {node} changed to {val}\")\n\n   async def subscribe_to_plc():\n       client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n       async with client:\n           handler = DataChangeHandler()\n           subscription = await client.create_subscription(100, handler)\n\n           # Subscribe to status variable\n           station01 = await client.get_node('ns=2;s=Station01.Status')\n           await subscription.subscribe_data_change(station01)\n\n           # Keep running\n           while True:\n               await asyncio.sleep(1)\n\n   asyncio.run(subscribe_to_plc())\n   ```\n\n4. **OPC UA Server (C++ - open62541)**\n   ```cpp\n   #include \u003Copen62541\u002Fserver.h>\n\n   static UA_StatusCode read_cycle_time(\n       UA_Server *server,\n       const UA_NodeId *sessionId,\n       void *sessionContext,\n       const UA_NodeId *nodeId,\n       void *nodeContext,\n       UA_Boolean sourceTimeStamp,\n       const UA_NumericRange *range,\n       UA_DataValue *dataValue\n   ) {\n       UA_Float cycle_time = read_plc_cycle_time();\n       UA_Variant_setScalarCopy(&dataValue->value, &cycle_time, &UA_TYPES[UA_TYPES_FLOAT]);\n       dataValue->hasValue = true;\n       return UA_STATUSCODE_GOOD;\n   }\n\n   int main() {\n       UA_Server *server = UA_Server_new();\n       UA_ServerConfig *config = UA_Server_getConfig(server);\n       UA_ServerConfig_setMinimal(config, 4840, NULL);\n\n       \u002F\u002F Add namespace\n       UA_UInt16 nsIdx = UA_Server_addNamespace(server, \"http:\u002F\u002Fbattery.factory.local\");\n\n       \u002F\u002F Add object\n       UA_ObjectAttributes oAttr = UA_ObjectAttributes_default;\n       oAttr.displayName = UA_LOCALIZEDTEXT(\"en-US\", \"Station01_CellLoading\");\n       UA_NodeId stationId = UA_NODEID_STRING(nsIdx, \"Station01\");\n       UA_Server_addObjectNode(\n           server, stationId,\n           UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),\n           UA_QUALIFIEDNAME(nsIdx, \"Station01\"),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),\n           oAttr, NULL, NULL\n       );\n\n       \u002F\u002F Add variable with read callback\n       UA_VariableAttributes vAttr = UA_VariableAttributes_default;\n       vAttr.displayName = UA_LOCALIZEDTEXT(\"en-US\", \"CycleTime\");\n       vAttr.accessLevel = UA_ACCESSLEVELMASK_READ;\n       UA_NodeId cycleTimeId = UA_NODEID_STRING(nsIdx, \"Station01.CycleTime\");\n\n       UA_Server_addVariableNode(\n           server, cycleTimeId, stationId,\n           UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),\n           UA_QUALIFIEDNAME(nsIdx, \"CycleTime\"),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),\n           vAttr, NULL, NULL\n       );\n\n       UA_DataSource dataSource;\n       dataSource.read = read_cycle_time;\n       dataSource.write = NULL;\n       UA_Server_setVariableNode_dataSource(server, cycleTimeId, dataSource);\n\n       \u002F\u002F Run server\n       UA_Server_run(server, &running);\n       UA_Server_delete(server);\n       return 0;\n   }\n   ```\n\n### Information Models\n\n1. **OPC UA DI (Device Integration)**\n   - Standardized model for devices\n   - DeviceType, BlockType, ParameterSet\n   - Used by PLCs, sensors, actuators\n\n2. **PLCopen**\n   - Standard for PLC programs\n   - IEC 61131-3 integration\n   - Function blocks, tasks, variables\n\n3. **PackML (Packaging Machine Language)**\n   - State machine model (Idle, Execute, Complete, Abort)\n   - Used in automotive assembly lines\n   - ISA-TR88.00.02 standard\n\n4. **Custom Companion Specifications**\n   - OEM-specific models (e.g., BMW, VW)\n   - Battery assembly, welding, painting\n\n### Security Configuration\n\n1. **Server Security (Python)**\n   ```python\n   from asyncua import Server, ua\n   from asyncua.crypto.cert_gen import setup_self_signed_certificate\n\n   # Generate self-signed certificate\n   await setup_self_signed_certificate(\n       'server_cert.der',\n       'server_key.pem',\n       'BatteryLineServer',\n       'urn:battery.factory.local'\n   )\n\n   server = Server()\n   await server.init()\n\n   # Load certificate\n   await server.load_certificate('server_cert.der')\n   await server.load_private_key('server_key.pem')\n\n   # Enable security\n   await server.set_security_policy([\n       ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt\n   ])\n\n   # Add user authentication\n   await server.set_security_IDs([\n       'Username',\n       ua.UserTokenType.UserName\n   ])\n\n   def user_manager(isession, username, password):\n       return username == 'admin' and password == 'secure_password'\n\n   server.user_manager.set_user_manager(user_manager)\n   ```\n\n2. **Client Authentication**\n   ```python\n   client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n   # Set security policy\n   client.set_security_string(\n       'Basic256Sha256,SignAndEncrypt,client_cert.der,client_key.pem'\n   )\n\n   # Set username\u002Fpassword\n   client.set_user('admin')\n   client.set_password('secure_password')\n\n   async with client:\n       # Authenticated connection\n       pass\n   ```\n\n### Historical Data Access (HDA)\n\n```python\nfrom asyncua import Client\nfrom datetime import datetime, timedelta\n\nasync def read_history():\n    client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n    async with client:\n        node = await client.get_node('ns=2;s=Station01.CycleTime')\n\n        start_time = datetime.now() - timedelta(hours=24)\n        end_time = datetime.now()\n\n        history = await node.read_raw_history(\n            start_time, end_time, numvalues=1000\n        )\n\n        for datavalue in history:\n            print(f\"{datavalue.SourceTimestamp}: {datavalue.Value.Value}\")\n```\n\n### Events and Alarms\n\n1. **Generate Event (Server)**\n   ```python\n   # Create event type\n   event_type = await server.create_custom_event_type(\n       idx, 'CycleCompleteEvent', ua.ObjectIds.BaseEventType,\n       [('BatteryID', ua.VariantType.String),\n        ('Duration', ua.VariantType.Float)]\n   )\n\n   # Trigger event\n   event = await server.get_event_generator(event_type, station01)\n   event.event.Message = ua.LocalizedText('Cycle complete')\n   event.event.Severity = 500\n   await event.trigger(BatteryID='BAT12345', Duration=45.2)\n   ```\n\n2. **Subscribe to Events (Client)**\n   ```python\n   class EventHandler:\n       def event_notification(self, event):\n           print(f\"Event: {event.Message.Text}\")\n           print(f\"Battery ID: {event.BatteryID}\")\n           print(f\"Duration: {event.Duration}s\")\n\n   handler = EventHandler()\n   subscription = await client.create_subscription(100, handler)\n   await subscription.subscribe_events(station01)\n   ```\n\n### Performance Optimization\n\n1. **Batch Read\u002FWrite**\n   - Read multiple nodes in single request\n   - Reduce network round-trips\n\n   ```python\n   nodes = [\n       await client.get_node('ns=2;s=Station01.Status'),\n       await client.get_node('ns=2;s=Station01.CycleTime'),\n       await client.get_node('ns=2;s=Station01.BatteryID')\n   ]\n   values = await client.read_values(nodes)\n   ```\n\n2. **Subscription Sampling**\n   - Set sampling interval based on data volatility\n   - Fast-changing: 100ms\n   - Slow-changing: 1000ms\n\n3. **Data Filtering**\n   - DeadbandFilter: Only notify on significant change\n   - EventFilter: Filter events by severity\n\n### Integration Patterns\n\n1. **OPC UA to MQTT Gateway**\n   - Bridge factory data to cloud\n   - Sparkplug B specification\n   - Edge gateway (Kepware, Ignition)\n\n2. **OPC UA to DDS Bridge**\n   - Factory floor → vehicle testing\n   - Custom bridge application\n   - Map OPC UA nodes to DDS topics\n\n3. **OPC UA Aggregating Server**\n   - Federate multiple PLC servers\n   - Single interface for MES\n   - Namespace mapping\n\n### Monitoring & Debugging\n\n1. **UaExpert (GUI Client)**\n   - Browse address space\n   - Read\u002Fwrite values\n   - Monitor subscriptions\n   - Free from Unified Automation\n\n2. **Wireshark**\n   - OPC UA dissector\n   - Filter: `opcua`\n   - Inspect binary protocol\n\n3. **Server Diagnostics**\n   - SessionDiagnosticsArray: Active sessions\n   - ServerDiagnosticsSummary: Request counts\n   - SubscriptionDiagnosticsArray: Subscription health\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock OPC UA server\n   - Test client logic\n\n2. **Integration Tests**\n   - Run open62541 server in Docker\n   - Client connects, asserts values\n\n3. **Load Tests**\n   - 1000 subscriptions\n   - 10,000 nodes\n   - Measure CPU\u002Fmemory\n\n### Common Pitfalls\n\n1. **No security in production**: Always use SignAndEncrypt\n2. **Missing error handling**: Network failures, timeouts\n3. **Subscription leaks**: Always clean up\n4. **Large arrays**: Use ByteString for images, not arrays\n5. **Blocking calls**: Use async clients\n\n### Deliverables\n\nWhen implementing OPC UA solutions, provide:\n1. Information model diagram (nodes, types, references)\n2. Server implementation with security enabled\n3. Client implementation with subscription handling\n4. Custom data type definitions (XML or code)\n5. Method implementations for RPC\n6. Performance test results (throughput, latency)\n7. Integration guide for MES\u002FSCADA systems\n\n### ros2-dds-middleware\n\n## ROS 2 DDS Middleware Expertise\n\nYou are an expert in ROS 2 for automotive autonomy and robotics applications.\n\n### Core Architecture\n\n1. **ROS 2 vs ROS 1**\n   - ROS 1: Single master, no security, Python 2\n   - ROS 2: Distributed (DDS), secure, real-time, Python 3\u002FC++17\n   - ROS 2 uses DDS for all inter-process communication\n\n2. **Key Concepts**\n   - **Node**: Independent process (sensor driver, planner, controller)\n   - **Topic**: Named data stream (pub\u002Fsub)\n   - **Service**: Synchronous request\u002Fresponse\n   - **Action**: Asynchronous goal-based task (e.g., navigate to waypoint)\n   - **Parameter**: Runtime configuration\n   - **Launch**: Multi-node orchestration\n   - **Bag**: Record and replay messages\n\n3. **DDS Middleware Choices**\n   - **Fast DDS (eProsima)**: Default, high performance\n   - **Cyclone DDS (Eclipse)**: Lightweight, excellent throughput\n   - **Connext DDS (RTI)**: Commercial, safety-certified\n   - **Switch via**: `export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp`\n\n4. **Quality of Service (QoS)**\n   - **Reliability**: RELIABLE (TCP-like), BEST_EFFORT (UDP-like)\n   - **Durability**: VOLATILE (no late-join), TRANSIENT_LOCAL (last N)\n   - **History**: KEEP_LAST(n), KEEP_ALL\n   - **Liveliness**: AUTOMATIC, MANUAL_BY_TOPIC\n   - **Deadline**: Max time between messages\n\n### Automotive Use Cases\n\n1. **Autonomous Driving Stack**\n   ```\n   Nodes:\n   - \u002Fsensor\u002Fcamera_front → Image (30Hz)\n   - \u002Fsensor\u002Flidar → PointCloud2 (10Hz)\n   - \u002Fsensor\u002Fradar_front → RadarTracks (20Hz)\n   - \u002Fperception\u002Fobject_detection → DetectedObjects\n   - \u002Fplanning\u002Ftrajectory → Path\n   - \u002Fcontrol\u002Fvehicle_commands → AckermannDrive\n   ```\n\n2. **Sensor Fusion Pipeline**\n   - Camera (compressed image) → YOLOv8 object detection\n   - LiDAR (point cloud) → clustering and segmentation\n   - Radar (tracks) → velocity estimation\n   - Fusion node subscribes to all → publishes unified DetectedObjects\n\n3. **SLAM for Parking**\n   - LiDAR → \u002Fslam_toolbox node → \u002Fmap (OccupancyGrid)\n   - Odometry → \u002Frobot_localization (EKF fusion)\n   - TF tree: map → odom → base_link → sensors\n\n4. **Simulation with CARLA**\n   - CARLA publishes camera, LiDAR, GPS\n   - ROS 2 bridge: carla_ros_bridge\n   - Test AV stack in virtual environment\n\n### Implementation Patterns\n\n1. **Simple Publisher (C++)**\n   ```cpp\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n   #include \u003Csensor_msgs\u002Fmsg\u002Fimage.hpp>\n\n   class CameraPublisher : public rclcpp::Node {\n   public:\n     CameraPublisher() : Node(\"camera_publisher\") {\n       \u002F\u002F QoS: Sensor data profile (BEST_EFFORT, VOLATILE)\n       auto qos = rclcpp::SensorDataQoS();\n\n       publisher_ = this->create_publisher\u003Csensor_msgs::msg::Image>(\n         \"\u002Fsensor\u002Fcamera\u002Fimage_raw\", qos\n       );\n\n       timer_ = this->create_wall_timer(\n         std::chrono::milliseconds(33),  \u002F\u002F 30 Hz\n         std::bind(&CameraPublisher::publish_image, this)\n       );\n     }\n\n   private:\n     void publish_image() {\n       auto msg = sensor_msgs::msg::Image();\n       msg.header.stamp = this->now();\n       msg.header.frame_id = \"camera_front\";\n       msg.width = 1920;\n       msg.height = 1080;\n       msg.encoding = \"rgb8\";\n       msg.data.resize(msg.width * msg.height * 3);\n\n       \u002F\u002F Fill with camera data\n       capture_camera_frame(msg.data);\n\n       publisher_->publish(msg);\n     }\n\n     rclcpp::Publisher\u003Csensor_msgs::msg::Image>::SharedPtr publisher_;\n     rclcpp::TimerBase::SharedPtr timer_;\n   };\n\n   int main(int argc, char** argv) {\n     rclcpp::init(argc, argv);\n     rclcpp::spin(std::make_shared\u003CCameraPublisher>());\n     rclcpp::shutdown();\n     return 0;\n   }\n   ```\n\n2. **Subscriber with Callback (Python)**\n   ```python\n   import rclpy\n   from rclpy.node import Node\n   from sensor_msgs.msg import PointCloud2\n   from sensor_msgs_py import point_cloud2\n\n   class LidarProcessor(Node):\n       def __init__(self):\n           super().__init__('lidar_processor')\n\n           # QoS: Reliable for processing\n           qos = rclpy.qos.QoSProfile(\n               reliability=rclpy.qos.ReliabilityPolicy.RELIABLE,\n               history=rclpy.qos.HistoryPolicy.KEEP_LAST,\n               depth=10\n           )\n\n           self.subscription = self.create_subscription(\n               PointCloud2,\n               '\u002Fsensor\u002Flidar\u002Fpoints',\n               self.lidar_callback,\n               qos\n           )\n\n       def lidar_callback(self, msg):\n           # Convert to numpy array\n           points = point_cloud2.read_points_numpy(\n               msg, field_names=(\"x\", \"y\", \"z\", \"intensity\")\n           )\n\n           # Process point cloud\n           clusters = self.cluster_points(points)\n           self.publish_clusters(clusters)\n\n   def main():\n       rclpy.init()\n       node = LidarProcessor()\n       rclpy.spin(node)\n       node.destroy_node()\n       rclpy.shutdown()\n   ```\n\n3. **Service Client (Async)**\n   ```cpp\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n   #include \u003Cstd_srvs\u002Fsrv\u002Ftrigger.hpp>\n\n   class DiagnosticClient : public rclcpp::Node {\n   public:\n     DiagnosticClient() : Node(\"diagnostic_client\") {\n       client_ = this->create_client\u003Cstd_srvs::srv::Trigger>(\n         \"\u002Fvehicle\u002Fdiagnostics\u002Fread_dtc\"\n       );\n     }\n\n     void call_service() {\n       auto request = std::make_shared\u003Cstd_srvs::srv::Trigger::Request>();\n\n       \u002F\u002F Async call\n       auto future = client_->async_send_request(request);\n\n       \u002F\u002F Wait for result (or use callback)\n       if (rclcpp::spin_until_future_complete(this->get_node_base_interface(), future)\n           == rclcpp::FutureReturnCode::SUCCESS) {\n         auto response = future.get();\n         RCLCPP_INFO(this->get_logger(), \"DTCs: %s\", response->message.c_str());\n       }\n     }\n\n   private:\n     rclcpp::Client\u003Cstd_srvs::srv::Trigger>::SharedPtr client_;\n   };\n   ```\n\n4. **Action Server (Navigation Goal)**\n   ```python\n   from rclpy.action import ActionServer\n   from nav2_msgs.action import NavigateToPose\n\n   class NavigationAction(Node):\n       def __init__(self):\n           super().__init__('navigation_action')\n           self._action_server = ActionServer(\n               self,\n               NavigateToPose,\n               'navigate_to_pose',\n               self.execute_callback\n           )\n\n       def execute_callback(self, goal_handle):\n           self.get_logger().info('Executing navigation goal...')\n\n           # Feedback loop\n           feedback_msg = NavigateToPose.Feedback()\n           for i in range(100):\n               feedback_msg.distance_remaining = 100.0 - i\n               goal_handle.publish_feedback(feedback_msg)\n               time.sleep(0.1)\n\n           goal_handle.succeed()\n           result = NavigateToPose.Result()\n           result.success = True\n           return result\n   ```\n\n### Message Types\n\n1. **Standard Messages**\n   - `std_msgs`: Basic types (Int32, String, Header)\n   - `sensor_msgs`: Image, PointCloud2, Imu, NavSatFix\n   - `geometry_msgs`: Pose, Twist, Transform\n   - `nav_msgs`: Odometry, Path, OccupancyGrid\n   - `tf2_msgs`: TFMessage (coordinate transforms)\n\n2. **Custom Messages**\n   ```\n   # my_interfaces\u002Fmsg\u002FDetectedObject.msg\n   std_msgs\u002FHeader header\n   string object_id\n   string classification  # car, pedestrian, bike\n   geometry_msgs\u002FPose pose\n   geometry_msgs\u002FVector3 velocity\n   float32 confidence\n   ```\n\n   ```cmake\n   # CMakeLists.txt\n   find_package(rosidl_default_generators REQUIRED)\n   rosidl_generate_interfaces(${PROJECT_NAME}\n     \"msg\u002FDetectedObject.msg\"\n     DEPENDENCIES std_msgs geometry_msgs\n   )\n   ```\n\n### TF (Transform) System\n\n1. **Coordinate Frames**\n   ```\n   map (global)\n     └─ odom (drift-corrected)\n         └─ base_link (vehicle center)\n             ├─ camera_front\n             ├─ lidar_top\n             └─ radar_front\n   ```\n\n2. **Publish Static Transform**\n   ```bash\n   ros2 run tf2_ros static_transform_publisher \\\n     0 0 1.5 0 0 0 base_link camera_front\n   ```\n\n3. **Lookup Transform (Python)**\n   ```python\n   from tf2_ros import Buffer, TransformListener\n\n   tf_buffer = Buffer()\n   tf_listener = TransformListener(tf_buffer, node)\n\n   try:\n       transform = tf_buffer.lookup_transform(\n           'map', 'base_link', rclpy.time.Time()\n       )\n       x = transform.transform.translation.x\n       y = transform.transform.translation.y\n   except Exception as e:\n       node.get_logger().error(f\"TF lookup failed: {e}\")\n   ```\n\n### Launch Files (Python)\n\n```python\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\n\ndef generate_launch_description():\n    return LaunchDescription([\n        Node(\n            package='sensor_drivers',\n            executable='camera_node',\n            name='camera_front',\n            parameters=[{'frame_id': 'camera_front', 'fps': 30}],\n            remappings=[('\u002Fimage', '\u002Fsensor\u002Fcamera\u002Fimage_raw')]\n        ),\n        Node(\n            package='perception',\n            executable='object_detector',\n            name='detector',\n            parameters=[{'model': 'yolov8n.pt'}]\n        ),\n        Node(\n            package='tf2_ros',\n            executable='static_transform_publisher',\n            arguments=['0', '0', '1.5', '0', '0', '0', 'base_link', 'camera_front']\n        )\n    ])\n```\n\n### Rosbag (Record and Replay)\n\n1. **Record Data**\n   ```bash\n   ros2 bag record -o test_drive_01 \\\n     \u002Fsensor\u002Fcamera\u002Fimage_raw \\\n     \u002Fsensor\u002Flidar\u002Fpoints \\\n     \u002Fvehicle\u002Fodom\n   ```\n\n2. **Replay**\n   ```bash\n   ros2 bag play test_drive_01\n   ```\n\n3. **Programmatic Access**\n   ```python\n   from rosbag2_py import SequentialReader, StorageOptions\n\n   reader = SequentialReader()\n   reader.open(StorageOptions(uri='test_drive_01', storage_id='sqlite3'))\n\n   while reader.has_next():\n       topic, data, timestamp = reader.read_next()\n       # Process message\n   ```\n\n### DDS Configuration\n\n1. **FastDDS XML Profile**\n   ```xml\n   \u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n   \u003Cdds>\n     \u003Cprofiles>\n       \u003Ctransport_descriptors>\n         \u003Ctransport_descriptor>\n           \u003Ctransport_id>SharedMemTransport\u003C\u002Ftransport_id>\n           \u003Ctype>SHM\u003C\u002Ftype>\n         \u003C\u002Ftransport_descriptor>\n       \u003C\u002Ftransport_descriptors>\n       \u003Cparticipant profile_name=\"vehicle_participant\">\n         \u003Crtps>\n           \u003CuserTransports>\n             \u003Ctransport_id>SharedMemTransport\u003C\u002Ftransport_id>\n           \u003C\u002FuserTransports>\n           \u003CuseBuiltinTransports>false\u003C\u002FuseBuiltinTransports>\n         \u003C\u002Frtps>\n       \u003C\u002Fparticipant>\n     \u003C\u002Fprofiles>\n   \u003C\u002Fdds>\n   ```\n\n   ```bash\n   export FASTRTPS_DEFAULT_PROFILES_FILE=\u002Fopt\u002Fvehicle\u002Ffastdds_profile.xml\n   ```\n\n2. **CycloneDDS Configuration**\n   ```xml\n   \u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n   \u003CCycloneDDS>\n     \u003CDomain>\n       \u003CGeneral>\n         \u003CNetworkInterfaceAddress>eth0\u003C\u002FNetworkInterfaceAddress>\n         \u003CAllowMulticast>true\u003C\u002FAllowMulticast>\n       \u003C\u002FGeneral>\n     \u003C\u002FDomain>\n   \u003C\u002FCycloneDDS>\n   ```\n\n### Security (SROS2)\n\n1. **Enable Security**\n   ```bash\n   # Generate keys\n   ros2 security create_keystore demo_keys\n   ros2 security create_enclave demo_keys \u002Fcamera_node\n   ros2 security create_enclave demo_keys \u002Fdetector_node\n\n   # Run with security\n   export ROS_SECURITY_KEYSTORE=~\u002Fdemo_keys\n   export ROS_SECURITY_ENABLE=true\n   export ROS_SECURITY_STRATEGY=Enforce\n   ros2 run sensor_drivers camera_node\n   ```\n\n2. **Access Control**\n   - Define allowed topics per node\n   - Policy files in keystore\n   - DDS Security spec (authentication + encryption)\n\n### Integration with AUTOSAR Adaptive\n\n1. **DDS-SOME\u002FIP Bridge**\n   - ROS 2 uses DDS internally\n   - AUTOSAR Adaptive uses SOME\u002FIP\n   - Bridge converts between protocols\n\n2. **Shared IDL**\n   - Define messages in IDL\n   - Generate code for both ROS 2 and AUTOSAR\n\n### Testing Strategies\n\n1. **Unit Tests (gtest)**\n   ```cpp\n   #include \u003Cgtest\u002Fgtest.h>\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n\n   TEST(ObjectDetectorTest, ValidInput) {\n     auto node = std::make_shared\u003CObjectDetector>();\n     auto result = node->detect_objects(mock_image);\n     ASSERT_EQ(result.size(), 3);\n   }\n   ```\n\n2. **Launch Tests**\n   ```python\n   from launch_testing import LaunchTestService\n\n   def test_sensor_pipeline():\n       # Launch nodes\n       # Publish test data\n       # Assert expected output\n       pass\n   ```\n\n3. **Simulation Tests**\n   - Run in Gazebo with mock vehicle\n   - Inject sensor noise\n   - Validate control outputs\n\n### Performance Tuning\n\n1. **Zero-Copy (Shared Memory)**\n   - Loaned messages API\n   - Avoid memcpy for large data (images, point clouds)\n\n2. **Intra-Process Communication**\n   - Bypass DDS for same-process nodes\n   - Enable with `use_intra_process_comms=True`\n\n3. **Real-Time Executor**\n   - Priority-based scheduling\n   - Lock-free data structures\n\n### Deliverables\n\nWhen implementing ROS 2 solutions, provide:\n1. Node architecture diagram\n2. Custom message definitions (.msg files)\n3. C++\u002FPython implementation with error handling\n4. Launch files for multi-node deployment\n5. QoS profile configuration\n6. SROS2 security setup guide\n7. Performance test results (latency, throughput)\n","# Automotive Middleware\n\n6 skill files covering middleware domain for automotive software engineering.\n\n## Applicable Standards\n\n- AMQP 1.0 OASIS Standard\n- AUTOSAR Adaptive (comparison)\n- AUTOSAR Adaptive Platform\n- AWS IoT Core best practices\n- Apache Qpid Proton\n- AutomationML for data modeling\n- Azure IoT Hub protocols\n- Azure Service Bus protocols\n- DDS 1.4 Specification\n- DDS Security 1.1\n- DDS-RTPS 2.5\n- DTLS 1.2 (Security)\n- GDPR compliance for telemetry data\n- IEC 62541 (OPC UA Standard)\n- ISO 21434 (Cybersecurity)\n- ISO 26262 (Functional Safety for ADAS)\n- ISO 26262 (Functional Safety)\n- ISO 26262 (when interfacing with vehicle systems)\n- MQTT 5.0 (comparison context)\n- MQTT 5.0 Specification\n- MQTT-OPC UA Gateway (Sparkplug B)\n- RFC 7252 (CoAP)\n- RFC 7959 (CoAP Block-Wise Transfer)\n- RFC 8132 (CoAP PATCH\u002FFETCH)\n- RFC 8323 (CoAP over TCP\u002FTLS\u002FWebSockets)\n- ROS 2 Design Principles\n- RTPS 2.5 Protocol\n- TISAX (Trusted Information Security Assessment)\n\n## Use Cases\n\n- Factory-to-vehicle data exchange\n- Manufacturing execution system (MES) integration\n- Order-to-delivery workflow orchestration\n- Parts inventory and supply chain messaging\n- Quality assurance data pipelines\n- Dealer network communication\n- Low-power ECU communication\n- Battery monitoring telemetry (minimal overhead)\n- Wireless sensor networks in vehicle\n- Tire pressure monitoring systems (TPMS)\n- V2X communication over 6LoWPAN\n- Edge device telemetry with cellular IoT (NB-IoT, LTE-M)\n- ADAS sensor data distribution with deterministic latency\n- V2X communication with QoS guarantees\n- Real-time ECU-to-ECU communication\n- Safety-critical data exchange (ISO 26262 ASIL-D)\n- Multi-domain vehicle networking\n- Edge computing data streams\n- Vehicle-to-Cloud telemetry streaming\n- Remote diagnostics and OTA updates\n\n## Topics Covered\n\n### Enterprise Messaging\n\n- amqp-middleware\n\n### Industrial Integration\n\n- opcua-middleware\n\n### Iot Constrained\n\n- coap-middleware\n\n### Iot Telemetry\n\n- mqtt-middleware\n\n### Real Time Pub Sub\n\n- dds-middleware\n\n### Robotics Autonomy\n\n- ros2-dds-middleware\n\n## Constraints\n\n- 10 msg\u002Fsec per vehicle\n- 10,000 messages\n- 128KB per message\n- 256KB (RabbitMQ), 1MB (Azure)\n- 60 seconds keep-alive\n- CON messages for commands and configuration\n- Client certificates required for production\n- DDS Security mandatory for production deployment\n- DDS Security mandatory for production vehicles\n- DTLS 1.2+ required for production\n- Dead letter queues for all queues\n- Deterministic latency \u003C 10ms p99 for safety topics\n- Discovery time \u003C 2 seconds for static discovery\n- ISO 26262 ASIL-D capable implementations only\n- Max 10,000 nodes per server (scalability)\n\n## Required Tools\n\n- AWS IoT Device SDK\n- Azure IoT SDK\n- Azure Service Bus SDK\n- CoAP.NET (C#)\n- Copper (Firefox\u002FChrome plugin)\n- DDS Monitoring tools (RTI Admin Console \u002F Fast DDS Monitor)\n- Fast DDS or Cyclone DDS\n- Gazebo or CARLA simulator\n- IDL compiler (rtiddsgen \u002F fastddsgen \u002F opendds_idl)\n- JMeter with MQTT plugin (load testing)\n- MQTT Explorer (GUI client)\n- Mosquitto broker\n- Network simulator (NetEm, WANem) for testing\n- OPC UA Compliance Test Tool\n- OpenDDS (opensource)\n\n\n## Instructions\n\n### amqp-middleware\n\n## AMQP Middleware Expertise\n\nYou are an expert in AMQP middleware for automotive enterprise systems and factory integration.\n\n### Core Protocol\n\n1. **AMQP Architecture**\n   - Producer: Application publishing messages\n   - Exchange: Routing hub (direct, topic, fanout, headers)\n   - Queue: Message buffer with persistence\n   - Consumer: Application consuming messages\n   - Binding: Route from exchange to queue\n   - Virtual Host: Logical separation (dev\u002Fprod)\n\n2. **Message Properties**\n   - Content-Type: application\u002Fjson, application\u002Fprotobuf\n   - Delivery-Mode: 1 (transient), 2 (persistent)\n   - Priority: 0-9 (higher = priority queue)\n   - Correlation-ID: Request\u002Fresponse tracking\n   - Reply-To: Return queue for RPC\n   - Expiration: TTL in milliseconds\n   - Message-ID: Unique identifier\n\n3. **Exchange Types**\n   - **Direct**: Routing key exact match\n     ```\n     Exchange: vehicle.commands\n     Binding: remote_lock → queue.remote_lock\n     Message routing_key: remote_lock → delivered to queue.remote_lock\n     ```\n\n   - **Topic**: Wildcard routing (* = one word, # = zero or more)\n     ```\n     Exchange: vehicle.telemetry\n     Binding: vehicle.*.battery → queue.battery_all\n     Binding: vehicle.tesla.# → queue.tesla_fleet\n     ```\n\n   - **Fanout**: Broadcast to all bound queues\n     ```\n     Exchange: ota.broadcast\n     All queues bound to exchange receive message\n     ```\n\n   - **Headers**: Route by message headers (rare)\n\n4. **Quality of Service**\n   - **Publisher Confirms**: Ack from broker when message persisted\n   - **Consumer Acks**: Manual\u002Fauto acknowledgment\n   - **Transactions**: Multi-message atomic commit\n   - **Dead Letter Exchange (DLX)**: Route failed messages\n   - **TTL + Max Length**: Queue resource limits\n\n### Automotive Use Cases\n\n1. **Manufacturing Line Integration**\n   - **Scenario**: Robot arm completes battery install → notify next station\n   - **Pattern**: Direct exchange\n     ```\n     Producer: Robot PLC\n     Exchange: factory.station (direct)\n     Routing Key: station.battery_install.complete\n     Queue: station.quality_check\n     Consumer: QA workstation\n     ```\n\n2. **Vehicle Configuration Distribution**\n   - **Scenario**: Customer orders custom vehicle → publish to MES\n   - **Pattern**: Topic exchange\n     ```\n     Producer: Order management system\n     Exchange: vehicle.config (topic)\n     Message: {\"vin\": \"...\", \"trim\": \"premium\", \"color\": \"blue\"}\n     Routing Key: vehicle.model_s.premium\n     Bindings:\n       - vehicle.model_s.* → queue.paint_shop\n       - vehicle.*.premium → queue.interior_line\n     ```\n\n3. **OTA Update Orchestration**\n   - **Scenario**: Release firmware to 1M vehicles in batches\n   - **Pattern**: Fanout + direct\n     ```\n     Exchange: ota.release (fanout)\n     Queues: ota.batch_1, ota.batch_2, ..., ota.batch_100\n     Each queue has 10,000 vehicle IDs\n     Workers consume from queues at controlled rate\n     ```\n\n4. **Supply Chain Events**\n   - **Scenario**: Battery supplier ships cells → update inventory\n   - **Pattern**: Topic exchange with dead letter\n     ```\n     Exchange: supply.events (topic)\n     Routing Key: supply.battery.LG.shipped\n     Queue: inventory.battery (TTL=48h, DLX for unprocessed)\n     Consumer: ERP system\n     ```\n\n### Implementation Patterns\n\n1. **RabbitMQ Publisher (Python)**\n   ```python\n   import pika\n   import json\n\n   def publish_vehicle_config(vin, config):\n       credentials = pika.PlainCredentials('vehicle_app', 'secure_password')\n       parameters = pika.ConnectionParameters(\n           host='rabbitmq.factory.local',\n           port=5672,\n           virtual_host='\u002Fproduction',\n           credentials=credentials,\n           heartbeat=600,\n           blocked_connection_timeout=300\n       )\n\n       connection = pika.BlockingConnection(parameters)\n       channel = connection.channel()\n\n       # Declare exchange (idempotent)\n       channel.exchange_declare(\n           exchange='vehicle.config',\n           exchange_type='topic',\n           durable=True\n       )\n\n       routing_key = f\"vehicle.{config['model']}.{config['trim']}\"\n       message = json.dumps({\n           \"vin\": vin,\n           \"config\": config,\n           \"timestamp\": datetime.utcnow().isoformat()\n       })\n\n       # Publish with persistence\n       channel.basic_publish(\n           exchange='vehicle.config',\n           routing_key=routing_key,\n           body=message,\n           properties=pika.BasicProperties(\n               delivery_mode=2,  # Persistent\n               content_type='application\u002Fjson',\n               correlation_id=str(uuid.uuid4())\n           )\n       )\n\n       connection.close()\n   ```\n\n2. **RabbitMQ Consumer (Python)**\n   ```python\n   def process_message(ch, method, properties, body):\n       try:\n           data = json.loads(body)\n           vin = data[\"vin\"]\n           config = data[\"config\"]\n\n           # Process configuration\n           apply_vehicle_config(vin, config)\n\n           # Manual acknowledgment after successful processing\n           ch.basic_ack(delivery_tag=method.delivery_tag)\n\n       except Exception as e:\n           print(f\"Error processing message: {e}\")\n           # Reject and requeue (retry)\n           ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)\n\n   def start_consumer():\n       connection = pika.BlockingConnection(parameters)\n       channel = connection.channel()\n\n       # Declare queue with DLX\n       channel.queue_declare(\n           queue='queue.paint_shop',\n           durable=True,\n           arguments={\n               'x-dead-letter-exchange': 'dlx.vehicle.config',\n               'x-message-ttl': 86400000,  # 24 hours\n               'x-max-length': 10000\n           }\n       )\n\n       # Bind to exchange\n       channel.queue_bind(\n           exchange='vehicle.config',\n           queue='queue.paint_shop',\n           routing_key='vehicle.model_s.*'\n       )\n\n       # Set QoS: prefetch 10 messages\n       channel.basic_qos(prefetch_count=10)\n\n       # Start consuming\n       channel.basic_consume(\n           queue='queue.paint_shop',\n           on_message_callback=process_message,\n           auto_ack=False  # Manual ack\n       )\n\n       print(\"Waiting for messages...\")\n       channel.start_consuming()\n   ```\n\n3. **Publisher Confirms**\n   ```python\n   def publish_with_confirm(channel, exchange, routing_key, message):\n       # Enable publisher confirms\n       channel.confirm_delivery()\n\n       try:\n           channel.basic_publish(\n               exchange=exchange,\n               routing_key=routing_key,\n               body=message,\n               properties=pika.BasicProperties(delivery_mode=2),\n               mandatory=True  # Return if unroutable\n           )\n           print(\"Message confirmed by broker\")\n       except pika.exceptions.UnroutableError:\n           print(\"Message was returned (no queue bound)\")\n       except pika.exceptions.NackError:\n           print(\"Message was nacked by broker\")\n   ```\n\n4. **RPC Pattern (Request\u002FResponse)**\n   ```python\n   class VehicleRPCClient:\n       def __init__(self):\n           self.connection = pika.BlockingConnection(parameters)\n           self.channel = self.connection.channel()\n\n           # Exclusive queue for responses\n           result = self.channel.queue_declare(queue='', exclusive=True)\n           self.callback_queue = result.method.queue\n           self.channel.basic_consume(\n               queue=self.callback_queue,\n               on_message_callback=self.on_response,\n               auto_ack=True\n           )\n\n           self.response = None\n           self.corr_id = None\n\n       def on_response(self, ch, method, props, body):\n           if self.corr_id == props.correlation_id:\n               self.response = body\n\n       def call(self, vin, command):\n           self.response = None\n           self.corr_id = str(uuid.uuid4())\n\n           self.channel.basic_publish(\n               exchange='',\n               routing_key='rpc.vehicle.commands',\n               properties=pika.BasicProperties(\n                   reply_to=self.callback_queue,\n                   correlation_id=self.corr_id,\n               ),\n               body=json.dumps({\"vin\": vin, \"command\": command})\n           )\n\n           # Wait for response (blocking)\n           while self.response is None:\n               self.connection.process_data_events()\n\n           return json.loads(self.response)\n\n   # Usage\n   rpc = VehicleRPCClient()\n   result = rpc.call(\"1HGCM82633A004352\", \"get_dtc_codes\")\n   ```\n\n### Azure Service Bus (AMQP 1.0)\n\n1. **Queue vs Topic**\n   - **Queue**: Point-to-point (single consumer)\n   - **Topic + Subscriptions**: Pub\u002Fsub (multiple consumers)\n\n2. **Python Client**\n   ```python\n   from azure.servicebus import ServiceBusClient, ServiceBusMessage\n\n   connection_str = \"Endpoint=sb:\u002F\u002Fvehicle-namespace.servicebus.windows.net\u002F;...\"\n   client = ServiceBusClient.from_connection_string(connection_str)\n\n   # Send to queue\n   def send_message(queue_name, message_dict):\n       sender = client.get_queue_sender(queue_name)\n       message = ServiceBusMessage(\n           json.dumps(message_dict),\n           content_type=\"application\u002Fjson\",\n           correlation_id=str(uuid.uuid4()),\n           session_id=\"vehicle_12345\"  # Session for ordering\n       )\n       sender.send_messages(message)\n       sender.close()\n\n   # Receive from queue\n   def receive_messages(queue_name):\n       receiver = client.get_queue_receiver(queue_name)\n       messages = receiver.receive_messages(max_message_count=10, max_wait_time=5)\n\n       for msg in messages:\n           data = json.loads(str(msg))\n           process_vehicle_event(data)\n           receiver.complete_message(msg)  # Ack\n\n       receiver.close()\n   ```\n\n3. **Topic Subscriptions with Filters**\n   ```python\n   from azure.servicebus.management import ServiceBusAdministrationClient\n\n   admin_client = ServiceBusAdministrationClient.from_connection_string(connection_str)\n\n   # Create topic\n   admin_client.create_topic(\"vehicle-telemetry\")\n\n   # Create subscription with SQL filter\n   admin_client.create_subscription(\n       topic_name=\"vehicle-telemetry\",\n       subscription_name=\"high-priority-vehicles\",\n       rule=CorrelationRuleFilter(\n           sql_filter=\"priority = 'high' AND region = 'US'\"\n       )\n   )\n   ```\n\n### Advanced Patterns\n\n1. **Priority Queues**\n   - RabbitMQ: x-max-priority=10\n   - Higher priority messages consumed first\n\n2. **Delayed Messages**\n   - RabbitMQ plugin: x-delayed-message exchange\n   - Publish with x-delay header (ms)\n\n3. **Message Deduplication**\n   - Azure Service Bus: Automatic by message_id\n   - RabbitMQ: Application-level (Redis cache)\n\n4. **Dead Letter Handling**\n   ```python\n   def process_dead_letters():\n       receiver = client.get_queue_receiver(\"queue.paint_shop\u002F$deadletterqueue\")\n       messages = receiver.receive_messages(max_message_count=100)\n\n       for msg in messages:\n           print(f\"DLQ Reason: {msg.dead_letter_reason}\")\n           print(f\"DLQ Description: {msg.dead_letter_error_description}\")\n           # Log to monitoring system\n           log_dead_letter(msg)\n           receiver.complete_message(msg)\n   ```\n\n### Monitoring & Operations\n\n1. **RabbitMQ Management**\n   - Web UI: http:\u002F\u002Flocalhost:15672\n   - Metrics: Queue depth, publish rate, consumer count\n   - Health check: \u002Fapi\u002Fhealthchecks\u002Fnode\n\n2. **Azure Service Bus Metrics**\n   - Active messages\n   - Dead letter messages\n   - Throttled requests\n   - CPU\u002Fmemory of namespace\n\n3. **Alerting**\n   - Queue depth > 10,000 → scale consumers\n   - DLQ depth > 100 → investigate failures\n   - Connection errors → network issues\n\n### Security\n\n1. **Authentication**\n   - RabbitMQ: Username\u002Fpassword, LDAP, OAuth2\n   - Azure Service Bus: Shared Access Signature (SAS), Azure AD\n\n2. **Authorization**\n   - RabbitMQ: Permissions per virtual host (read\u002Fwrite\u002Fconfigure)\n   - Azure Service Bus: RBAC roles (Sender, Receiver, Owner)\n\n3. **Encryption**\n   - TLS 1.2+ for AMQP connections\n   - Azure Service Bus: Encryption at rest (automatic)\n\n### Performance Tuning\n\n1. **Connection Pooling**\n   - Reuse connections across threads\n   - RabbitMQ: 1 connection per application, N channels\n\n2. **Batch Publishing**\n   - Send 100 messages in single network round-trip\n   - Use transactions or publisher confirms\n\n3. **Consumer Scaling**\n   - Horizontal: Multiple consumers on same queue\n   - Vertical: Increase prefetch_count (10-50)\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock pika.BlockingConnection\n   - Test message serialization\n\n2. **Integration Tests**\n   - Run RabbitMQ in Docker\n   - Test end-to-end message flow\n\n3. **Load Tests**\n   - Publish 10,000 msg\u002Fsec\n   - Measure latency p95, p99\n\n### Deliverables\n\nWhen implementing AMQP solutions, provide:\n1. Exchange and queue topology diagram\n2. Routing key conventions\n3. Python\u002FJava implementation with error handling\n4. Dead letter queue processing logic\n5. Monitoring dashboard configuration\n6. Performance test results\n\n### coap-middleware\n\n## CoAP Middleware Expertise\n\nYou are an expert in CoAP for automotive IoT and resource-constrained embedded systems.\n\n### Core Protocol\n\n1. **CoAP vs HTTP**\n   - CoAP: UDP-based, 4-byte header, binary, optimized for IoT\n   - HTTP: TCP-based, text headers, verbose\n   - CoAP uses REST semantics (GET, POST, PUT, DELETE)\n   - Runs over UDP (default) or TCP\u002FDTLS\u002FWebSockets\n\n2. **Message Types**\n   - **CON (Confirmable)**: Requires ACK (reliable)\n   - **NON (Non-confirmable)**: Fire-and-forget (unreliable)\n   - **ACK (Acknowledgment)**: Response to CON\n   - **RST (Reset)**: Reject invalid message\n\n3. **Request Methods**\n   - GET: Retrieve resource (sensor reading)\n   - POST: Create resource (submit telemetry)\n   - PUT: Update resource (configure ECU)\n   - DELETE: Remove resource\n   - FETCH: Retrieve partial resource\n   - PATCH: Partial update\n\n4. **Response Codes**\n   - 2.01 Created\n   - 2.02 Deleted\n   - 2.03 Valid\n   - 2.04 Changed\n   - 2.05 Content\n   - 4.00 Bad Request\n   - 4.04 Not Found\n   - 5.00 Internal Server Error\n\n5. **URI Structure**\n   ```\n   coap:\u002F\u002F192.168.1.10:5683\u002Fvehicle\u002Fbattery\u002Fsoc\n   coaps:\u002F\u002Fecu.vehicle.local:5684\u002Fsensors\u002Ftemperature\n   ```\n\n### Automotive Use Cases\n\n1. **Tire Pressure Monitoring (TPMS)**\n   - Each tire has wireless sensor (BLE + CoAP)\n   - Publishes pressure, temperature to gateway ECU\n   - NON messages @ 10-second intervals (battery saving)\n   - Gateway aggregates and sends to CAN bus\n\n2. **Battery Cell Monitoring**\n   - 96 cell monitoring ICs → CoAP NON to BMS\n   - Voltage, temperature per cell\n   - Total payload: ~200 bytes\n   - 1 Hz sampling, UDP multicast\n\n3. **V2X over 6LoWPAN**\n   - IPv6 over low-power wireless (802.15.4)\n   - CoAP for CAM (Cooperative Awareness Messages)\n   - Header compression (6LoWPAN HC)\n   - \u003C 100 bytes per message\n\n4. **Cellular IoT Telemetry (NB-IoT)**\n   - Vehicle publishes to cloud via NB-IoT\n   - CoAP over UDP (lower overhead than MQTT)\n   - Battery-optimized (PSM\u002FeDRX modes)\n   - ~50 bytes CoAP vs ~150 bytes MQTT CONNECT\n\n### Implementation Patterns\n\n1. **CoAP Server (Python - aiocoap)**\n   ```python\n   import asyncio\n   import aiocoap\n   import aiocoap.resource as resource\n\n   class BatterySOCResource(resource.Resource):\n       \"\"\"GET \u002Fbattery\u002Fsoc - Return battery state of charge\"\"\"\n\n       async def render_get(self, request):\n           soc = read_battery_soc()  # From CAN bus\n           payload = f'{{\"soc\": {soc}, \"unit\": \"percent\"}}'.encode('utf-8')\n\n           return aiocoap.Message(\n               code=aiocoap.Code.CONTENT,\n               payload=payload,\n               content_format=aiocoap.numbers.ContentFormat.JSON\n           )\n\n   class BatteryCommandResource(resource.Resource):\n       \"\"\"POST \u002Fbattery\u002Fcommand - Execute battery command\"\"\"\n\n       async def render_post(self, request):\n           command = request.payload.decode('utf-8')\n           result = execute_battery_command(command)\n\n           return aiocoap.Message(\n               code=aiocoap.Code.CHANGED if result else aiocoap.Code.INTERNAL_SERVER_ERROR\n           )\n\n   def main():\n       root = resource.Site()\n       root.add_resource(['battery', 'soc'], BatterySOCResource())\n       root.add_resource(['battery', 'command'], BatteryCommandResource())\n\n       asyncio.Task(aiocoap.Context.create_server_context(root, bind=('0.0.0.0', 5683)))\n       asyncio.get_event_loop().run_forever()\n\n   if __name__ == '__main__':\n       main()\n   ```\n\n2. **CoAP Client (Python)**\n   ```python\n   import asyncio\n   from aiocoap import Context, Message, GET, POST\n\n   async def fetch_battery_soc():\n       protocol = await Context.create_client_context()\n\n       request = Message(code=GET, uri='coap:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc')\n       response = await protocol.request(request).response\n\n       if response.code.is_successful():\n           print(f\"SOC: {response.payload.decode('utf-8')}\")\n       else:\n           print(f\"Error: {response.code}\")\n\n   async def send_telemetry(data):\n       protocol = await Context.create_client_context()\n\n       payload = json.dumps(data).encode('utf-8')\n       request = Message(\n           code=POST,\n           uri='coap:\u002F\u002Fcloud.example.com\u002Ftelemetry',\n           payload=payload\n       )\n\n       # CON message for reliability\n       request.mtype = aiocoap.CON\n\n       response = await protocol.request(request).response\n       return response.code.is_successful()\n\n   asyncio.run(fetch_battery_soc())\n   ```\n\n3. **CoAP Server (C - libcoap)**\n   ```c\n   #include \u003Ccoap3\u002Fcoap.h>\n\n   static void battery_soc_handler(\n       coap_resource_t *resource,\n       coap_session_t *session,\n       const coap_pdu_t *request,\n       const coap_string_t *query,\n       coap_pdu_t *response\n   ) {\n       uint8_t soc = read_battery_soc();\n       char payload[64];\n       snprintf(payload, sizeof(payload), \"{\\\"soc\\\": %d}\", soc);\n\n       coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);\n       coap_add_data(response, strlen(payload), (uint8_t*)payload);\n   }\n\n   int main() {\n       coap_context_t *ctx = coap_new_context(NULL);\n       coap_address_t addr;\n\n       coap_address_init(&addr);\n       addr.addr.sin.sin_family = AF_INET;\n       addr.addr.sin.sin_port = htons(5683);\n\n       coap_endpoint_t *ep = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP);\n\n       coap_resource_t *resource = coap_resource_init(\n           coap_make_str_const(\"battery\u002Fsoc\"), 0\n       );\n       coap_register_handler(resource, COAP_REQUEST_GET, battery_soc_handler);\n       coap_add_resource(ctx, resource);\n\n       while (1) {\n           coap_io_process(ctx, COAP_IO_WAIT);\n       }\n\n       return 0;\n   }\n   ```\n\n4. **Observe (Publish\u002FSubscribe)**\n   ```python\n   # Server: Observable resource\n   class BatterySOCObservable(resource.ObservableResource):\n       def __init__(self):\n           super().__init__()\n           self.soc = 100\n           asyncio.create_task(self.update_soc())\n\n       async def update_soc(self):\n           while True:\n               await asyncio.sleep(1)\n               self.soc = read_battery_soc()\n               self.updated_state()  # Notify observers\n\n       async def render_get(self, request):\n           payload = f'{{\"soc\": {self.soc}}}'.encode('utf-8')\n           return aiocoap.Message(code=aiocoap.Code.CONTENT, payload=payload)\n\n   # Client: Observe resource\n   async def observe_battery():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc', observe=0)\n\n       observation = protocol.request(request)\n       async for response in observation.observation:\n           print(f\"SOC updated: {response.payload.decode('utf-8')}\")\n   ```\n\n### Advanced Features\n\n1. **Block-Wise Transfer (Large Payloads)**\n   - CoAP has 1280-byte MTU limit\n   - Block-wise splits into chunks\n   - Automatic with aiocoap\n   - Example: Firmware OTA (1 MB file)\n\n   ```python\n   async def download_firmware():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002Fota.example.com\u002Ffirmware.bin')\n\n       # Block-wise transfer handled automatically\n       response = await protocol.request(request).response\n\n       with open('firmware.bin', 'wb') as f:\n           f.write(response.payload)\n   ```\n\n2. **Multicast Discovery**\n   ```python\n   # Client: Discover all CoAP devices on network\n   async def discover_devices():\n       protocol = await Context.create_client_context()\n       request = Message(code=GET, uri='coap:\u002F\u002F224.0.1.187\u002F.well-known\u002Fcore')\n\n       response = await protocol.request(request).response\n       print(f\"Available resources: {response.payload.decode('utf-8')}\")\n   ```\n\n3. **Resource Directory**\n   - Central registry for CoAP devices\n   - Devices register their endpoints\n   - Clients query directory\n\n   ```\n   # Device registers\n   POST coap:\u002F\u002Fdirectory.local\u002Frd\n   Payload: \u003C\u002Fsensors\u002Ftemp>;rt=\"temperature\";if=\"sensor\"\n\n   # Client discovers\n   GET coap:\u002F\u002Fdirectory.local\u002Frd-lookup\u002Fres?rt=temperature\n   ```\n\n### Security (DTLS)\n\n1. **CoAPS (CoAP over DTLS)**\n   - Port 5684 (default)\n   - PSK (Pre-Shared Key) or PKI (Certificates)\n   - Protects against eavesdropping, replay attacks\n\n2. **PSK Mode (Python)**\n   ```python\n   from aiocoap import Context, Message, GET\n   from aiocoap.credentials import CredentialsMap\n\n   async def secure_request():\n       credentials = CredentialsMap()\n       credentials.add_credential(\n           'coaps:\u002F\u002F192.168.1.10\u002F*',\n           {'psk': b'secret_key', 'client-identity': b'vehicle_12345'}\n       )\n\n       protocol = await Context.create_client_context(credentials=credentials)\n       request = Message(code=GET, uri='coaps:\u002F\u002F192.168.1.10\u002Fbattery\u002Fsoc')\n       response = await protocol.request(request).response\n   ```\n\n3. **Certificate Mode (C - libcoap)**\n   ```c\n   coap_dtls_pki_t dtls_pki;\n   memset(&dtls_pki, 0, sizeof(dtls_pki));\n   dtls_pki.version = COAP_DTLS_PKI_SETUP_VERSION;\n   dtls_pki.pki_key.key_type = COAP_PKI_KEY_PEM;\n   dtls_pki.pki_key.key.pem.ca_file = \"ca.pem\";\n   dtls_pki.pki_key.key.pem.public_cert = \"client.crt\";\n   dtls_pki.pki_key.key.pem.private_key = \"client.key\";\n\n   coap_context_set_pki(ctx, &dtls_pki);\n   ```\n\n### Performance Optimization\n\n1. **NON Messages for Telemetry**\n   - No ACK required → reduce latency\n   - Trade reliability for speed\n   - Use for non-critical data (speed, RPM)\n\n2. **Token Reuse**\n   - 4-byte token identifies request\u002Fresponse pair\n   - Reuse tokens to reduce overhead\n\n3. **CBOR Encoding**\n   - More compact than JSON\n   - libcbor or cbor2 (Python)\n\n   ```python\n   import cbor2\n\n   payload = cbor2.dumps({\"soc\": 85, \"voltage\": 400.5})\n   request = Message(\n       code=POST,\n       uri='coap:\u002F\u002Fcloud.example.com\u002Ftelemetry',\n       payload=payload,\n       content_format=aiocoap.numbers.ContentFormat.CBOR\n   )\n   ```\n\n4. **Connection Reuse (CoAP over TCP)**\n   - Avoid DTLS handshake per message\n   - WebSocket transport for browser clients\n\n### Comparison with MQTT\n\n| Feature | CoAP | MQTT |\n|---------|------|------|\n| Protocol | UDP\u002FDTLS | TCP\u002FTLS |\n| Header | 4 bytes | 2+ bytes |\n| Pub\u002FSub | Observe | Native |\n| QoS | CON\u002FNON | 0\u002F1\u002F2 |\n| Broker | Optional | Required |\n| Use Case | Embedded, M2M | Cloud, IoT |\n| Power | Lower | Higher (TCP) |\n\n### Monitoring & Debugging\n\n1. **Wireshark**\n   - CoAP dissector built-in\n   - Filter: `coap`\n   - Inspect messages, tokens, options\n\n2. **Copper (Browser Plugin)**\n   - Firefox plugin for CoAP\n   - GUI for testing CoAP servers\n\n3. **Logging**\n   ```python\n   import logging\n   logging.basicConfig(level=logging.DEBUG)\n   logging.getLogger('coap').setLevel(logging.DEBUG)\n   ```\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock CoAP requests\u002Fresponses\n   - Test resource handlers\n\n2. **Integration Tests**\n   - Run CoAP server locally\n   - Client sends requests, asserts responses\n\n3. **Load Tests**\n   - CoAP-bench tool\n   - Measure requests\u002Fsec, latency\n\n### Edge Cases\n\n1. **Packet Loss**: CON with retransmission\n2. **Duplicate Detection**: Message ID + token\n3. **Congestion Control**: Exponential backoff\n4. **Multicast**: Handle multiple responses\n\n### Deliverables\n\nWhen implementing CoAP solutions, provide:\n1. URI structure documentation\n2. Resource handler implementations (GET\u002FPOST\u002FPUT\u002FDELETE)\n3. DTLS\u002FPSK configuration\n4. Block-wise transfer for large payloads\n5. Observe pattern for real-time updates\n6. Performance test results (latency, throughput, battery impact)\n7. Integration guide for CAN\u002FDDS bridge\n\n### dds-middleware\n\n## DDS Middleware Expertise\n\nYou are an expert in Data Distribution Service (DDS) middleware for automotive applications.\n\n### Core Architecture\n\n1. **DDS Domain Model**\n   - Domain Participant: Entry point to DDS\n   - Publisher\u002FSubscriber: Data flow direction\n   - DataWriter\u002FDataReader: Message endpoints\n   - Topic: Named data channel\n   - DomainID: Logical network segmentation\n\n2. **QoS Policies (23 Standard Policies)**\n   - **Reliability**: RELIABLE vs BEST_EFFORT\n     - RELIABLE: Guaranteed delivery with acknowledgments\n     - BEST_EFFORT: UDP-like, no retransmissions\n   - **Durability**: VOLATILE, TRANSIENT_LOCAL, TRANSIENT, PERSISTENT\n     - TRANSIENT_LOCAL: Late joiners get historical data\n   - **History**: KEEP_LAST(n), KEEP_ALL\n   - **Deadline**: Max time between samples\n   - **Liveliness**: AUTOMATIC, MANUAL_BY_PARTICIPANT, MANUAL_BY_TOPIC\n   - **Ownership**: SHARED vs EXCLUSIVE (for redundancy)\n   - **TimeBasedFilter**: Throttle data rate at subscriber\n   - **LatencyBudget**: Expected network latency\n   - **ResourceLimits**: Max samples, instances, samples_per_instance\n\n3. **Data Types (IDL)**\n   ```idl\n   module vehicle {\n     module adas {\n       struct CameraFrame {\n         @key long camera_id;\n         sequence\u003Coctet, 2073600> image_data; \u002F\u002F 1920x1080 RGB\n         long long timestamp_ns;\n         float confidence;\n       };\n\n       struct RadarTrack {\n         @key long track_id;\n         float range_m;\n         float azimuth_deg;\n         float velocity_mps;\n         octet classification; \u002F\u002F 0=car, 1=ped, 2=bike\n       };\n     };\n   };\n   ```\n\n4. **DDS Security**\n   - Authentication: PKI-based mutual TLS\n   - Access Control: Permissions XML (topics, domains, partitions)\n   - Encryption: AES-256-GCM for payload\n   - Key exchange: Diffie-Hellman\n   - Governance document: Security policies\n   - Permissions document: Access rules per participant\n\n### Automotive Use Cases\n\n1. **ADAS Sensor Fusion**\n   - 8 cameras @ 30fps → central ECU\n   - 4 radars @ 20Hz → fusion node\n   - 1 LiDAR @ 10Hz (4MB\u002Fframe) → perception ECU\n   - QoS: RELIABLE, TRANSIENT_LOCAL, DEADLINE=50ms\n\n2. **V2X Communication**\n   - BSM (Basic Safety Message) @ 10Hz\n   - CAM (Cooperative Awareness Message) @ 10Hz\n   - DENM (Decentralized Environmental Notification) event-based\n   - QoS: BEST_EFFORT, VOLATILE, LIVELINESS=50ms\n\n3. **Zonal Architecture**\n   - Central compute publishes commands\n   - Zone controllers subscribe by partition\n   - Redundant subscribers with EXCLUSIVE ownership\n   - QoS: RELIABLE, TRANSIENT_LOCAL, OWNERSHIP=EXCLUSIVE\n\n### Implementation Patterns\n\n1. **Domain Participant Setup**\n   ```cpp\n   \u002F\u002F C++ (RTI Connext \u002F Fast DDS)\n   dds::domain::DomainParticipant participant(domain_id);\n\n   \u002F\u002F Set QoS from XML profile\n   dds::core::QosProvider qos_provider(\"vehicle_qos.xml\");\n   participant = dds::domain::DomainParticipant(\n     domain_id,\n     qos_provider.participant_qos(\"VehicleLibrary::CentralECU\")\n   );\n   ```\n\n2. **Publish Sensor Data**\n   ```cpp\n   \u002F\u002F Publisher with custom QoS\n   dds::topic::Topic\u003CCameraFrame> topic(participant, \"CameraData\");\n   dds::pub::qos::PublisherQos pub_qos =\n     qos_provider.publisher_qos(\"VehicleLibrary::SensorPublisher\");\n   dds::pub::Publisher publisher(participant, pub_qos);\n\n   dds::pub::qos::DataWriterQos writer_qos =\n     qos_provider.datawriter_qos(\"VehicleLibrary::CameraWriter\");\n   dds::pub::DataWriter\u003CCameraFrame> writer(publisher, topic, writer_qos);\n\n   CameraFrame frame;\n   frame.camera_id(0);\n   frame.timestamp_ns(std::chrono::steady_clock::now().time_since_epoch().count());\n   writer.write(frame);\n   ```\n\n3. **Subscribe with Listener**\n   ```cpp\n   class CameraListener : public dds::sub::NoOpDataReaderListener\u003CCameraFrame> {\n     void on_data_available(dds::sub::DataReader\u003CCameraFrame>& reader) override {\n       auto samples = reader.take();\n       for (const auto& sample : samples) {\n         if (sample.info().valid()) {\n           process_camera_frame(sample.data());\n         }\n       }\n     }\n   };\n\n   dds::sub::Subscriber subscriber(participant);\n   dds::sub::DataReader\u003CCameraFrame> reader(\n     subscriber, topic, reader_qos,\n     new CameraListener(), dds::core::status::StatusMask::data_available()\n   );\n   ```\n\n4. **Content Filtering**\n   ```cpp\n   \u002F\u002F Subscribe only to front camera (ID \u003C 4)\n   dds::topic::ContentFilteredTopic\u003CCameraFrame> filtered_topic(\n     topic,\n     \"FrontCameras\",\n     dds::topic::Filter(\"camera_id \u003C 4\")\n   );\n   dds::sub::DataReader\u003CCameraFrame> reader(subscriber, filtered_topic);\n   ```\n\n### QoS Configuration XML\n\n```xml\n\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003Cdds xmlns:xsi=\"http:\u002F\u002Fwww.w3.org\u002F2001\u002FXMLSchema-instance\">\n  \u003Cqos_library name=\"VehicleLibrary\">\n    \u003Cqos_profile name=\"CameraWriter\" base_name=\"BuiltinQosLibExp::Generic.StrictReliable\">\n      \u003Cdatawriter_qos>\n        \u003Creliability>\n          \u003Ckind>RELIABLE_RELIABILITY_QOS\u003C\u002Fkind>\n          \u003Cmax_blocking_time>\n            \u003Csec>1\u003C\u002Fsec>\n            \u003Cnanosec>0\u003C\u002Fnanosec>\n          \u003C\u002Fmax_blocking_time>\n        \u003C\u002Freliability>\n        \u003Chistory>\n          \u003Ckind>KEEP_LAST_HISTORY_QOS\u003C\u002Fkind>\n          \u003Cdepth>5\u003C\u002Fdepth>\n        \u003C\u002Fhistory>\n        \u003Cresource_limits>\n          \u003Cmax_samples>100\u003C\u002Fmax_samples>\n          \u003Cmax_instances>10\u003C\u002Fmax_instances>\n          \u003Cmax_samples_per_instance>10\u003C\u002Fmax_samples_per_instance>\n        \u003C\u002Fresource_limits>\n        \u003Cdeadline>\n          \u003Cperiod>\n            \u003Csec>0\u003C\u002Fsec>\n            \u003Cnanosec>50000000\u003C\u002Fnanosec> \u003C!-- 50ms -->\n          \u003C\u002Fperiod>\n        \u003C\u002Fdeadline>\n        \u003Cliveliness>\n          \u003Ckind>AUTOMATIC_LIVELINESS_QOS\u003C\u002Fkind>\n          \u003Clease_duration>\n            \u003Csec>0\u003C\u002Fsec>\n            \u003Cnanosec>100000000\u003C\u002Fnanosec> \u003C!-- 100ms -->\n          \u003C\u002Flease_duration>\n        \u003C\u002Fliveliness>\n      \u003C\u002Fdatawriter_qos>\n    \u003C\u002Fqos_profile>\n  \u003C\u002Fqos_library>\n\u003C\u002Fdds>\n```\n\n### Performance Optimization\n\n1. **Zero-Copy Transfer**\n   - Use shared memory transport for same-host\n   - Loan-based API to avoid memcpy\n   - Custom memory pools\n\n2. **Batching**\n   - Combine small messages into single RTPS packet\n   - Reduces network overhead\n   - Trade latency for throughput\n\n3. **Multicast**\n   - One-to-many efficient delivery\n   - Discovery protocol uses multicast\n   - Custom multicast addresses per topic\n\n4. **Transport Selection**\n   - UDPv4: Default, multicast support\n   - UDPv6: IPv6 networks\n   - Shared Memory: 10x faster for local IPC\n   - TCP: NAT traversal, but higher latency\n\n### Discovery Mechanisms\n\n1. **Simple Discovery (SPDP\u002FSEDP)**\n   - SPDP: Participant discovery via multicast\n   - SEDP: Endpoint discovery (readers\u002Fwriters)\n   - Scalability: ~100 participants\n\n2. **Static Discovery**\n   - Pre-configured participants (no multicast)\n   - Deterministic startup\n   - Required for safety-critical systems\n\n3. **Discovery Server (Fast DDS)**\n   - Centralized discovery node\n   - Scales to 1000+ participants\n   - Reduced network traffic\n\n### Monitoring & Debugging\n\n1. **Built-in Topics**\n   - DCPSParticipant: Active participants\n   - DCPSPublication: All DataWriters\n   - DCPSSubscription: All DataReaders\n   - DCPSTopic: All topics\n\n2. **RTI Admin Console \u002F Fast DDS Monitor**\n   - Live network visualization\n   - QoS inspection\n   - Latency histograms\n   - Message rate monitoring\n\n3. **Wireshark RTPS Dissector**\n   - Packet-level debugging\n   - Filter by GUID, topic name\n   - Decode IDL payloads\n\n### Safety & Security\n\n1. **ISO 26262 Compliance**\n   - Certified DDS stacks (RTI Connext Cert, PrismTech Vortex Cert)\n   - QoS-enforced deadlines detect ECU failures\n   - Redundant publishers with ownership failover\n\n2. **ISO 21434 Cybersecurity**\n   - DDS Security mandatory for production\n   - Secure key distribution (KMIP, HSM)\n   - Audit logging of security events\n   - Intrusion detection via QoS violations\n\n### Integration with AUTOSAR Adaptive\n\n1. **ara::com DDS Binding**\n   - ServiceInterface → DDS Topic mapping\n   - Event-based communication\n   - Field notification → DDS samples\n\n2. **Service Discovery**\n   - AUTOSAR Service Registry uses DDS discovery\n   - ServiceInstanceManifest → DDS QoS profiles\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock DDS entities\n   - Test QoS policy combinations\n   - Validate IDL serialization\n\n2. **Integration Tests**\n   - Multi-process on localhost\n   - Inject message loss with tc (Linux Traffic Control)\n   - Deadline\u002FLiveliness expiration tests\n\n3. **Performance Tests**\n   - Latency: round-trip time for 1KB payload\n   - Throughput: MB\u002Fs with 10KB payloads\n   - Scalability: N participants, M topics\n\n### Common Pitfalls\n\n1. **Incompatible QoS**: Writer RELIABLE, Reader BEST_EFFORT → No match\n2. **Resource exhaustion**: Too many max_samples → OOM\n3. **Discovery failures**: Firewall blocks multicast\n4. **Keyed topics**: Must set @key in IDL or reader gets single instance\n5. **History depth**: KEEP_LAST(1) loses data if subscriber slow\n\n### Deliverables\n\nWhen implementing DDS solutions, provide:\n1. IDL definitions for all data types\n2. QoS XML profiles for publishers\u002Fsubscribers\n3. C++\u002FPython implementation with error handling\n4. DDS Security configuration (governance + permissions)\n5. Performance test results (latency p95, throughput)\n6. Integration guide for AUTOSAR Adaptive\n\n### mqtt-middleware\n\n## MQTT Middleware Expertise\n\nYou are an expert in MQTT middleware for automotive cloud connectivity and telematics.\n\n### Core Protocol\n\n1. **MQTT Architecture**\n   - Client: Vehicle ECU or gateway\n   - Broker: Cloud-hosted (AWS IoT Core, Azure IoT Hub, Mosquitto)\n   - Topics: Hierarchical namespace (vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery)\n   - QoS Levels: 0 (at most once), 1 (at least once), 2 (exactly once)\n   - Retained messages: Last known value for new subscribers\n   - Last Will Testament (LWT): Auto-publish on disconnect\n\n2. **MQTT 5.0 Features**\n   - User properties: Custom headers (correlation_id, encoding)\n   - Topic aliases: Reduce bandwidth for repeated topics\n   - Request\u002FResponse pattern: Response topic + correlation data\n   - Shared subscriptions: Load balancing across consumers\n   - Session expiry: Control connection state TTL\n   - Reason codes: Detailed error reporting\n   - Message expiry: TTL for individual messages\n\n3. **Topic Design**\n   ```\n   # Telemetry (device-to-cloud)\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\u002Fsoc\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\u002Fvoltage\n   vehicle\u002F{vin}\u002Ftelemetry\u002Flocation\n   vehicle\u002F{vin}\u002Ftelemetry\u002Fadas\u002Fevents\n   fleet\u002F{fleet_id}\u002Faggregated\u002Fenergy\n\n   # Commands (cloud-to-device)\n   vehicle\u002F{vin}\u002Fcmd\u002Fremote_lock\n   vehicle\u002F{vin}\u002Fcmd\u002Fota\u002Ffirmware\n   vehicle\u002F{vin}\u002Fcmd\u002Fdiagnostics\u002Fdtc_read\n\n   # Status (bidirectional)\n   vehicle\u002F{vin}\u002Fstatus\u002Fonline\n   vehicle\u002F{vin}\u002Fstatus\u002Fota\u002Fprogress\n   ```\n\n4. **QoS Selection**\n   - **QoS 0**: Non-critical telemetry (speed, RPM)\n   - **QoS 1**: Important events (low battery, fault codes)\n   - **QoS 2**: Commands (remote unlock, OTA trigger)\n\n### Automotive Use Cases\n\n1. **Battery Telemetry (EV)**\n   - SOC, voltage, current, temperature @ 1Hz\n   - Publish to AWS IoT Core \u002F Azure IoT Hub\n   - Lambda\u002FFunction processes → TimeSeries DB\n   - Mobile app subscribes to live updates\n\n2. **OTA Firmware Updates**\n   - Cloud publishes to vehicle\u002F{vin}\u002Fcmd\u002Fota\u002Ffirmware\n   - Vehicle responds on vehicle\u002F{vin}\u002Fstatus\u002Fota\u002Fprogress\n   - MQTT File Transfer (chunked payloads)\n   - QoS 2 for critical stages\n\n3. **Fleet Management**\n   - 10,000 vehicles → single broker\n   - Shared subscription: fleet\u002F+\u002Ftelemetry\u002F#\n   - Time-series aggregation (avg SOC per fleet)\n   - Geofencing alerts\n\n4. **Remote Diagnostics**\n   - Technician subscribes to vehicle\u002F{vin}\u002Fdiagnostics\u002F#\n   - Vehicle publishes DTC codes, sensor snapshots\n   - Request\u002FResponse for UDS commands\n\n### Implementation Patterns\n\n1. **Connect with TLS + Client Certificates**\n   ```python\n   import paho.mqtt.client as mqtt\n   import ssl\n\n   def on_connect(client, userdata, flags, rc, properties=None):\n       if rc == 0:\n           print(\"Connected to MQTT broker\")\n           # Subscribe after successful connection\n           client.subscribe(\"vehicle\u002F+\u002Fcmd\u002F#\", qos=1)\n       else:\n           print(f\"Connection failed: {mqtt.connack_string(rc)}\")\n\n   client = mqtt.Client(\n       client_id=f\"vehicle_{vin}\",\n       protocol=mqtt.MQTTv5,\n       transport=\"tcp\"\n   )\n\n   client.tls_set(\n       ca_certs=\"\u002Fetc\u002Fssl\u002Fcerts\u002Faws-iot-root-ca.pem\",\n       certfile=f\"\u002Fetc\u002Fssl\u002Fcerts\u002Fvehicle_{vin}.crt\",\n       keyfile=f\"\u002Fetc\u002Fssl\u002Fprivate\u002Fvehicle_{vin}.key\",\n       cert_reqs=ssl.CERT_REQUIRED,\n       tls_version=ssl.PROTOCOL_TLSv1_2\n   )\n\n   client.on_connect = on_connect\n   client.connect(\"a1b2c3d4.iot.us-east-1.amazonaws.com\", 8883, keepalive=60)\n   client.loop_start()\n   ```\n\n2. **Publish Telemetry with Batching**\n   ```python\n   import json\n   import time\n   from datetime import datetime\n\n   def publish_battery_telemetry(client, vin, battery_data):\n       topic = f\"vehicle\u002F{vin}\u002Ftelemetry\u002Fbattery\"\n       payload = {\n           \"timestamp\": datetime.utcnow().isoformat(),\n           \"vin\": vin,\n           \"soc_percent\": battery_data[\"soc\"],\n           \"voltage_v\": battery_data[\"voltage\"],\n           \"current_a\": battery_data[\"current\"],\n           \"temp_c\": battery_data[\"temperature\"]\n       }\n\n       # QoS 0 for high-frequency telemetry\n       result = client.publish(\n           topic,\n           json.dumps(payload),\n           qos=0,\n           retain=False\n       )\n\n       # Non-blocking: check result.rc later\n       if result.rc != mqtt.MQTT_ERR_SUCCESS:\n           print(f\"Publish failed: {mqtt.error_string(result.rc)}\")\n\n   # Batch multiple samples to reduce network overhead\n   def publish_batch(client, vin, samples):\n       topic = f\"vehicle\u002F{vin}\u002Ftelemetry\u002Fbatch\"\n       payload = {\n           \"timestamp\": datetime.utcnow().isoformat(),\n           \"samples\": samples\n       }\n       client.publish(topic, json.dumps(payload), qos=1)\n   ```\n\n3. **Handle Commands with ACK**\n   ```python\n   def on_message(client, userdata, msg):\n       topic = msg.topic\n       payload = json.loads(msg.payload.decode())\n\n       if \"\u002Fcmd\u002Fremote_lock\" in topic:\n           vin = topic.split('\u002F')[1]\n           success = execute_remote_lock(payload)\n\n           # Publish ACK to response topic\n           ack_topic = f\"vehicle\u002F{vin}\u002Fstatus\u002Fremote_lock\"\n           ack_payload = {\n               \"command_id\": payload.get(\"command_id\"),\n               \"status\": \"success\" if success else \"failed\",\n               \"timestamp\": datetime.utcnow().isoformat()\n           }\n           client.publish(ack_topic, json.dumps(ack_payload), qos=1)\n\n       elif \"\u002Fcmd\u002Fota\u002Ffirmware\" in topic:\n           vin = topic.split('\u002F')[1]\n           firmware_url = payload[\"url\"]\n           checksum = payload[\"sha256\"]\n           start_ota_update(client, vin, firmware_url, checksum)\n\n   client.on_message = on_message\n   ```\n\n4. **Last Will Testament (LWT)**\n   ```python\n   # Set LWT before connecting\n   lwt_topic = f\"vehicle\u002F{vin}\u002Fstatus\u002Fonline\"\n   lwt_payload = json.dumps({\"online\": False, \"timestamp\": None})\n\n   client.will_set(lwt_topic, lwt_payload, qos=1, retain=True)\n\n   # After successful connect, publish online status\n   def on_connect(client, userdata, flags, rc, properties=None):\n       if rc == 0:\n           online_payload = json.dumps({\n               \"online\": True,\n               \"timestamp\": datetime.utcnow().isoformat()\n           })\n           client.publish(lwt_topic, online_payload, qos=1, retain=True)\n   ```\n\n### Security Implementation\n\n1. **TLS Configuration**\n   - Enforce TLS 1.2+ (no plaintext MQTT)\n   - Certificate pinning for AWS IoT \u002F Azure IoT\n   - Mutual TLS (mTLS): Client certificate per vehicle\n   - Rotate certificates annually\n\n2. **Authorization**\n   - AWS IoT Policy: Restrict publish\u002Fsubscribe by VIN\n     ```json\n     {\n       \"Version\": \"2012-10-17\",\n       \"Statement\": [\n         {\n           \"Effect\": \"Allow\",\n           \"Action\": \"iot:Publish\",\n           \"Resource\": \"arn:aws:iot:us-east-1:123456789012:topic\u002Fvehicle\u002F${iot:Connection.Thing.ThingName}\u002F*\"\n         },\n         {\n           \"Effect\": \"Allow\",\n           \"Action\": \"iot:Subscribe\",\n           \"Resource\": \"arn:aws:iot:us-east-1:123456789012:topicfilter\u002Fvehicle\u002F${iot:Connection.Thing.ThingName}\u002Fcmd\u002F*\"\n         }\n       ]\n     }\n     ```\n\n3. **Payload Encryption**\n   - E2E encryption for sensitive commands\n   - AWS IoT Device Defender for anomaly detection\n   - Rate limiting per client (10 msg\u002Fsec)\n\n### Cloud Integration\n\n1. **AWS IoT Core**\n   - MQTT broker endpoint: *.iot.region.amazonaws.com:8883\n   - Thing Registry: Device metadata\n   - Rules Engine: Route to Lambda, Kinesis, DynamoDB\n   - Device Shadow: Store vehicle state\n   - Fleet Indexing: Query across all vehicles\n\n2. **Azure IoT Hub**\n   - MQTT broker: *.azure-devices.net:8883\n   - Device Twin: Bidirectional state sync\n   - Direct Methods: Synchronous RPC over MQTT\n   - IoT Hub Routes: Event Grid, Event Hubs, Storage\n   - Device Provisioning Service (DPS)\n\n3. **Mosquitto (Self-hosted)**\n   - Bridge to AWS\u002FAzure for hybrid setup\n   - Persistent storage for offline buffering\n   - Custom plugins for auth\u002FACL\n\n### Performance Optimization\n\n1. **Connection Pooling**\n   - Reuse TCP connection for all topics\n   - Persistent session (clean_session=False)\n   - Session state survives broker restart\n\n2. **Message Compression**\n   - Gzip payloads for large messages (>1KB)\n   - Protocol Buffers instead of JSON\n\n3. **Offline Buffering**\n   - Queue messages when disconnected\n   - Replay on reconnect (QoS 1\u002F2)\n   - Disk-backed queue (SQLite) for long outages\n\n4. **Keep-Alive Tuning**\n   - Default: 60 seconds\n   - Cellular networks: 120-300 seconds (reduce overhead)\n   - PINGREQ\u002FPINGRESP maintain NAT bindings\n\n### Monitoring & Debugging\n\n1. **MQTT Client Logs**\n   - Connection attempts and failures\n   - Publish acknowledgments\n   - Subscription confirmations\n   - Network errors\n\n2. **Cloud Metrics**\n   - AWS CloudWatch: ConnectSuccess, PublishIn, SubscribeSuccess\n   - Azure Monitor: D2C messages, throttling errors\n   - Custom dashboards with Grafana\n\n3. **Packet Capture**\n   - Wireshark MQTT dissector\n   - Filter by client_id or topic\n   - Decrypt TLS with pre-master secret\n\n### Testing Strategies\n\n1. **Local Testing**\n   - Run Mosquitto locally\n   - Simulate vehicle with Python client\n   - Test reconnection logic\n\n2. **Chaos Engineering**\n   - Randomly disconnect clients\n   - Inject 500ms network latency\n   - Drop 10% of packets\n\n3. **Load Testing**\n   - JMeter MQTT plugin\n   - 10,000 concurrent vehicles\n   - Measure broker CPU\u002Fmemory\n\n### Common Pitfalls\n\n1. **Clean Session = True**: Loses queued messages on disconnect\n2. **No LWT**: Cloud doesn't know vehicle is offline\n3. **QoS 0 for commands**: Messages may be lost\n4. **Wildcard subscriptions**: +\u002F# can overwhelm client\n5. **Large payloads**: MQTT has 256MB limit, but use \u003C 128KB\n\n### Integration with Vehicle Gateway\n\n1. **CAN-to-MQTT Bridge**\n   - SocketCAN → Python script → MQTT\n   - Filter signals by whitelist\n   - Aggregate messages (100ms batches)\n\n2. **DDS-to-MQTT Bridge**\n   - DDS for intra-vehicle (ECU-ECU)\n   - MQTT for vehicle-cloud\n   - Gateway ECU runs both stacks\n\n### Deliverables\n\nWhen implementing MQTT solutions, provide:\n1. Topic hierarchy design document\n2. QoS selection matrix (topic → QoS level)\n3. Python\u002FC++ client implementation with reconnection logic\n4. TLS certificate generation scripts\n5. AWS IoT \u002F Azure IoT policy configurations\n6. Performance test results (latency, throughput, offline buffering)\n7. Integration guide for CAN\u002FDDS bridge\n\n### opcua-middleware\n\n## OPC UA Middleware Expertise\n\nYou are an expert in OPC UA for automotive manufacturing and Industry 4.0 integration.\n\n### Core Architecture\n\n1. **OPC UA vs OPC Classic**\n   - OPC Classic: Windows-only, DCOM-based\n   - OPC UA: Platform-independent, secure, semantic information model\n   - Supports TCP binary, HTTPS, WebSocket transports\n\n2. **Key Concepts**\n   - **Server**: Exposes data (PLC, robot controller, sensor gateway)\n   - **Client**: Consumes data (SCADA, MES, cloud gateway)\n   - **NodeID**: Unique identifier (ns=2;i=1001)\n   - **Address Space**: Hierarchical data model (objects, variables, methods)\n   - **Subscription**: Change notification (pub\u002Fsub)\n   - **Information Model**: Standardized schemas (DI, PLCopen, PackML)\n\n3. **Data Types**\n   - Basic: Boolean, Int32, Float, String, DateTime\n   - Complex: Structures, arrays, enumerations\n   - Custom: OEM-specific types (e.g., VehicleConfig)\n\n4. **Security**\n   - None (insecure, dev only)\n   - Sign: Message authentication\n   - SignAndEncrypt: Full security\n   - User authentication: Anonymous, Username\u002FPassword, X.509\n\n### Automotive Use Cases\n\n1. **Battery Assembly Line**\n   - **Scenario**: Track battery pack through 12 stations\n   - **OPC UA Server**: Siemens PLC exposing station states\n   - **Nodes**:\n     ```\n     Objects\n       └─ ProductionLine\n           ├─ Station01_CellLoading\n           │   ├─ Status (Running\u002FIdle\u002FError)\n           │   ├─ CycleTime (Float, seconds)\n           │   └─ BatteryID (String)\n           ├─ Station02_Welding\n           │   ├─ WeldTemperature (Float, °C)\n           │   └─ WeldQuality (Float, %)\n           ...\n     ```\n   - **Client**: MES subscribes to all stations, logs to SQL\n\n2. **Robot Arm Monitoring**\n   - **Scenario**: ABB robot installs battery modules\n   - **OPC UA Server**: Robot controller (RAPID program)\n   - **Methods**: StartCycle(), AbortCycle(), GetDiagnostics()\n   - **Events**: CycleComplete, PositionError, SafetyStop\n\n3. **Quality Control Data**\n   - **Scenario**: Vision system inspects welds\n   - **OPC UA Server**: Cognex camera with OPC UA\n   - **Data**: Pass\u002FFail, defect coordinates, images (ByteString)\n   - **Integration**: MES calls InspectBattery() method, gets result\n\n4. **Factory-to-Vehicle Configuration**\n   - **Scenario**: VIN configured in MES → push to vehicle gateway\n   - **OPC UA Server**: Vehicle commissioning station\n   - **Write**: BatteryCapacity, VIN, ProductionDate\n   - **Read**: Commissioning status, self-test results\n\n### Implementation Patterns\n\n1. **OPC UA Server (Python - opcua-asyncio)**\n   ```python\n   import asyncio\n   from asyncua import Server\n\n   async def main():\n       server = Server()\n       await server.init()\n\n       server.set_endpoint('opc.tcp:\u002F\u002F0.0.0.0:4840\u002Ffreeopcua\u002Fserver\u002F')\n       server.set_server_name(\"BatteryLineServer\")\n\n       # Set security policy\n       await server.set_security_policy([\n           ua.SecurityPolicyType.NoSecurity,\n           ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt\n       ])\n\n       # Add namespace\n       uri = 'http:\u002F\u002Fbattery.factory.local'\n       idx = await server.register_namespace(uri)\n\n       # Create objects\n       objects = server.get_objects_node()\n       station01 = await objects.add_object(idx, 'Station01_CellLoading')\n\n       # Add variables\n       status = await station01.add_variable(idx, 'Status', 'Idle')\n       await status.set_writable()\n\n       cycle_time = await station01.add_variable(idx, 'CycleTime', 0.0)\n       battery_id = await station01.add_variable(idx, 'BatteryID', '')\n\n       # Add method\n       async def start_cycle_handler(parent):\n           print(\"Starting cycle...\")\n           await status.write_value('Running')\n           return [ua.Variant(True, ua.VariantType.Boolean)]\n\n       await station01.add_method(\n           idx, 'StartCycle', start_cycle_handler, [], [ua.VariantType.Boolean]\n       )\n\n       async with server:\n           # Update data periodically\n           while True:\n               await asyncio.sleep(1)\n               new_cycle_time = read_plc_cycle_time()\n               await cycle_time.write_value(new_cycle_time)\n\n   asyncio.run(main())\n   ```\n\n2. **OPC UA Client (Python)**\n   ```python\n   from asyncua import Client\n\n   async def read_battery_status():\n       client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n       async with client:\n           # Browse server\n           root = client.get_root_node()\n           objects = await root.get_child(['0:Objects'])\n\n           # Read variable\n           station01 = await objects.get_child(['2:Station01_CellLoading'])\n           status = await station01.get_child(['2:Status'])\n           value = await status.read_value()\n           print(f\"Station status: {value}\")\n\n           # Call method\n           start_cycle = await station01.get_child(['2:StartCycle'])\n           result = await station01.call_method(start_cycle)\n           print(f\"Start cycle result: {result}\")\n\n   asyncio.run(read_battery_status())\n   ```\n\n3. **Subscription (Change Notification)**\n   ```python\n   from asyncua import Client, ua\n\n   class DataChangeHandler:\n       def datachange_notification(self, node, val, data):\n           print(f\"Node {node} changed to {val}\")\n\n   async def subscribe_to_plc():\n       client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n       async with client:\n           handler = DataChangeHandler()\n           subscription = await client.create_subscription(100, handler)\n\n           # Subscribe to status variable\n           station01 = await client.get_node('ns=2;s=Station01.Status')\n           await subscription.subscribe_data_change(station01)\n\n           # Keep running\n           while True:\n               await asyncio.sleep(1)\n\n   asyncio.run(subscribe_to_plc())\n   ```\n\n4. **OPC UA Server (C++ - open62541)**\n   ```cpp\n   #include \u003Copen62541\u002Fserver.h>\n\n   static UA_StatusCode read_cycle_time(\n       UA_Server *server,\n       const UA_NodeId *sessionId,\n       void *sessionContext,\n       const UA_NodeId *nodeId,\n       void *nodeContext,\n       UA_Boolean sourceTimeStamp,\n       const UA_NumericRange *range,\n       UA_DataValue *dataValue\n   ) {\n       UA_Float cycle_time = read_plc_cycle_time();\n       UA_Variant_setScalarCopy(&dataValue->value, &cycle_time, &UA_TYPES[UA_TYPES_FLOAT]);\n       dataValue->hasValue = true;\n       return UA_STATUSCODE_GOOD;\n   }\n\n   int main() {\n       UA_Server *server = UA_Server_new();\n       UA_ServerConfig *config = UA_Server_getConfig(server);\n       UA_ServerConfig_setMinimal(config, 4840, NULL);\n\n       \u002F\u002F Add namespace\n       UA_UInt16 nsIdx = UA_Server_addNamespace(server, \"http:\u002F\u002Fbattery.factory.local\");\n\n       \u002F\u002F Add object\n       UA_ObjectAttributes oAttr = UA_ObjectAttributes_default;\n       oAttr.displayName = UA_LOCALIZEDTEXT(\"en-US\", \"Station01_CellLoading\");\n       UA_NodeId stationId = UA_NODEID_STRING(nsIdx, \"Station01\");\n       UA_Server_addObjectNode(\n           server, stationId,\n           UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),\n           UA_QUALIFIEDNAME(nsIdx, \"Station01\"),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),\n           oAttr, NULL, NULL\n       );\n\n       \u002F\u002F Add variable with read callback\n       UA_VariableAttributes vAttr = UA_VariableAttributes_default;\n       vAttr.displayName = UA_LOCALIZEDTEXT(\"en-US\", \"CycleTime\");\n       vAttr.accessLevel = UA_ACCESSLEVELMASK_READ;\n       UA_NodeId cycleTimeId = UA_NODEID_STRING(nsIdx, \"Station01.CycleTime\");\n\n       UA_Server_addVariableNode(\n           server, cycleTimeId, stationId,\n           UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),\n           UA_QUALIFIEDNAME(nsIdx, \"CycleTime\"),\n           UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),\n           vAttr, NULL, NULL\n       );\n\n       UA_DataSource dataSource;\n       dataSource.read = read_cycle_time;\n       dataSource.write = NULL;\n       UA_Server_setVariableNode_dataSource(server, cycleTimeId, dataSource);\n\n       \u002F\u002F Run server\n       UA_Server_run(server, &running);\n       UA_Server_delete(server);\n       return 0;\n   }\n   ```\n\n### Information Models\n\n1. **OPC UA DI (Device Integration)**\n   - Standardized model for devices\n   - DeviceType, BlockType, ParameterSet\n   - Used by PLCs, sensors, actuators\n\n2. **PLCopen**\n   - Standard for PLC programs\n   - IEC 61131-3 integration\n   - Function blocks, tasks, variables\n\n3. **PackML (Packaging Machine Language)**\n   - State machine model (Idle, Execute, Complete, Abort)\n   - Used in automotive assembly lines\n   - ISA-TR88.00.02 standard\n\n4. **Custom Companion Specifications**\n   - OEM-specific models (e.g., BMW, VW)\n   - Battery assembly, welding, painting\n\n### Security Configuration\n\n1. **Server Security (Python)**\n   ```python\n   from asyncua import Server, ua\n   from asyncua.crypto.cert_gen import setup_self_signed_certificate\n\n   # Generate self-signed certificate\n   await setup_self_signed_certificate(\n       'server_cert.der',\n       'server_key.pem',\n       'BatteryLineServer',\n       'urn:battery.factory.local'\n   )\n\n   server = Server()\n   await server.init()\n\n   # Load certificate\n   await server.load_certificate('server_cert.der')\n   await server.load_private_key('server_key.pem')\n\n   # Enable security\n   await server.set_security_policy([\n       ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt\n   ])\n\n   # Add user authentication\n   await server.set_security_IDs([\n       'Username',\n       ua.UserTokenType.UserName\n   ])\n\n   def user_manager(isession, username, password):\n       return username == 'admin' and password == 'secure_password'\n\n   server.user_manager.set_user_manager(user_manager)\n   ```\n\n2. **Client Authentication**\n   ```python\n   client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n   # Set security policy\n   client.set_security_string(\n       'Basic256Sha256,SignAndEncrypt,client_cert.der,client_key.pem'\n   )\n\n   # Set username\u002Fpassword\n   client.set_user('admin')\n   client.set_password('secure_password')\n\n   async with client:\n       # Authenticated connection\n       pass\n   ```\n\n### Historical Data Access (HDA)\n\n```python\nfrom asyncua import Client\nfrom datetime import datetime, timedelta\n\nasync def read_history():\n    client = Client('opc.tcp:\u002F\u002Fplc.factory.local:4840')\n\n    async with client:\n        node = await client.get_node('ns=2;s=Station01.CycleTime')\n\n        start_time = datetime.now() - timedelta(hours=24)\n        end_time = datetime.now()\n\n        history = await node.read_raw_history(\n            start_time, end_time, numvalues=1000\n        )\n\n        for datavalue in history:\n            print(f\"{datavalue.SourceTimestamp}: {datavalue.Value.Value}\")\n```\n\n### Events and Alarms\n\n1. **Generate Event (Server)**\n   ```python\n   # Create event type\n   event_type = await server.create_custom_event_type(\n       idx, 'CycleCompleteEvent', ua.ObjectIds.BaseEventType,\n       [('BatteryID', ua.VariantType.String),\n        ('Duration', ua.VariantType.Float)]\n   )\n\n   # Trigger event\n   event = await server.get_event_generator(event_type, station01)\n   event.event.Message = ua.LocalizedText('Cycle complete')\n   event.event.Severity = 500\n   await event.trigger(BatteryID='BAT12345', Duration=45.2)\n   ```\n\n2. **Subscribe to Events (Client)**\n   ```python\n   class EventHandler:\n       def event_notification(self, event):\n           print(f\"Event: {event.Message.Text}\")\n           print(f\"Battery ID: {event.BatteryID}\")\n           print(f\"Duration: {event.Duration}s\")\n\n   handler = EventHandler()\n   subscription = await client.create_subscription(100, handler)\n   await subscription.subscribe_events(station01)\n   ```\n\n### Performance Optimization\n\n1. **Batch Read\u002FWrite**\n   - Read multiple nodes in single request\n   - Reduce network round-trips\n\n   ```python\n   nodes = [\n       await client.get_node('ns=2;s=Station01.Status'),\n       await client.get_node('ns=2;s=Station01.CycleTime'),\n       await client.get_node('ns=2;s=Station01.BatteryID')\n   ]\n   values = await client.read_values(nodes)\n   ```\n\n2. **Subscription Sampling**\n   - Set sampling interval based on data volatility\n   - Fast-changing: 100ms\n   - Slow-changing: 1000ms\n\n3. **Data Filtering**\n   - DeadbandFilter: Only notify on significant change\n   - EventFilter: Filter events by severity\n\n### Integration Patterns\n\n1. **OPC UA to MQTT Gateway**\n   - Bridge factory data to cloud\n   - Sparkplug B specification\n   - Edge gateway (Kepware, Ignition)\n\n2. **OPC UA to DDS Bridge**\n   - Factory floor → vehicle testing\n   - Custom bridge application\n   - Map OPC UA nodes to DDS topics\n\n3. **OPC UA Aggregating Server**\n   - Federate multiple PLC servers\n   - Single interface for MES\n   - Namespace mapping\n\n### Monitoring & Debugging\n\n1. **UaExpert (GUI Client)**\n   - Browse address space\n   - Read\u002Fwrite values\n   - Monitor subscriptions\n   - Free from Unified Automation\n\n2. **Wireshark**\n   - OPC UA dissector\n   - Filter: `opcua`\n   - Inspect binary protocol\n\n3. **Server Diagnostics**\n   - SessionDiagnosticsArray: Active sessions\n   - ServerDiagnosticsSummary: Request counts\n   - SubscriptionDiagnosticsArray: Subscription health\n\n### Testing Strategies\n\n1. **Unit Tests**\n   - Mock OPC UA server\n   - Test client logic\n\n2. **Integration Tests**\n   - Run open62541 server in Docker\n   - Client connects, asserts values\n\n3. **Load Tests**\n   - 1000 subscriptions\n   - 10,000 nodes\n   - Measure CPU\u002Fmemory\n\n### Common Pitfalls\n\n1. **No security in production**: Always use SignAndEncrypt\n2. **Missing error handling**: Network failures, timeouts\n3. **Subscription leaks**: Always clean up\n4. **Large arrays**: Use ByteString for images, not arrays\n5. **Blocking calls**: Use async clients\n\n### Deliverables\n\nWhen implementing OPC UA solutions, provide:\n1. Information model diagram (nodes, types, references)\n2. Server implementation with security enabled\n3. Client implementation with subscription handling\n4. Custom data type definitions (XML or code)\n5. Method implementations for RPC\n6. Performance test results (throughput, latency)\n7. Integration guide for MES\u002FSCADA systems\n\n### ros2-dds-middleware\n\n## ROS 2 DDS Middleware Expertise\n\nYou are an expert in ROS 2 for automotive autonomy and robotics applications.\n\n### Core Architecture\n\n1. **ROS 2 vs ROS 1**\n   - ROS 1: Single master, no security, Python 2\n   - ROS 2: Distributed (DDS), secure, real-time, Python 3\u002FC++17\n   - ROS 2 uses DDS for all inter-process communication\n\n2. **Key Concepts**\n   - **Node**: Independent process (sensor driver, planner, controller)\n   - **Topic**: Named data stream (pub\u002Fsub)\n   - **Service**: Synchronous request\u002Fresponse\n   - **Action**: Asynchronous goal-based task (e.g., navigate to waypoint)\n   - **Parameter**: Runtime configuration\n   - **Launch**: Multi-node orchestration\n   - **Bag**: Record and replay messages\n\n3. **DDS Middleware Choices**\n   - **Fast DDS (eProsima)**: Default, high performance\n   - **Cyclone DDS (Eclipse)**: Lightweight, excellent throughput\n   - **Connext DDS (RTI)**: Commercial, safety-certified\n   - **Switch via**: `export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp`\n\n4. **Quality of Service (QoS)**\n   - **Reliability**: RELIABLE (TCP-like), BEST_EFFORT (UDP-like)\n   - **Durability**: VOLATILE (no late-join), TRANSIENT_LOCAL (last N)\n   - **History**: KEEP_LAST(n), KEEP_ALL\n   - **Liveliness**: AUTOMATIC, MANUAL_BY_TOPIC\n   - **Deadline**: Max time between messages\n\n### Automotive Use Cases\n\n1. **Autonomous Driving Stack**\n   ```\n   Nodes:\n   - \u002Fsensor\u002Fcamera_front → Image (30Hz)\n   - \u002Fsensor\u002Flidar → PointCloud2 (10Hz)\n   - \u002Fsensor\u002Fradar_front → RadarTracks (20Hz)\n   - \u002Fperception\u002Fobject_detection → DetectedObjects\n   - \u002Fplanning\u002Ftrajectory → Path\n   - \u002Fcontrol\u002Fvehicle_commands → AckermannDrive\n   ```\n\n2. **Sensor Fusion Pipeline**\n   - Camera (compressed image) → YOLOv8 object detection\n   - LiDAR (point cloud) → clustering and segmentation\n   - Radar (tracks) → velocity estimation\n   - Fusion node subscribes to all → publishes unified DetectedObjects\n\n3. **SLAM for Parking**\n   - LiDAR → \u002Fslam_toolbox node → \u002Fmap (OccupancyGrid)\n   - Odometry → \u002Frobot_localization (EKF fusion)\n   - TF tree: map → odom → base_link → sensors\n\n4. **Simulation with CARLA**\n   - CARLA publishes camera, LiDAR, GPS\n   - ROS 2 bridge: carla_ros_bridge\n   - Test AV stack in virtual environment\n\n### Implementation Patterns\n\n1. **Simple Publisher (C++)**\n   ```cpp\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n   #include \u003Csensor_msgs\u002Fmsg\u002Fimage.hpp>\n\n   class CameraPublisher : public rclcpp::Node {\n   public:\n     CameraPublisher() : Node(\"camera_publisher\") {\n       \u002F\u002F QoS: Sensor data profile (BEST_EFFORT, VOLATILE)\n       auto qos = rclcpp::SensorDataQoS();\n\n       publisher_ = this->create_publisher\u003Csensor_msgs::msg::Image>(\n         \"\u002Fsensor\u002Fcamera\u002Fimage_raw\", qos\n       );\n\n       timer_ = this->create_wall_timer(\n         std::chrono::milliseconds(33),  \u002F\u002F 30 Hz\n         std::bind(&CameraPublisher::publish_image, this)\n       );\n     }\n\n   private:\n     void publish_image() {\n       auto msg = sensor_msgs::msg::Image();\n       msg.header.stamp = this->now();\n       msg.header.frame_id = \"camera_front\";\n       msg.width = 1920;\n       msg.height = 1080;\n       msg.encoding = \"rgb8\";\n       msg.data.resize(msg.width * msg.height * 3);\n\n       \u002F\u002F Fill with camera data\n       capture_camera_frame(msg.data);\n\n       publisher_->publish(msg);\n     }\n\n     rclcpp::Publisher\u003Csensor_msgs::msg::Image>::SharedPtr publisher_;\n     rclcpp::TimerBase::SharedPtr timer_;\n   };\n\n   int main(int argc, char** argv) {\n     rclcpp::init(argc, argv);\n     rclcpp::spin(std::make_shared\u003CCameraPublisher>());\n     rclcpp::shutdown();\n     return 0;\n   }\n   ```\n\n2. **Subscriber with Callback (Python)**\n   ```python\n   import rclpy\n   from rclpy.node import Node\n   from sensor_msgs.msg import PointCloud2\n   from sensor_msgs_py import point_cloud2\n\n   class LidarProcessor(Node):\n       def __init__(self):\n           super().__init__('lidar_processor')\n\n           # QoS: Reliable for processing\n           qos = rclpy.qos.QoSProfile(\n               reliability=rclpy.qos.ReliabilityPolicy.RELIABLE,\n               history=rclpy.qos.HistoryPolicy.KEEP_LAST,\n               depth=10\n           )\n\n           self.subscription = self.create_subscription(\n               PointCloud2,\n               '\u002Fsensor\u002Flidar\u002Fpoints',\n               self.lidar_callback,\n               qos\n           )\n\n       def lidar_callback(self, msg):\n           # Convert to numpy array\n           points = point_cloud2.read_points_numpy(\n               msg, field_names=(\"x\", \"y\", \"z\", \"intensity\")\n           )\n\n           # Process point cloud\n           clusters = self.cluster_points(points)\n           self.publish_clusters(clusters)\n\n   def main():\n       rclpy.init()\n       node = LidarProcessor()\n       rclpy.spin(node)\n       node.destroy_node()\n       rclpy.shutdown()\n   ```\n\n3. **Service Client (Async)**\n   ```cpp\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n   #include \u003Cstd_srvs\u002Fsrv\u002Ftrigger.hpp>\n\n   class DiagnosticClient : public rclcpp::Node {\n   public:\n     DiagnosticClient() : Node(\"diagnostic_client\") {\n       client_ = this->create_client\u003Cstd_srvs::srv::Trigger>(\n         \"\u002Fvehicle\u002Fdiagnostics\u002Fread_dtc\"\n       );\n     }\n\n     void call_service() {\n       auto request = std::make_shared\u003Cstd_srvs::srv::Trigger::Request>();\n\n       \u002F\u002F Async call\n       auto future = client_->async_send_request(request);\n\n       \u002F\u002F Wait for result (or use callback)\n       if (rclcpp::spin_until_future_complete(this->get_node_base_interface(), future)\n           == rclcpp::FutureReturnCode::SUCCESS) {\n         auto response = future.get();\n         RCLCPP_INFO(this->get_logger(), \"DTCs: %s\", response->message.c_str());\n       }\n     }\n\n   private:\n     rclcpp::Client\u003Cstd_srvs::srv::Trigger>::SharedPtr client_;\n   };\n   ```\n\n4. **Action Server (Navigation Goal)**\n   ```python\n   from rclpy.action import ActionServer\n   from nav2_msgs.action import NavigateToPose\n\n   class NavigationAction(Node):\n       def __init__(self):\n           super().__init__('navigation_action')\n           self._action_server = ActionServer(\n               self,\n               NavigateToPose,\n               'navigate_to_pose',\n               self.execute_callback\n           )\n\n       def execute_callback(self, goal_handle):\n           self.get_logger().info('Executing navigation goal...')\n\n           # Feedback loop\n           feedback_msg = NavigateToPose.Feedback()\n           for i in range(100):\n               feedback_msg.distance_remaining = 100.0 - i\n               goal_handle.publish_feedback(feedback_msg)\n               time.sleep(0.1)\n\n           goal_handle.succeed()\n           result = NavigateToPose.Result()\n           result.success = True\n           return result\n   ```\n\n### Message Types\n\n1. **Standard Messages**\n   - `std_msgs`: Basic types (Int32, String, Header)\n   - `sensor_msgs`: Image, PointCloud2, Imu, NavSatFix\n   - `geometry_msgs`: Pose, Twist, Transform\n   - `nav_msgs`: Odometry, Path, OccupancyGrid\n   - `tf2_msgs`: TFMessage (coordinate transforms)\n\n2. **Custom Messages**\n   ```\n   # my_interfaces\u002Fmsg\u002FDetectedObject.msg\n   std_msgs\u002FHeader header\n   string object_id\n   string classification  # car, pedestrian, bike\n   geometry_msgs\u002FPose pose\n   geometry_msgs\u002FVector3 velocity\n   float32 confidence\n   ```\n\n   ```cmake\n   # CMakeLists.txt\n   find_package(rosidl_default_generators REQUIRED)\n   rosidl_generate_interfaces(${PROJECT_NAME}\n     \"msg\u002FDetectedObject.msg\"\n     DEPENDENCIES std_msgs geometry_msgs\n   )\n   ```\n\n### TF (Transform) System\n\n1. **Coordinate Frames**\n   ```\n   map (global)\n     └─ odom (drift-corrected)\n         └─ base_link (vehicle center)\n             ├─ camera_front\n             ├─ lidar_top\n             └─ radar_front\n   ```\n\n2. **Publish Static Transform**\n   ```bash\n   ros2 run tf2_ros static_transform_publisher \\\n     0 0 1.5 0 0 0 base_link camera_front\n   ```\n\n3. **Lookup Transform (Python)**\n   ```python\n   from tf2_ros import Buffer, TransformListener\n\n   tf_buffer = Buffer()\n   tf_listener = TransformListener(tf_buffer, node)\n\n   try:\n       transform = tf_buffer.lookup_transform(\n           'map', 'base_link', rclpy.time.Time()\n       )\n       x = transform.transform.translation.x\n       y = transform.transform.translation.y\n   except Exception as e:\n       node.get_logger().error(f\"TF lookup failed: {e}\")\n   ```\n\n### Launch Files (Python)\n\n```python\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\n\ndef generate_launch_description():\n    return LaunchDescription([\n        Node(\n            package='sensor_drivers',\n            executable='camera_node',\n            name='camera_front',\n            parameters=[{'frame_id': 'camera_front', 'fps': 30}],\n            remappings=[('\u002Fimage', '\u002Fsensor\u002Fcamera\u002Fimage_raw')]\n        ),\n        Node(\n            package='perception',\n            executable='object_detector',\n            name='detector',\n            parameters=[{'model': 'yolov8n.pt'}]\n        ),\n        Node(\n            package='tf2_ros',\n            executable='static_transform_publisher',\n            arguments=['0', '0', '1.5', '0', '0', '0', 'base_link', 'camera_front']\n        )\n    ])\n```\n\n### Rosbag (Record and Replay)\n\n1. **Record Data**\n   ```bash\n   ros2 bag record -o test_drive_01 \\\n     \u002Fsensor\u002Fcamera\u002Fimage_raw \\\n     \u002Fsensor\u002Flidar\u002Fpoints \\\n     \u002Fvehicle\u002Fodom\n   ```\n\n2. **Replay**\n   ```bash\n   ros2 bag play test_drive_01\n   ```\n\n3. **Programmatic Access**\n   ```python\n   from rosbag2_py import SequentialReader, StorageOptions\n\n   reader = SequentialReader()\n   reader.open(StorageOptions(uri='test_drive_01', storage_id='sqlite3'))\n\n   while reader.has_next():\n       topic, data, timestamp = reader.read_next()\n       # Process message\n   ```\n\n### DDS Configuration\n\n1. **FastDDS XML Profile**\n   ```xml\n   \u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n   \u003Cdds>\n     \u003Cprofiles>\n       \u003Ctransport_descriptors>\n         \u003Ctransport_descriptor>\n           \u003Ctransport_id>SharedMemTransport\u003C\u002Ftransport_id>\n           \u003Ctype>SHM\u003C\u002Ftype>\n         \u003C\u002Ftransport_descriptor>\n       \u003C\u002Ftransport_descriptors>\n       \u003Cparticipant profile_name=\"vehicle_participant\">\n         \u003Crtps>\n           \u003CuserTransports>\n             \u003Ctransport_id>SharedMemTransport\u003C\u002Ftransport_id>\n           \u003C\u002FuserTransports>\n           \u003CuseBuiltinTransports>false\u003C\u002FuseBuiltinTransports>\n         \u003C\u002Frtps>\n       \u003C\u002Fparticipant>\n     \u003C\u002Fprofiles>\n   \u003C\u002Fdds>\n   ```\n\n   ```bash\n   export FASTRTPS_DEFAULT_PROFILES_FILE=\u002Fopt\u002Fvehicle\u002Ffastdds_profile.xml\n   ```\n\n2. **CycloneDDS Configuration**\n   ```xml\n   \u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n   \u003CCycloneDDS>\n     \u003CDomain>\n       \u003CGeneral>\n         \u003CNetworkInterfaceAddress>eth0\u003C\u002FNetworkInterfaceAddress>\n         \u003CAllowMulticast>true\u003C\u002FAllowMulticast>\n       \u003C\u002FGeneral>\n     \u003C\u002FDomain>\n   \u003C\u002FCycloneDDS>\n   ```\n\n### Security (SROS2)\n\n1. **Enable Security**\n   ```bash\n   # Generate keys\n   ros2 security create_keystore demo_keys\n   ros2 security create_enclave demo_keys \u002Fcamera_node\n   ros2 security create_enclave demo_keys \u002Fdetector_node\n\n   # Run with security\n   export ROS_SECURITY_KEYSTORE=~\u002Fdemo_keys\n   export ROS_SECURITY_ENABLE=true\n   export ROS_SECURITY_STRATEGY=Enforce\n   ros2 run sensor_drivers camera_node\n   ```\n\n2. **Access Control**\n   - Define allowed topics per node\n   - Policy files in keystore\n   - DDS Security spec (authentication + encryption)\n\n### Integration with AUTOSAR Adaptive\n\n1. **DDS-SOME\u002FIP Bridge**\n   - ROS 2 uses DDS internally\n   - AUTOSAR Adaptive uses SOME\u002FIP\n   - Bridge converts between protocols\n\n2. **Shared IDL**\n   - Define messages in IDL\n   - Generate code for both ROS 2 and AUTOSAR\n\n### Testing Strategies\n\n1. **Unit Tests (gtest)**\n   ```cpp\n   #include \u003Cgtest\u002Fgtest.h>\n   #include \u003Crclcpp\u002Frclcpp.hpp>\n\n   TEST(ObjectDetectorTest, ValidInput) {\n     auto node = std::make_shared\u003CObjectDetector>();\n     auto result = node->detect_objects(mock_image);\n     ASSERT_EQ(result.size(), 3);\n   }\n   ```\n\n2. **Launch Tests**\n   ```python\n   from launch_testing import LaunchTestService\n\n   def test_sensor_pipeline():\n       # Launch nodes\n       # Publish test data\n       # Assert expected output\n       pass\n   ```\n\n3. **Simulation Tests**\n   - Run in Gazebo with mock vehicle\n   - Inject sensor noise\n   - Validate control outputs\n\n### Performance Tuning\n\n1. **Zero-Copy (Shared Memory)**\n   - Loaned messages API\n   - Avoid memcpy for large data (images, point clouds)\n\n2. **Intra-Process Communication**\n   - Bypass DDS for same-process nodes\n   - Enable with `use_intra_process_comms=True`\n\n3. **Real-Time Executor**\n   - Priority-based scheduling\n   - Lock-free data structures\n\n### Deliverables\n\nWhen implementing ROS 2 solutions, provide:\n1. Node architecture diagram\n2. Custom message definitions (.msg files)\n3. C++\u002FPython implementation with error handling\n4. Launch files for multi-node deployment\n5. QoS profile configuration\n6. SROS2 security setup guide\n7. Performance test results (latency, throughput)\n",{"name":5,"tags":24,"source":67,"license":15,"description":68,"imported_at":69,"source_path":70,"source_repository":71},[25,26,27,5,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66],"adas","amqp","automotive","autonomous-driving","autosar","aws","azure","battery","cloud","coap","constrained","dds","digital-twin","dtls","embedded","enterprise","fleet-management","industrial","industry-4.0","iot","iso-26262","manufacturing","mes","middleware","mqtt","opcua","ota","plc","pub-sub","rabbitmq","real-time","robotics","ros2","scada","sensor-fusion","simulation","slam","supply-chain","telemetry","tpms","udp","v2x","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills","Expert in AMQP (Advanced Message Queuing Protocol) middleware for automotive enterprise integration using RabbitMQ and Azure Service Bus. Covers 6 topics across middleware domain. Includes 6 skill files covering AMQP 1.0 OASIS Standard, AUTOSAR Adaptive (comparison), AUTOSAR Adaptive Platform, AWS IoT Core best practices, Apache Qpid Proton, AutomationML for data modeling, Azure IoT Hub protocols, Azure Service Bus protocols and more.\n","2026-09-20","skills\u002Fautomotive-middleware\u002FSKILL.md","pangzhenying2025\u002Fhermes-automotive-skills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fautomotive\u002Fautomotive-middleware","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":79,"prompt":89,"zipAvailable":90},[80,83,86],{"tool":81,"command":82},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-middleware",{"tool":84,"command":85},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-middleware",{"tool":87,"command":88},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-middleware","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fautomotive\u002Fautomotive-middleware\u002FSKILL.md",true,[],[93,101,108,115,122,129],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":100},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":100},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":100},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":100},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":100},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":100},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]