### Complete Example: Building an ECU Database Source: https://pya2l.readthedocs.io/en/latest/api_reference.html A comprehensive example demonstrating the creation of an ECU database from scratch using pyA2L. It covers project setup, module creation, unit and conversion definitions, record layouts, measurements, and characteristics. ```python from pya2l import DB, export_a2l from pya2l.api.create import ( ProjectCreator, ModuleCreator, CompuMethodCreator, MeasurementCreator, CharacteristicCreator, RecordLayoutCreator, FunctionCreator, GroupCreator, ) from pya2l.api.inspect import Project # --- Setup --- db = DB() session = db.open_create("TurboECU.a2ldb") pc = ProjectCreator(session) project = pc.create_project("TurboECU", "Turbocharged engine ECU") hdr = pc.add_header(project, "Created by pyA2L automation") pc.add_project_no(hdr, "TE-2026-001") mc = ModuleCreator(session) module = mc.create_module("TCU", "Turbo control unit", project=project) mc.add_mod_common(module, "Common settings", byte_order="LITTLE_ENDIAN", data_size=32) # --- Units --- mc.add_unit(module, "rpm", "Revolutions per minute", "rpm", "DERIVED") mc.add_unit(module, "bar", "Pressure", "bar", "DERIVED") mc.add_unit(module, "degC", "Temperature", "°C", "DERIVED") # --- Conversions --- cmc = CompuMethodCreator(session) cm_rpm = cmc.create_compu_method( "CM_RPM", "RPM", "LINEAR", "%8.0", "rpm", module_name="TCU") cmc.add_coeffs_linear(cm_rpm, offset=0.0, factor=1.0) cm_bar = cmc.create_compu_method( "CM_Boost", "Boost pressure", "LINEAR", "%5.2", "bar", module_name="TCU") cmc.add_coeffs_linear(cm_bar, offset=-1.0, factor=0.01) cm_temp = cmc.create_compu_method( "CM_Temp", "Temperature", "LINEAR", "%6.1", "°C", module_name="TCU") cmc.add_coeffs_linear(cm_temp, offset=-40.0, factor=0.1) # --- Record Layouts --- rlc = RecordLayoutCreator(session) rl_u16 = rlc.create_record_layout("RL_U16", module_name="TCU") rlc.add_fnc_values(rl_u16, 1, "UWORD", "ALTERNATE", "DIRECT") rl_curve = rlc.create_record_layout("RL_CURVE_12", module_name="TCU") rlc.add_no_axis_pts_x(rl_curve, 1, "UBYTE") rlc.add_axis_pts_x(rl_curve, 2, "UWORD", "INDEX_INCR", "DIRECT") rlc.add_fnc_values(rl_curve, 3, "UWORD", "ALTERNATE", "DIRECT") # --- Measurements --- mec = MeasurementCreator(session) m_rpm = mec.create_measurement( "EngineSpeed", "Current engine speed", "UWORD", "CM_RPM", 1, 1.0, 0.0, 8000.0, module_name="TCU") mec.add_ecu_address(m_rpm, 0x100000) m_boost = mec.create_measurement( "BoostPressure", "Turbo boost pressure", "UWORD", "CM_Boost", 1, 0.1, -1.0, 3.5, module_name="TCU") mec.add_ecu_address(m_boost, 0x100002) m_temp = mec.create_measurement( "ChargeAirTemp", "Charge air temperature", "UWORD", "CM_Temp", 1, 0.5, -40.0, 150.0, module_name="TCU") mec.add_ecu_address(m_temp, 0x100004) # --- Characteristics --- cc = CharacteristicCreator(session) c_target = cc.create_characteristic( "TargetBoost", "Target boost pressure", "VALUE", 0x200000, "RL_U16", 0.0, "CM_Boost", 0.0, 3.0, module_name="TCU") c_curve = cc.create_characteristic( "BoostCurve", "Boost vs RPM", "CURVE", 0x201000, "RL_CURVE_12", 0.0, "CM_Boost", 0.0, 3.0, module_name="TCU") cc.add_axis_descr(c_curve, "STD_AXIS", "EngineSpeed", "CM_RPM", 12, 0.0, 8000.0) ``` -------------------------------- ### Build ECU Database from Scratch Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt A comprehensive example demonstrating the creation of an entire ECU database (A2L file) from scratch using pyA2L. It covers project setup, module creation, unit definitions, computational method definitions, and the creation of characteristics, record layouts, functions, and groups. ```python from pya2l import DB, export_a2l from pya2l.api.create import ( ProjectCreator, ModuleCreator, CompuMethodCreator, MeasurementCreator, CharacteristicCreator, RecordLayoutCreator, FunctionCreator, GroupCreator, ) from pya2l.api.inspect import Project # --- Setup --- db = DB() session = db.open_create("TurboECU.a2ldb") pc = ProjectCreator(session) project = pc.create_project("TurboECU", "Turbocharged engine ECU") hdr = pc.add_header(project, "Created by pyA2L automation") pc.add_project_no(hdr, "TE-2026-001") mc = ModuleCreator(session) module = mc.create_module("TCU", "Turbo control unit", project=project) mc.add_mod_common(module, "Common settings", byte_order="LITTLE_ENDIAN", data_size=32) # --- Units --- mc.add_unit(module, "rpm", "Revolutions per minute", "rpm", "DERIVED") mc.add_unit(module, "bar", "Pressure", "bar", "DERIVED") mc.add_unit(module, "degC", "Temperature", "°C", "DERIVED") # --- Conversions --- cmc = CompuMethodCreator(session) cm_rpm = cmc.create_compu_method( "CM_RPM", "RPM", "LINEAR", "%8.0", "rpm", module_name="TCU") cmc.add_coeffs_linear(cm_rpm, offset=0.0, factor=1.0) cm_bar = cmc.create_compu_method( "CM_Boost", "Boost pressure", "LINEAR", "%5.2", "bar", module_name="TCU") cmc.add_coeffs_linear(cm_bar, offset=-1.0, factor=0.01) cm_temp = cmc.create_compu_method( ``` -------------------------------- ### Install pyA2L from Source (One-liner) Source: https://pya2l.readthedocs.io/en/latest/building.html Use this command to compile native extensions and install pya2ldb into your environment when building from source. ```bash pip install -v . ``` -------------------------------- ### IfData Reference Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt This snippet serves as a placeholder for IfData-related examples, directing users to the 'ifdata' documentation for a full guide. ```python from pya2l.api.inspect import Frame # See :doc:`ifdata` for a full guide. Quick reference: fr = Frame.get(session, "FRAME1") print(fr.if_data) # IfData instance ``` -------------------------------- ### One-liner Build and Install pyA2L Source: https://pya2l.readthedocs.io/en/latest/_sources/building.rst.txt Use this command for a standard build and installation of pyA2L from source. It compiles native extensions and installs the package into your environment. ```bash pip install -v . ``` -------------------------------- ### a2ldb-imex CLI usage examples Source: https://pya2l.readthedocs.io/en/latest/configuration.html Demonstrates common command-line operations for the a2ldb-imex tool, including importing, exporting to file/stdout, and JSON export with pretty-printing. ```bash a2ldb-imex -h # show help a2ldb-imex -V # show version # Import a2ldb-imex -i file.a2l # import (creates .a2ldb next to file) a2ldb-imex -i file.a2l -L # create .a2ldb in current directory a2ldb-imex -i file.a2l -E utf-8 # specify encoding a2ldb-imex -i file.a2l -p # silence progress bar # Export a2ldb-imex -e file.a2ldb -o out.a2l # export to file a2ldb-imex -e file.a2ldb # export to stdout # JSON export a2ldb-imex -e file.a2ldb --json -o out.json # export as JSON a2ldb-imex -e file.a2ldb --json --pretty -o out.json # pretty-printed JSON a2ldb-imex -e file.a2ldb --json # JSON to stdout ``` -------------------------------- ### Install pya2ldb from source (editable) Source: https://pya2l.readthedocs.io/en/latest/_sources/installation.rst.txt Clone the repository and install the package in editable mode for development. This requires Git and a C/C++ toolchain with CMake. ```bash git clone https://github.com/christoph2/pyA2L.git cd pyA2L pip install -v -e . ``` -------------------------------- ### a2ldb-imex CLI Usage Examples Source: https://pya2l.readthedocs.io/en/latest/_sources/README.rst.txt Illustrates various command-line operations for the a2ldb-imex tool, including showing version, importing A2L files, and exporting A2L databases. ```bash # Show version $ a2ldb-imex -V ``` ```bash # Import an A2L (creates .a2ldb next to the input or in CWD with -L) $ a2ldb-imex -i path/to/file.a2l ``` ```bash # Import with explicit encoding and create DB in current directory $ a2ldb-imex -i path/to/file.a2l -E latin-1 -L ``` ```bash # Export an .a2ldb back to A2L text (stdout by default or -o file) $ a2ldb-imex -e path/to/file.a2ldb -o exported.a2l ``` -------------------------------- ### Build a Minimal ECU Database Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt A comprehensive example demonstrating the creation of a minimal ECU database, including project, module, units, conversions, measurements, characteristics, and groups. ```python from pya2l import DB from pya2l.api.create import ( ProjectCreator, ModuleCreator, CompuMethodCreator, MeasurementCreator, CharacteristicCreator, RecordLayoutCreator ) db = DB() session = db.open_create("MinimalECU.a2ldb") # Project and module pc = ProjectCreator(session) project = pc.create_project("MinimalECU", "Minimal ECU example") mc = ModuleCreator(session) module = mc.create_module("Engine", "Engine control", project=project) # Unit mc.add_unit(module, name="rpm", long_identifier="RPM", display="rpm", type_str="DERIVED") # Conversion cmc = CompuMethodCreator(session) cm = cmc.create_compu_method( "CM_RPM", "RPM conversion", "LINEAR", "%8.2", "rpm", module_name="Engine" ) cmc.add_coeffs_linear(cm, offset=0.0, factor=0.25) # Record layout rlc = RecordLayoutCreator(session) rl = rlc.create_record_layout("RL_UWORD", module_name="Engine") rlc.add_fnc_values(rl, position=1, datatype="UWORD", index_mode="ALTERNATE", address_type="DIRECT") # Measurement mec = MeasurementCreator(session) meas = mec.create_measurement( "EngineSpeed", "Current engine speed", "UWORD", "CM_RPM", resolution=1, accuracy=1.0, lower_limit=0.0, upper_limit=8000.0, module_name="Engine" ) mec.add_ecu_address(meas, 0x100000) # Characteristic cc = CharacteristicCreator(session) char = cc.create_characteristic( "IdleSpeed", "Target idle speed", "VALUE", 0x200000, "RL_UWORD", 0.0, "CM_RPM", 500.0, 1500.0, module_name="Engine" ) # Group grp = mc.add_group(module, name="BasicParams", long_identifier="Basic parameters") mc.add_group_ref_characteristic(grp, ["IdleSpeed"]) mc.add_group_ref_measurement(grp, ["EngineSpeed"]) # Commit and close mc.commit() db.close() # Export to A2L from pya2l import export_a2l export_a2l("MinimalECU", "MinimalECU.a2l") ``` -------------------------------- ### Build pyA2L Documentation Locally Source: https://pya2l.readthedocs.io/en/latest/building.html Install documentation dependencies and build the Sphinx site locally. Open the generated HTML files in your browser to view the documentation. ```bash python -m pip install -r docs/requirements.txt sphinx sphinx-build -b html docs docs/_build/html ``` -------------------------------- ### Build pyA2L Documentation Source: https://pya2l.readthedocs.io/en/latest/_sources/building.rst.txt Install documentation dependencies and build the Sphinx documentation site locally. The output is generated in the 'docs/_build/html' directory. ```bash python -m pip install -r docs/requirements.txt sphinx ``` ```bash sphinx-build -b html docs docs/_build/html ``` -------------------------------- ### Development Install pyA2L from Source Source: https://pya2l.readthedocs.io/en/latest/building.html For active development, use this command to keep sources editable and automatically recompile extensions as needed. ```bash pip install -v -e . ``` -------------------------------- ### Install pya2ldb from PyPI Source: https://pya2l.readthedocs.io/en/latest/_sources/installation.rst.txt Use this command to install the package directly from the Python Package Index. Ensure you use the correct package name 'pya2ldb'. ```bash pip install pya2ldb ``` -------------------------------- ### Create Characteristic with CharacteristicCreator Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt This snippet is incomplete and only shows the start of creating a characteristic. It initializes the CharacteristicCreator. ```python from pya2l.api.create import CharacteristicCreator cc = CharacteristicCreator(session) # VALUE (scalar) c1 = cc.create_characteristic( ``` -------------------------------- ### Session Management Source: https://pya2l.readthedocs.io/en/latest/api_reference.html Workflows start by obtaining a session using the DB class or function-level imports. ```APIDOC ## Session Management Every workflow starts by obtaining a session: ```python from pya2l import DB db = DB() # Parse A2L → SQLite (creates .a2ldb) session = db.import_a2l("ASAP2_Demo_V161.a2l") # Open existing database (fast, no reparsing) session = db.open_existing("ASAP2_Demo_V161") # Open-or-create (convenience method) session = db.open_create("ASAP2_Demo_V161.a2l") ``` The returned `session` is a `SessionProxy` that wraps a SQLAlchemy `Session` and adds IF_DATA parsing capabilities. You can use it for raw SQLAlchemy queries _and_ for the high-level inspect/create/validate APIs. Function-level API (no `DB` class needed): ```python from pya2l import import_a2l, open_existing, export_a2l session = import_a2l("file.a2l", encoding="utf-8", progress_bar=False) session = open_existing("file") export_a2l("file", "output.a2l") ``` ``` -------------------------------- ### Get First Few Measurements Source: https://pya2l.readthedocs.io/en/latest/_sources/tutorial.rst.txt Retrieve the first few measurements from a module by materializing the query results into a list and then slicing it. ```python # 1) Get the first few measurements (materialize the generator) meas_list = list(module.measurement.query()) first_three = meas_list[:3] ``` -------------------------------- ### Development Install pyA2L Source: https://pya2l.readthedocs.io/en/latest/_sources/building.rst.txt Install pyA2L in editable mode for development. This method uses the build backend defined in pyproject.toml and recompiles extensions as needed when changes are made. ```bash pip install -v -e . ``` -------------------------------- ### Create Minimal ECU A2L Database Source: https://pya2l.readthedocs.io/en/latest/howto.html This example demonstrates how to programmatically create a minimal A2L database file from scratch using the pyA2L Creator API. It covers creating projects, modules, units, conversions, record layouts, measurements, characteristics, and groups. ```python from pya2l import DB from pya2l.api.create import ( ProjectCreator, ModuleCreator, CompuMethodCreator, MeasurementCreator, CharacteristicCreator, RecordLayoutCreator ) db = DB() session = db.open_create("MinimalECU.a2ldb") # Project and module pc = ProjectCreator(session) project = pc.create_project("MinimalECU", "Minimal ECU example") mc = ModuleCreator(session) module = mc.create_module("Engine", "Engine control", project=project) # Unit mc.add_unit(module, name="rpm", long_identifier="RPM", display="rpm", type_str="DERIVED") # Conversion cmc = CompuMethodCreator(session) cm = cmc.create_compu_method( "CM_RPM", "RPM conversion", "LINEAR", "%8.2", "rpm", module_name="Engine" ) cmc.add_coeffs_linear(cm, offset=0.0, factor=0.25) # Record layout rlc = RecordLayoutCreator(session) rl = rlc.create_record_layout("RL_UWORD", module_name="Engine") rlc.add_fnc_values(rl, position=1, datatype="UWORD", index_mode="ALTERNATE", address_type="DIRECT") # Measurement mec = MeasurementCreator(session) meas = mec.create_measurement( "EngineSpeed", "Current engine speed", "UWORD", "CM_RPM", resolution=1, accuracy=1.0, lower_limit=0.0, upper_limit=8000.0, module_name="Engine" ) mec.add_ecu_address(meas, 0x100000) # Characteristic cc = CharacteristicCreator(session) char = cc.create_characteristic( "IdleSpeed", "Target idle speed", "VALUE", 0x200000, "RL_UWORD", 0.0, "CM_RPM", 500.0, 1500.0, module_name="Engine" ) # Group grp = mc.add_group(module, name="BasicParams", long_identifier="Basic parameters") mc.add_group_ref_characteristic(grp, ["IdleSpeed"]) mc.add_group_ref_measurement(grp, ["EngineSpeed"]) # Commit and close mc.commit() db.close() # Export to A2L from pya2l import export_a2l export_a2l("MinimalECU", "MinimalECU.a2l") ``` -------------------------------- ### Using IfData flatmap for Lookups Source: https://pya2l.readthedocs.io/en/latest/ifdata.html This example shows how to use the `flatmap` attribute of the IfData object to efficiently access IF_DATA information. It iterates through all found keys and demonstrates direct lookups for specific tags like 'PROTOCOL_LAYER' and 'DAQ'. ```python from pya2l import DB from pya2l.api.inspect import Module session = DB().open_create("xcp_demo_autodetect.a2l") module = Module(session) ifd = module.if_data # IfData instance # Iterate all keys the parser found for key, values in ifd.flatmap.items(): print(f"{key}: {len(values)} occurrence(s)") # Direct look-up of a known tag if "PROTOCOL_LAYER" in ifd.flatmap: proto = ifd.flatmap["PROTOCOL_LAYER"] print("Protocol layer info:", proto) if "DAQ" in ifd.flatmap: daq = ifd.flatmap["DAQ"] print("DAQ configuration:", daq) ``` -------------------------------- ### Create Curve Record Layout Source: https://pya2l.readthedocs.io/en/latest/api_reference.html This example shows how to create a record layout for CURVE data, defining components for axis points and function values with specific data types and addressing. ```python # Curve layout (axis + values) rl2 = rlc.create_record_layout("RL_CURVE", module_name="Engine") pc.add_no_axis_pts_x(rl2, position=1, datatype="UBYTE") pc.add_axis_pts_x(rl2, position=2, datatype="UWORD", index_incr="INDEX_INCR", address_type="DIRECT") pc.add_fnc_values(rl2, position=3, datatype="UWORD", index_mode="ALTERNATE", address_type="DIRECT") ``` -------------------------------- ### Combine Parsed and Raw IF_DATA for Diagnostics Source: https://pya2l.readthedocs.io/en/latest/ifdata.html This example illustrates a diagnostic workflow by collecting both the parsed IF_DATA and the raw text for each measurement in a module. It generates a report containing the measurement name, parsed data, raw texts, and flatmap keys, useful for logging and review. ```python import json from pya2l import DB from pya2l.api.inspect import Module session = DB().open_create("my_project.a2l") module = Module(session) report = [] for meas in module.measurement.query(): ifd = meas.if_data if not ifd.if_data_parsed: continue entry = { "name": meas.name, "parsed": ifd.if_data_parsed, "raw_texts": [obj.raw for obj in ifd.if_data_raw], "flatmap_keys": list(ifd.flatmap.keys()), } report.append(entry) ``` -------------------------------- ### Create Common A2L Entities Programmatically Source: https://pya2l.readthedocs.io/en/latest/_sources/README.rst.txt Demonstrates creating common A2L entities such as units, CompuTabs, frames, transformers, and typedef structures using the Creator API. This example assumes an open database session. ```python from pya2l import DB from pya2l.api.create import ModuleCreator from pya2l.api.inspect import Module # Open or create a database session = DB().open_create("MyProject.a2l") # or .a2ldb mc = ModuleCreator(session) # Create a module mod = mc.create_module("DEMO", "Demo ECU module") # Units and conversions temp_unit = mc.add_unit(mod, name="degC", long_identifier="Celsius", display="°C", type_str="TEMPERATURE") ct = mc.add_compu_tab(mod, name="TAB_NOINTP_DEMO", long_identifier="Demo Tab", conversion_type="TAB_NOINTP", pairs=[(0, 0.0), (100, 1.0)], default_numeric=0.0) # Frames and transformers fr = mc.add_frame(mod, name="FRAME1", long_identifier="Demo frame", scaling_unit=1, rate=10, measurements=["ENGINE_SPEED"]) tr = mc.add_transformer(mod, name="TR1", version="1.0", executable32="tr32.dll", executable64="tr64.dll", timeout=1000, trigger="ON_CHANGE", inverse="NONE", in_objects=["ENGINE_SPEED"], out_objects=["SPEED_PHYS"]) # Typedefs and instances ts = mc.add_typedef_structure(mod, name="TSig", long_identifier="Signal", size=8) ``` -------------------------------- ### Extract KWP2000 Transport Data from IF_DATA Source: https://pya2l.readthedocs.io/en/latest/ifdata.html This example demonstrates how to extract KWP2000 (Keyword Protocol 2000) transport parameters, such as baud rates and timing, from the IF_DATA blocks. It specifically looks for the 'ASAP1B_KWP2000' key and processes 'TP_BLOB' and 'SOURCE' sub-blocks. ```python from pya2l import DB from pya2l.api.inspect import Module session = DB().open_create("if_kwp6.a2l") module = Module(session) for block in module.if_data.if_data_parsed: if not isinstance(block, dict): continue if "ASAP1B_KWP2000" not in block: continue kwp = block["ASAP1B_KWP2000"] print("KWP2000 transport parameters:") # TP_BLOB contains baud rates, timing, SERAM, checksum config if "TP_BLOB" in kwp: tp = kwp["TP_BLOB"] print(f" TP_BLOB: {tp}") # SOURCE blocks describe measurement channels if "SOURCE" in kwp: sources = kwp["SOURCE"] if not isinstance(sources, list): sources = [sources] for src in sources: print(f" SOURCE: {src}") ``` -------------------------------- ### CLI: Show help and options Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt Display the help message and available options for the `a2ldb-imex` command-line tool. ```console a2ldb-imex -h ``` -------------------------------- ### Filter A2L Characteristics by Name Prefix Source: https://pya2l.readthedocs.io/en/latest/_sources/faq.rst.txt Demonstrates filtering A2L characteristics based on a name prefix using a lambda function with the query method. This example finds characteristics starting with 'ENGINE_'. ```python # Get all characteristics with names starting with "ENGINE_" engine_chars = list(module.characteristic.query( lambda x: x.name.startswith("ENGINE_") )) ``` -------------------------------- ### Show CLI Help and Version Source: https://pya2l.readthedocs.io/en/latest/howto.html Display help information and available options for the `a2ldb-imex` command-line tool, or check its version. ```bash # Show help and available options a2ldb-imex -h ``` ```bash # Show version a2ldb-imex -V ``` -------------------------------- ### Install pyA2L using pip Source: https://pya2l.readthedocs.io/en/latest/README.html Install the pyA2ldb package using pip. Note that the package name is 'pya2ldb', not 'pya2l'. ```shell $ pip install pya2ldb ``` -------------------------------- ### CLI: Show version Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt Display the version of the `a2ldb-imex` tool. ```console a2ldb-imex -V ``` -------------------------------- ### Get Measurement Data Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Retrieves a Measurement object from a session and accesses its interface data. ```python from pya2l.api.inspect import Measurement m = Measurement.get(session, "ENGINE_SPEED") ifd = m.if_data # IfData instance ifd.if_data_parsed # List[Any] – structured dicts ifd.if_data_raw # list – original model objects ifd.flatmap # Dict[str, List[Any]] – lazy flat index ``` -------------------------------- ### Import and Query Module Components Source: https://pya2l.readthedocs.io/en/latest/_sources/README.rst.txt Demonstrates adding structure components and instances to a module, and then querying the number of frames and computation tabs. Requires an active session. ```python mc.add_structure_component(ts, name="raw", typedefName="UWORD", addressOffset=0) inst = mc.add_instance(mod, name="S1", long_identifier="Inst of TSig", type_name="TSig", address=0x1000) # Verify with inspect helpers mi = Module(session) print("#frames:", len(list(mi.frame.query()))) print("#compu tabs:", len(list(mi.compu_tab.query()))) ``` -------------------------------- ### CLI: Import A2L with multiple options Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt Combine multiple options for importing an A2L file: specify UTF-8 encoding, create the database in the local directory, and silence the progress bar. ```console a2ldb-imex -i examples\ASAP2_Demo_V161.a2l -E utf-8 -L -p ``` -------------------------------- ### Create Project with ProjectCreator Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Demonstrates how to create a new A2L project using the ProjectCreator. ```python from pya2l.api.create import ProjectCreator pc = ProjectCreator(session) project = pc.create_project("DemoProject", "Example ECU calibration") header = pc.add_header(project, "File comment / description") pc.add_project_no(header, "PRJ-001") pc.commit() ``` -------------------------------- ### CLI: Import A2L and create DB in current directory Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt Import an A2L file and create the resulting .a2ldb database file in the current working directory, rather than next to the input A2L file. ```console a2ldb-imex -i path/to/file.a2l -L ``` -------------------------------- ### Query Characteristics by Name Pattern Source: https://pya2l.readthedocs.io/en/latest/tutorial.html Find characteristics whose names start with a specific pattern, such as "ENGINE_". ```python specific_chars = list(module.characteristic.query( lambda x: x.name.startswith("ENGINE_") )) ``` -------------------------------- ### CLI: Import A2L with default settings Source: https://pya2l.readthedocs.io/en/latest/_sources/howto.rst.txt Import an A2L file using the `a2ldb-imex` tool. By default, this creates a corresponding .a2ldb file in the same directory as the input A2L file. ```console a2ldb-imex -i path/to/file.a2l ``` -------------------------------- ### Create Characteristic of type MAP Source: https://pya2l.readthedocs.io/en/latest/api_reference.html This example shows the creation of a 2-dimensional characteristic (MAP) and the definition of its two input axes, specifying their properties and ranges. ```python # MAP (2-D) c3 = cc.create_characteristic( "InjectionMap", "Fuel injection", "MAP", 0x320000, "RL_MAP", 0.0, "CM_Time", 0.0, 50.0, module_name="Engine" ) pc.add_axis_descr(c3, "STD_AXIS", "EngineSpeed", "CM_Speed", 16, 0.0, 8000.0) pc.add_axis_descr(c3, "STD_AXIS", "EngineLoad", "CM_Percent", 16, 0.0, 100.0) pc.commit() ``` -------------------------------- ### Create Characteristic of type VALUE Source: https://pya2l.readthedocs.io/en/latest/api_reference.html This example shows how to create a characteristic of type VALUE, representing a single scalar parameter with its associated properties and limits. ```python from pya2l.api.create import CharacteristicCreator cc = CharacteristicCreator(session) # VALUE (scalar) c1 = cc.create_characteristic( "IdleSpeed", "Target idle RPM", "VALUE", 0x300000, "RL_UWORD", 0.0, "CM_Speed", 500.0, 1500.0, module_name="Engine" ) ``` -------------------------------- ### Accessing Project and Module Information Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Shows how to initialize a Project object and access its name and header version. It also demonstrates iterating through modules and accessing a module directly by name. ```python from pya2l.api.inspect import Project, Module project = Project(session) print(project.name) # e.g. "DemoProject" print(project.header.version) # e.g. "1.0" # Iterate modules for mod in project.module: print(mod.name, mod.longIdentifier) # Direct access if you know the module name module = Module(session, "MyModule") ``` -------------------------------- ### Query Module Characteristics by Name Prefix Source: https://pya2l.readthedocs.io/en/latest/_sources/tutorial.rst.txt Retrieve characteristics whose names start with a specific prefix using a predicate function with the query() method. ```python starts = list(module.characteristic.query(lambda row: row.name.startswith("ENGINE_"))) ``` -------------------------------- ### Create A2L Module with Units and Conversions Source: https://pya2l.readthedocs.io/en/latest/README.html Demonstrates creating a module, adding units (like Celsius), and defining a CompuTab conversion method. Useful for augmenting existing A2L files programmatically. ```python from pya2l import DB from pya2l.api.create import ModuleCreator from pya2l.api.inspect import Module # Open or create a database session = DB().open_create("MyProject.a2l") # or .a2ldb mc = ModuleCreator(session) # Create a module mod = mc.create_module("DEMO", "Demo ECU module") # Units and conversions temp_unit = mc.add_unit(mod, name="degC", long_identifier="Celsius", display="°C", type_str="TEMPERATURE") ct = mc.add_compu_tab(mod, name="TAB_NOINTP_DEMO", long_identifier="Demo Tab", conversion_type="TAB_NOINTP", pairs=[(0, 0.0), (100, 1.0)], default_numeric=0.0) ``` -------------------------------- ### Function-Level API for Session Management Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Provides examples of using the function-level API for importing A2L files, opening existing sessions, and exporting A2L data. ```python from pya2l import import_a2l, open_existing, export_a2l session = import_a2l("file.a2l", encoding="utf-8", progress_bar=False) session = open_existing("file") export_a2l("file", "output.a2l") ``` -------------------------------- ### Show help and version for a2ldb-imex Source: https://pya2l.readthedocs.io/en/latest/_sources/configuration.rst.txt Use these commands to display the help message or the version information for the a2ldb-imex command-line tool. ```console a2ldb-imex -h # show help a2ldb-imex -V # show version ``` -------------------------------- ### Create Module with ModuleCreator Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Shows how to create a module and add various structural elements like units, groups, frames, typedefs, and instances using ModuleCreator. ```python from pya2l.api.create import ModuleCreator mc = ModuleCreator(session) module = mc.create_module("Engine", "Engine control", project=project) # Common settings mc.add_mod_common(module, "Module comment", byte_order="LITTLE_ENDIAN", data_size=32) # Units mc.add_unit(module, "rpm", "Revolutions per minute", display="rpm", type_str="DERIVED") mc.add_unit(module, "degC", "Degrees Celsius", display="°C", type_str="DERIVED") # Groups grp = mc.add_group(module, "EngineParams", "Engine parameters") mc.add_group_ref_measurement(grp, ["EngineSpeed", "CoolantTemp"]) mc.add_group_ref_characteristic(grp, ["IdleSpeed"]) # Frames mc.add_frame(module, "Frame1", "CAN frame", scaling_unit=1, rate=10, measurements=["EngineSpeed"]) # Typedef structures ts = mc.add_typedef_structure(module, "TSig", "Signal struct", size=4) mc.add_structure_component(ts, "raw", "UWORD", offset=0) mc.add_structure_component(ts, "status", "UBYTE", offset=2) # Instances mc.add_instance(module, "Signal1", "Instance of TSig", type_name="TSig", address=0x1000) mc.commit() ``` -------------------------------- ### Bridge ORM to Inspect API Source: https://pya2l.readthedocs.io/en/latest/api_reference.html Iterate through ORM query results and use the inspect API's get() method to retrieve corresponding objects for further inspection. ```python from pya2l.api.inspect import Measurement as MeasInspect import pya2l.model as model from pya2l import DB session = DB().open_existing("ASAP2_Demo_V161") measurements = ( session.query(model.Measurement) .filter(model.Measurement.datatype == "FLOAT32_IEEE") .order_by(model.Measurement.name) .all() ) for row in measurements: meas_obj = MeasInspect.get(session, row.name) print(f"{meas_obj.name}: {meas_obj.compuMethod.conversionType}") ``` -------------------------------- ### Create CompuMethod with Numeric and Verbal Range Tables Source: https://pya2l.readthedocs.io/en/latest/api_reference.html Demonstrates the creation of CompuMethods utilizing numeric tables (TAB_NOINTP) for interpolation and verbal range tables (TAB_VR) for defining discrete states. ```python # Numeric table ct = mc.add_compu_tab( module, "CT_Correction", "Correction factors", conversion_type="TAB_NOINTP", pairs=[(0, 1.0), (50, 1.05), (100, 1.12)], default_numeric=1.0, ) # Verbal range table vr = mc.add_compu_vtab_range( module, "VR_State", "Operating states", triples=[(0.0, 0.9, "OFF"), (1.0, 1.9, "STANDBY"), (2.0, 10.0, "RUN")], default_value="UNKNOWN", ) pc.commit() ``` -------------------------------- ### A2L Database Import/Export CLI Source: https://pya2l.readthedocs.io/en/latest/README.html Demonstrates command-line usage for the `a2ldb-imex` tool. Use `-i` to import, `-e` to export, `-E` for encoding, `-L` to create DB in CWD, and `-o` to specify output file. ```bash $ a2ldb-imex -V ``` ```bash $ a2ldb-imex -i path/to/file.a2l ``` ```bash $ a2ldb-imex -i path/to/file.a2l -E latin-1 -L ``` ```bash $ a2ldb-imex -e path/to/file.a2ldb -o exported.a2l ``` -------------------------------- ### Determine file encoding using 'file' and 'chardetect' Source: https://pya2l.readthedocs.io/en/latest/faq.html Use the `file` command to get basic file type information and `chardetect` to identify the character encoding of a file. ```bash $ file examples/tst.a2l examples/tst.a2l: UTF-8 Unicode (with BOM) text ``` ```bash $ chardetect examples/tst.a2l examples/tst.a2l: UTF-8-SIG with confidence 1.0 ``` ```bash $ file XCPlite-0002E248-5555.A2L XCPlite-0002E248-5555.A2L: ASCII text, with very long lines ``` ```bash $ chardetect XCPlite-0002E248-5555.A2L XCPlite-0002E248-5555.A2L: ascii with confidence 1.0 ``` -------------------------------- ### Import and Open A2L Sessions Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Demonstrates how to obtain a SessionProxy object using the DB class for parsing A2L files into SQLite databases, opening existing databases, or creating new ones. ```python from pya2l import DB db = DB() # Parse A2L → SQLite (creates .a2ldb) session = db.import_a2l("ASAP2_Demo_V161.a2l") # Open existing database (fast, no reparsing) session = db.open_existing("ASAP2_Demo_V161") # Open-or-create (convenience method) session = db.open_create("ASAP2_Demo_V161.a2l") ``` -------------------------------- ### Export Measurements to Excel using Pandas Source: https://pya2l.readthedocs.io/en/latest/howto.html Use the pandas library to query A2L measurements and export selected fields to an Excel file. Ensure 'pandas' and 'openpyxl' are installed. ```python import pandas as pd from pya2l import DB, model session = DB().open_existing("ASAP2_Demo_V161") q = ( session.query( model.Measurement.name, model.Measurement.datatype, model.Measurement.conversion, model.Measurement.ecu_address, ) .order_by(model.Measurement.name) ) df = pd.read_sql(q.statement, session.bind) df.to_excel("measurements.xlsx", index=False) ``` -------------------------------- ### Create CompuMethods with CompuMethodCreator Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Illustrates the creation of different types of CompuMethods (LINEAR, RAT_FUNC, TAB_VERB) and CompuTabs using CompuMethodCreator. ```python from pya2l.api.create import CompuMethodCreator cmc = CompuMethodCreator(session) # LINEAR: phys = factor * raw + offset cm = cmc.create_compu_method( "CM_Temp", "Temperature", "LINEAR", "%6.1", "°C", module_name="Engine" ) cmc.add_coeffs_linear(cm, offset=-40.0, factor=0.1) # RAT_FUNC: rational polynomial cm2 = cmc.create_compu_method( "CM_Pressure", "Pressure", "RAT_FUNC", "%8.3", "bar", module_name="Engine" ) cmc.add_coeffs(cm2, a=0, b=0.01, c=-1.0, d=0, e=0, f=1) # TAB_VERB: enumeration cm3 = cmc.create_compu_method( "CM_GearPos", "Gear", "TAB_VERB", "%d", "", module_name="Engine" ) # Numeric table ct = mc.add_compu_tab( module, "CT_Correction", "Correction factors", conversion_type="TAB_NOINTP", pairs=[(0, 1.0), (50, 1.05), (100, 1.12)], default_numeric=1.0, ) # Verbal range table vr = mc.add_compu_vtab_range( module, "VR_State", "Operating states", triples=[(0.0, 0.9, "OFF"), (1.0, 1.9, "STANDBY"), (2.0, 10.0, "RUN")], default_value="UNKNOWN", ) cmc.commit() ``` -------------------------------- ### Create Group Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Organizes related A2L elements into groups, allowing for hierarchical structuring. This example creates a group for basic engine parameters and references characteristics, measurements, and subgroups. ```python from pya2l.api.create import GroupCreator gc = GroupCreator(session) grp = gc.create_group("EngineBasic", "Basic engine parameters", module_name="Engine") gc.add_root(grp) gc.add_ref_characteristic(grp, ["IdleSpeed", "ThrottleCurve"]) gc.add_ref_measurement(grp, ["EngineSpeed"]) gc.add_sub_group(grp, ["AdvancedParams"]) gc.commit() ``` -------------------------------- ### Using the Inspect API to query measurements by datatype Source: https://pya2l.readthedocs.io/en/latest/getting_started.html Filter and retrieve measurements based on their data type. This example shows how to find all FLOAT32_IEEE measurements within a specific module. ```python # Query all FLOAT32 measurements float_meas = list(module.measurement.query( lambda row: row.datatype == "FLOAT32_IEEE" )) print(f"\nFLOAT32 measurements: {len(float_meas)}") for fm in float_meas: print(f" {fm.name}") ``` -------------------------------- ### Setting up IfDataParser on Session Source: https://pya2l.readthedocs.io/en/latest/_sources/ifdata.rst.txt Initialize the IF_DATA parser at the session level, enabling session.parse_ifdata() for use with measurement objects. ```python from pya2l import DB db = DB() session = db.open_existing("ASAP2_Demo_V161") # Initialize the IF_DATA parser for this session session.setup_ifdata_parser(loglevel="DEBUG") # Now session.parse_ifdata() is available import pya2l.model as model meas_obj = session.query(model.Measurement).filter_by(name="SomeMeasurement").first() if meas_obj: parsed = session.parse_ifdata(meas_obj.if_data) print(parsed) ``` -------------------------------- ### Filter A2L Measurements by Data Type Source: https://pya2l.readthedocs.io/en/latest/_sources/faq.rst.txt Use lambda functions with the query method to filter A2L elements. This example retrieves all measurements with the FLOAT32_IEEE data type from a module. ```python from pya2l import DB from pya2l.api.inspect import Project db = DB() session = db.open_create("ASAP2_Demo_V161.a2l") project = Project(session) module = project.module[0] # Get all measurements with FLOAT32_IEEE data type float_measurements = list(module.measurement.query( lambda x: x.datatype == "FLOAT32_IEEE" )) ``` -------------------------------- ### Create Measurements with MeasurementCreator Source: https://pya2l.readthedocs.io/en/latest/_sources/api_reference.rst.txt Demonstrates creating scalar, matrix, and symbol-linked measurements using MeasurementCreator, including setting various properties like limits, resolution, and ECU addresses. ```python from pya2l.api.create import MeasurementCreator mec = MeasurementCreator(session) # Basic scalar measurement m = mec.create_measurement( "EngineSpeed", "Engine RPM", "UWORD", "CM_Speed", resolution=1, accuracy=1.0, lower_limit=0.0, upper_limit=8000.0, module_name="Engine" ) mec.add_ecu_address(m, 0x100000) mec.add_format(m, "%8.2") mec.add_byte_order(m, "LITTLE_ENDIAN") mec.add_display_identifier(m, "EngSpd") # Matrix measurement m2 = mec.create_measurement( "TempGrid", "Temperature sensor array", "SWORD", "CM_Temp", resolution=1, accuracy=0.1, lower_limit=-40.0, upper_limit=150.0, module_name="Engine" ) mec.add_matrix_dim(m2, dims=[4, 4]) mec.add_ecu_address(m2, 0x200000) # Symbol-linked measurement (no direct address) m3 = mec.create_measurement( "VirtualSignal", "Computed signal", "FLOAT32_IEEE", "CM_Voltage", resolution=1, accuracy=0.01, lower_limit=0.0, upper_limit=5.0, module_name="Engine" ) mec.add_symbol_link(m3, "g_voltage_sensor", offset=0) mec.commit() ``` -------------------------------- ### Using the Inspect API to query characteristics by type Source: https://pya2l.readthedocs.io/en/latest/getting_started.html Filter and retrieve characteristics based on their type. This example demonstrates how to find all characteristics of type 'MAP' and display their number of axes and shape. ```python # Query characteristics by type maps = list(module.characteristic.query( lambda row: row.type == "MAP" )) print(f"\nMAP characteristics: {len(maps)}") for c in maps: print(f" {c.name}: {c.num_axes} axes, shape={c.fnc_np_shape}") ``` -------------------------------- ### Open or Create A2L Database Source: https://pya2l.readthedocs.io/en/latest/_sources/tutorial.rst.txt Use open_create() to open an existing database or create a new one if it doesn't exist. Can be used with or without the .a2ldb extension. ```python session = db.open_create("ASAP2_Demo_V161.a2l") # Creates database from A2L file # or session = db.open_create("ASAP2_Demo_V161") # Opens existing database ``` -------------------------------- ### Using the Inspect API to get a measurement Source: https://pya2l.readthedocs.io/en/latest/getting_started.html Retrieve a specific measurement by name using the Inspect API. You can access its properties like data type, ECU address, limits, and CompuMethod. ```python # Get a measurement by name m = Measurement.get(session, "ASAM.M.SCALAR.UBYTE.IDENTICAL") print(f"Name: {m.name}") print(f"Data type: {m.datatype}") print(f"Address: 0x{m.ecuAddress:08X}") print(f"Limits: [{m.lowerLimit}, {m.upperLimit}]") print(f"CompuMethod: {m.compuMethod.conversionType}") ```