0% found this document useful (0 votes)
6 views11 pages

AUTOSAR Python Revision

The document is a student revision guide on AUTOSAR (AUTomotive Open System ARchitecture) with a focus on Python applications. It covers the overview of AUTOSAR, the differences between Classic and Adaptive AUTOSAR, ARXML as the description language, key Python libraries for working with AUTOSAR, and provides code examples and hands-on questions for practice. The guide aims to facilitate understanding and practical skills in automotive software engineering using Python.

Uploaded by

Priyanshu Ranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

AUTOSAR Python Revision

The document is a student revision guide on AUTOSAR (AUTomotive Open System ARchitecture) with a focus on Python applications. It covers the overview of AUTOSAR, the differences between Classic and Adaptive AUTOSAR, ARXML as the description language, key Python libraries for working with AUTOSAR, and provides code examples and hands-on questions for practice. The guide aims to facilitate understanding and practical skills in automotive software engineering using Python.

Uploaded by

Priyanshu Ranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

AUTOSAR
with Python
Student Revision Guide
───────────────
Theory • Code Examples • 16 Hands-On Questions
Automotive Software Engineering | arxml | python-arxml | autosar-data

SECTION 1: What is AUTOSAR?

1.1 Overview of AUTOSAR


AUTOSAR (AUTomotive Open System ARchitecture) is a global partnership of automotive OEMs, Tier-1
suppliers, and tool developers. Its mission is to standardize automotive software architectures to enable reuse,
portability, and safe software development across the industry.

Founded 2003 by BMW, Bosch, Continental, DaimlerChrysler, Siemens VDO, and Volkswagen.

Standardize the ECU (Electronic Control Unit) software architecture across OEMs and
Goal
suppliers.

Two Classic AUTOSAR (deeply embedded, real-time) and Adaptive AUTOSAR (high-
Variants compute, Linux-based).

1.2 Classic vs Adaptive AUTOSAR


Feature Classic AUTOSAR Adaptive AUTOSAR
OS AUTOSAR OS (OSEK-based) POSIX (Linux, QNX)
Language C (mainly) C++14/17
Scheduling Static (fixed tasks) Dynamic (SOME/IP services)
Use Case Powertrain, Chassis, Body ADAS, Infotainment, OTA
Memory Kilobytes (flash) Gigabytes (RAM/storage)
Communication CAN, LIN, FlexRay Ethernet, SOME/IP, DDS

1.3 AUTOSAR Layered Architecture


Classic AUTOSAR separates software into well-defined layers, allowing hardware-independent application
development:

Page 1 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

Application Layer (SWC - Software Components)


RTE - Runtime Environment
BSW - Basic Software (COM, DCM, NVM, OS...)
MCAL - Microcontroller Abstraction Layer
Hardware / ECU

SECTION 2: ARXML — The AUTOSAR Description Language

2.1 What is ARXML?


ARXML (AUTOSAR XML) is the standard file format for describing AUTOSAR software architectures. Every
component — its ports, interfaces, data types, and connections — is described in .arxml files that tools like Vector
DaVinci, EB tresos, or Python libraries can process.

Key ARXML Concepts:


• Package (AUTOSAR-PACKAGE): Container for AUTOSAR elements
• Software Component (APPLICATION-SW-COMPONENT-TYPE): An SWC definition
• Port (P-PORT-PROTOTYPE / R-PORT-PROTOTYPE): Provided and Required ports
• Interface (SENDER-RECEIVER-INTERFACE): Defines data exchanged
• Data Element (VARIABLE-DATA-PROTOTYPE): Actual data inside an interface
• Composition (COMPOSITION-SW-COMPONENT-TYPE): Groups multiple SWCs

2.2 ARXML File Structure Example


<!-- Minimal ARXML file structure -->
<?xml version="1.0" encoding="UTF-8"?>
<AUTOSAR xmlns="[Link]
xmlns:xsi="[Link]
<AR-PACKAGES>
<AR-PACKAGE>
<SHORT-NAME>MyPackage</SHORT-NAME>
<ELEMENTS>
<!-- SWCs, Interfaces, Compositions go here -->
</ELEMENTS>
</AR-PACKAGE>
</AR-PACKAGES>
</AUTOSAR>

SECTION 3: Python Libraries for AUTOSAR

3.1 Key Python Libraries


Library Install Purpose

Page 2 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

autosar-data pip install autosar-data Read/write/validate ARXML (Rust-


backed, fast)
python-arxml pip install python-arxml Parse and manipulate ARXML files (pure
Python)
lxml pip install lxml Low-level XML parsing of ARXML
xmltodict pip install xmltodict Convert ARXML to Python dictionaries
cantools pip install cantools Parse DBC/ARXML CAN network databases
pydantic pip install pydantic Data validation for AUTOSAR data
models

3.2 Installing the Libraries


# Install all key AUTOSAR Python libraries
pip install autosar-data
pip install python-arxml
pip install lxml
pip install cantools
pip install xmltodict

# Verify installation
python -c "import autosar; print(autosar.__version__)"

SECTION 4: Python Code Examples

4.1 Parsing an ARXML File with lxml


lxml is the most fundamental approach — it lets you traverse the ARXML XML tree directly.

from lxml import etree

# Load and parse an ARXML file


tree = [Link]('[Link]')
root = [Link]()

# Define the AUTOSAR namespace


ns = {'ar': '[Link]

# Find all Software Components


swcs = [Link]('.//ar:APPLICATION-SW-COMPONENT-TYPE', ns)
for swc in swcs:
name = [Link]('ar:SHORT-NAME', ns).text
print(f'SWC Found: {name}')

# Find all Sender-Receiver Interfaces


sr_ifaces = [Link]('.//ar:SENDER-RECEIVER-INTERFACE', ns)
for iface in sr_ifaces:
iface_name = [Link]('ar:SHORT-NAME', ns).text
print(f'Interface: {iface_name}')

4.2 Using autosar-data Library

Page 3 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

autosar-data is a modern, high-performance library backed by a Rust core. It supports reading, writing, and
validating ARXML with strong type checking.

import autosar

# Create a new AUTOSAR workspace


ws = [Link]()

# Load an existing ARXML file


ws.load_file('my_system.arxml')

# Access packages
for package in [Link]:
print(f'Package: {[Link]}')

# Find a specific component by path


swc = ws['/MyPackage/Components/EngineController']
print(f'Component: {[Link]}, Type: {type(swc).__name__}')

# List all ports of the SWC


for port in [Link]:
direction = 'PROVIDED' if hasattr(port, 'provided') else 'REQUIRED'
print(f' Port: {[Link]} [{direction}]')

4.3 Creating a Software Component Programmatically


You can build an entire AUTOSAR SWC model in Python and export it as a valid ARXML file:

import autosar

ws = [Link](version='4.3.0')
package = ws.make_packages('/ComponentTypes')[0]

# Create a Sender-Receiver interface


iface_pkg = ws.make_packages('/Interfaces')[0]
iface = iface_pkg.create_sender_receiver_interface('SpeedInterface')
iface.create_data_element('VehicleSpeed',
type_ref='/DataTypes/uint16')

# Create an Application Software Component


swc = package.create_application_swc('SpeedSensorSWC')

# Add a Provided Port


port = swc.create_provide_port('SpeedOut',
port_interface_ref='/Interfaces/SpeedInterface')

# Save to ARXML
ws.save_file('[Link]')
print('ARXML file created successfully!')

4.4 Parsing CAN Signals from ARXML using cantools


cantools supports reading CAN network descriptions in ARXML format, allowing you to decode messages and
signals:

import cantools

Page 4 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

# Load ARXML CAN database


db = [Link].load_file('vehicle_can.arxml')

# List all messages


for msg in [Link]:
print(f'Message: {[Link]}, ID: 0x{msg.frame_id:X}, DLC: {[Link]}')
for sig in [Link]:
print(f' Signal: {[Link]}, Start: {[Link]},
Length: {[Link]}, Factor: {[Link]}')

# Decode a raw CAN frame


raw_data = bytes([0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
msg = db.get_message_by_name('EngineData')
decoded = [Link](raw_data)
print(f'Decoded: {decoded}')
# Output: {'EngineSpeed': 100, 'EngineTemp': 0}

4.5 Validating ARXML with xmltodict


xmltodict allows quick inspection of ARXML as Python dictionaries — great for scripting and validation checks:

import xmltodict

# Read ARXML as a Python dictionary


with open('[Link]', 'r', encoding='utf-8') as f:
data = [Link]([Link]())

# Navigate the structure


packages = data['AUTOSAR']['AR-PACKAGES']['AR-PACKAGE']

# Handle single or multiple packages


if isinstance(packages, dict):
packages = [packages]

for pkg in packages:


print(f"Package: {pkg['SHORT-NAME']}")
elements = [Link]('ELEMENTS', {})
swcs = [Link]('APPLICATION-SW-COMPONENT-TYPE', [])
if isinstance(swcs, dict):
swcs = [swcs]
for swc in swcs:
print(f" SWC: {swc['SHORT-NAME']}")

4.6 Generating ARXML Reports with Python


A practical use-case: scan an ARXML workspace and generate a CSV inventory of all SWCs and their ports:

import csv
from lxml import etree

tree = [Link]('[Link]')
root = [Link]()
ns = {'ar': '[Link]

rows = []
for swc in [Link]('.//ar:APPLICATION-SW-COMPONENT-TYPE', ns):

Page 5 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

swc_name = [Link]('ar:SHORT-NAME', ns).text


for port in [Link]('.//ar:P-PORT-PROTOTYPE', ns):
[Link]([swc_name, [Link]('ar:SHORT-NAME', ns).text, 'PROVIDED'])
for port in [Link]('.//ar:R-PORT-PROTOTYPE', ns):
[Link]([swc_name, [Link]('ar:SHORT-NAME', ns).text, 'REQUIRED'])

with open('swc_inventory.csv', 'w', newline='') as f:


writer = [Link](f)
[Link](['SWC', 'Port', 'Direction'])
[Link](rows)

print(f'Exported {len(rows)} ports to swc_inventory.csv')

SECTION 5: Key Concepts Quick Reference

5.1 AUTOSAR Communication Paradigms


Paradigm ARXML Type Description
Sender-Receiver SENDER-RECEIVER- Asynchronous data flow between SWCs
INTERFACE
Client-Server CLIENT-SERVER-INTERFACE Synchronous RPC-style operations
Mode Switch MODE-SWITCH-INTERFACE Broadcast ECU mode changes
Trigger TRIGGER-INTERFACE Event-based signaling (no data)
Parameter PARAMETER-INTERFACE Read-only calibration data

5.2 RTE API Patterns in Generated Code


After code generation, the RTE layer provides standardized APIs that SWC C code calls:

/* Sender SWC writes a value to port */


Std_ReturnType ret = Rte_Write_SpeedOut_VehicleSpeed(currentSpeed);

/* Receiver SWC reads a value from port */


uint16 speed;
Std_ReturnType ret = Rte_Read_SpeedIn_VehicleSpeed(&speed);

/* Client calls a server operation */


Std_ReturnType ret = Rte_Call_DiagClient_GetDTC(&dtcList);

/* Runnable entity entry point (called by OS) */


FUNC(void, SWC_CODE) SpeedSensor_Runnable(void) {
/* SWC logic here */
}

SECTION 6: 16 Hands-On Practice Questions

The following 16 questions test your understanding from theory through implementation. Questions are
grouped by difficulty.

Page 6 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

① Theory & Concept Questions (Q1-Q5)

Q1 Explain the difference between Classic AUTOSAR and Adaptive AUTOSAR. In what
automotive use-case would you choose each? Name at least two ECU examples for
each variant.

Q2 Draw or describe the AUTOSAR layered architecture. Identify the role of the RTE layer
and explain why it exists between the Application Layer and the Basic Software.

Q3 What are the five AUTOSAR port interface types? For each, write a one-sentence
description and give a real automotive example of where it would be used.

Q4 Compare Sender-Receiver and Client-Server interfaces: Which one is synchronous?


Which would you use for continuous sensor data vs. a diagnostic request? Justify your
answer.

Q5 What is an ARXML file? List five types of AUTOSAR elements that are described in an
ARXML file and explain the role of each.

② Python Setup & Library Questions (Q6-Q8)

Q6 Write the pip commands to install all five Python AUTOSAR-related libraries covered in
this guide. Then write a Python script that imports each one and prints a confirmation
message for each successful import.

# Q6 — Starter Template
# Fill in the correct library names and install commands

libraries = ['____', '____', '____', '____', '____']


for lib in libraries:
try:
__import__(lib)
print(f'[OK] {lib} is available')
except ImportError:
print(f'[MISSING] {lib} not installed')

Q7 What Python library would you use for each task below? Justify your choice: (a) Parse
and traverse ARXML XML tree nodes (b) Fast validation of a large ARXML workspace
(c) Decode a CAN message frame from raw bytes (d) Convert ARXML to a Python
dictionary for scripting (e) Create a new AUTOSAR workspace and export ARXML

Q8 Research and explain: What is the key advantage of the autosar-data library over
python-arxml? What technology does autosar-data use under the hood, and why does it
make it faster?

③ Coding Practice Questions (Q9-Q13)

Page 7 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

Q9 Complete the following Python function that parses an ARXML file and returns a list of
all SWC names found in the document. Test it on a sample ARXML file.

# Q9 — Complete this function


from lxml import etree

def get_all_swc_names(arxml_path: str) -> list[str]:


"""
Parse an ARXML file and return a list
of all APPLICATION-SW-COMPONENT-TYPE SHORT-NAMEs.
"""
tree = [Link](____)
root = [Link]()
ns = {'ar': ____} # Fill in the AUTOSAR namespace
swcs = [Link](____, ns) # Fill in the XPath
return [[Link](____, ns).text for swc in swcs]

# Test
names = get_all_swc_names('[Link]')
print(names)

Q10 Write a Python script using xmltodict that loads an ARXML file and prints: the total
number of AR-PACKAGEs, the total number of SWCs, and all interface names found.
Handle the case where there is only one package (dict instead of list).

Q11 Using cantools, write a Python function that takes a DBC or ARXML file path and a
message name, then returns a dictionary of all signal names and their properties (start
bit, length, factor, offset, min, max) for that message.

# Q11 — Complete this function


import cantools

def get_signal_info(db_path: str, msg_name: str) -> dict:


db = [Link].load_file(____)
msg = db.get_message_by_name(____)
result = {}
for sig in [Link]:
result[[Link]] = {
'start': ____,
'length': ____,
'factor': ____,
'offset': ____,
}
return result

Q12 Write a complete Python script that creates a minimal ARXML file from scratch using
lxml. The ARXML should contain one AR-PACKAGE named 'MyComponents' with one
APPLICATION-SW-COMPONENT-TYPE named 'BrakeSWC'. Save it as '[Link]'
and verify it by re-parsing it.

Q13 Extend the CSV report generator from Section 4.6 to also count and output: total
number of SWCs, total number of P-PORTs, total number of R-PORTs, and a list of
SWCs that have no ports. Format the output as a summary report.

Page 8 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

④ Advanced & Integration Questions (Q14-Q16)

Q14 Design a Python class AutosarWorkspaceAnalyzer that wraps lxml parsing and
provides the following methods: • load(path) — load an ARXML file • list_swcs() —
return all SWC names • list_interfaces() — return all interface names and types •
get_port_map() — return {swc_name: [list of (port_name, direction)]} Write the full
class with docstrings.

# Q14 — Class template


from lxml import etree

class AutosarWorkspaceAnalyzer:
NS = {'ar': '[Link]

def __init__(self):
[Link] = None

def load(self, path: str) -> None:


# TODO: Parse the ARXML file
pass

def list_swcs(self) -> list[str]:


# TODO: Return list of SWC names
pass

def list_interfaces(self) -> list[tuple[str, str]]:


# TODO: Return list of (name, type) tuples
pass

def get_port_map(self) -> dict:


# TODO: Return {swc_name: [(port_name, direction), ...]}
pass

Q15 AUTOSAR systems often have mismatched port connections — a provided port on one
SWC is not connected to a required port on another. Write a Python script that reads a
composition ARXML, lists all connector mappings, and identifies unconnected ports (P-
PORTs with no matching R-PORT connection). This type of consistency checking is
used in real AUTOSAR toolchains.

Q16 Mini-Project: Build a Python CLI tool autosar_report.py that accepts an ARXML file path
as a command-line argument (using argparse) and generates an HTML report showing:
(a) A summary table of all SWCs and their port counts (b) A list of all interfaces with
their data elements (c) A warning section listing any SWCs with no ports (d) The
AUTOSAR schema version read from the file Save the HTML to [Link] and print a
success message with the path.

# Q16 — Starter skeleton


import argparse
from lxml import etree

def parse_args():
parser = [Link](
description='Generate an HTML report from an ARXML file')
parser.add_argument('arxml', help='Path to the ARXML file')
parser.add_argument('-o', '--output', default='[Link]')
return parser.parse_args()

Page 9 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

def generate_html(root, ns) -> str:


# TODO: Build and return the full HTML string
pass

if __name__ == '__main__':
args = parse_args()
tree = [Link]([Link])
root = [Link]()
ns = {'ar': '[Link]
html = generate_html(root, ns)
with open([Link], 'w') as f:
[Link](html)
print(f'Report saved to {[Link]}')

APPENDIX: Quick Reference Cheat Sheet

A. AUTOSAR Common XPath Expressions


# All SWCs
'.//ar:APPLICATION-SW-COMPONENT-TYPE'

# All SR Interfaces
'.//ar:SENDER-RECEIVER-INTERFACE'

# All CS Interfaces
'.//ar:CLIENT-SERVER-INTERFACE'

# All P-Ports in a specific SWC element (variable: swc)


[Link]('.//ar:P-PORT-PROTOTYPE', ns)

# All R-Ports
[Link]('.//ar:R-PORT-PROTOTYPE', ns)

# SHORT-NAME of any element


[Link]('ar:SHORT-NAME', ns).text

# All Compositions
'.//ar:COMPOSITION-SW-COMPONENT-TYPE'

# All Data Elements in an SR Interface


[Link]('.//ar:VARIABLE-DATA-PROTOTYPE', ns)

B. Common AUTOSAR Acronyms


Acronym Meaning
SWC Software Component
RTE Runtime Environment
BSW Basic Software
MCAL Microcontroller Abstraction Layer
ECU Electronic Control Unit
ARXML AUTOSAR XML Description File

Page 10 | Python & AUTOSAR Revision | For Educational Use


AUTOSAR with Python | Student Revision Guide Automotive Software Engineering

SR Sender-Receiver (interface type)


CS Client-Server (interface type)
P-Port Provided Port
R-Port Required Port
COM Communication Stack Module
DCM Diagnostic Communication Manager
NVM Non-Volatile Memory Manager
OTA Over-The-Air (software update)
SOME/IP Scalable service-Oriented MiddlEware over IP

End of AUTOSAR Python Revision Guide • Good luck with your studies!

Page 11 | Python & AUTOSAR Revision | For Educational Use

You might also like