TTA Documentation Release 1.15.2

MAGNA Telemotive GmbH

Dec 18, 2019 CONTENTS

1 How to install TTA 1 1.1 Install steps...... 1 1.1.1 Follow the Installer Instructions...... 2 1.1.2 Check if my installation is complete...... 4 1.1.3 Check if path is set...... 6 1.1.4 Eclipse...... 6 1.2 Basic Functionality...... 6

2 Getting Started Tutorial 7 2.1 Your first test run (use of the GUI)...... 7 2.2 Write Testcases (use of the IDE)...... 9 2.3 Configure your Test setup...... 9

3 How to test with TTA ? 11 3.1 Start the TTA GUI...... 11 3.2 Test cases database / Test cases pool...... 11 3.3 Run a single test...... 12 3.4 Use of test parameters...... 12 3.5 Build a test sequence...... 14 3.6 Build a test sequence with test parameters...... 14 3.7 Run a test sequence...... 15 3.8 Run a test sequence randomly shuffled...... 17 3.9 Open the test report...... 18 3.10 Control more than one computer with TTA...... 18 3.11 Import tests from Git...... 18 3.12 Import tests from Apache Subversion...... 18

4 TTA test case generator 21 4.1 Start the script in Eclipse...... 21 4.2 Generate the test case in the GUI...... 21 4.3 Keyword Mapping...... 22

5 How to create a TTA test case script 23 5.1 Simple Test Case...... 23 5.2 Advanced Test Case...... 24 5.2.1 Execution order...... 25 5.2.2 Test step function naming conventions...... 25 5.2.3 Test initialization...... 26 5.2.4 Test step documentation and reports...... 26 5.2.5 Assert functions...... 27

i 5.2.5.1 Arguments and return type...... 27 5.2.5.2 Multiple asserts per test step...... 28 5.2.5.3 Assert types / automatic sub steps...... 29 5.2.5.4 Set a step result with an exception...... 29 5.2.6 Reporting...... 31 5.2.7 Error handling...... 31 5.3 Assert functions reference...... 32 5.4 Simple Test Case reference...... 38 5.5 Advanced Test Case reference...... 39

6 Tutorial Testcase Parameters 41 6.1 Getting started:...... 41 6.2 Operation...... 42 6.3 Additional Documentation...... 42

7 TTA Runner Reference 45 7.1 tta.runner.runner...... 45 7.2 Runner and Suite for Test Case execution...... 47 7.2.1 tta.runner package reference...... 47

8 Reporting 52 8.1 Overall overview...... 52 8.1.1 Report Structure...... 52 8.1.2 Basic Usage...... 53 8.1.3 HTML report structure...... 54 8.1.4 PDF report structure...... 54 8.2 Single test case overview...... 54 8.3 Test run protocol...... 55 8.3.1 tta.reporting package reference...... 55 8.4 tta.reporting.report...... 55 8.5 tta.reporting.bindings...... 57 8.6 tta.reporting.constants...... 62 8.7 tta.reporting.htmlconverter...... 63

9 Device configuration 64 9.1 Telemotive data loggers...... 64

10 XML-Description of a test case 66 10.1 XML Structure...... 66 10.2 Structure of a TestStep...... 66 10.3 Example...... 67

11 TTA dynamic code completion 68 11.1 Trigger on Save...... 68 11.2 Trigger on Open...... 68

12 TTA Lib Reference 69 12.1 tta.lib.catalog...... 69 12.1.1 tta.lib.catalog.MessageCatalogParser...... 69 12.1.2 tta.lib.catalog.fibex module...... 70 12.1.3 tta.lib.catalog.arxml module...... 71 12.1.4 resulting dictionary (CAN)...... 72

13 TTA Units Reference 74 13.1 tta.units.android.android...... 74 ii 13.2 tta.units.android.logcat...... 76 13.2.1 Logcat Unit...... 76 13.2.2 basic logcat usage...... 78 13.2.3 Advanced logcat usage...... 79 13.3 tta.units.audio...... 80 13.3.1 How to use the audio unit...... 80 13.3.1.1 Signal...... 80 13.3.1.2 Recorder...... 81 13.3.1.3 Player...... 81 13.3.1.4 Identification...... 82 13.3.1.5 Signal processing...... 82 13.3.1.6 Speech processing...... 83 13.3.1.7 Plotting...... 84 13.3.1.8 Module...... 84 13.4 tta.units.can.bpng...... 87 13.5 tta.units.can...... 89 13.5.1 CAN - CAN unit...... 89 13.5.2 CANMessage, CANMsgType - CAN messages...... 90 13.5.3 Sending CAN messages...... 92 13.5.4 Receiving CAN messages...... 92 13.5.5 CANFilter, CANFilterRange, CANFilterType - CAN filter for EventSources...... 93 13.6 tta.units.datalogger.datalogger...... 95 13.7 tta.units.ethernet...... 96 13.8 Ethernet Unit...... 96 13.8.1 Identify your Ethernet Interfaces...... 97 13.8.2 Configure the Network Adapter...... 97 13.8.3 Send Messages...... 98 13.8.3.1 Send single message...... 98 13.8.3.2 Send multiple data...... 99 13.8.3.3 Send data contained in a pcap file...... 100 13.8.4 Capture Packets...... 101 13.8.5 Convenience Functions...... 103 13.8.6 Ethernet Protocols...... 104 13.8.7 Ethernet...... 104 13.8.8 IP...... 105 13.8.9 ICMP...... 106 13.8.10 ARP...... 107 13.8.11 UDP...... 108 13.8.12 TCP...... 108 13.8.13 DHCP...... 109 13.8.14 SomeIP...... 110 13.8.15 SomeIPSD...... 110 13.8.16 RawPacket...... 111 13.9 tta.units.flash...... 111 13.9.1 Flash - Flash unit...... 112 13.9.1.1 Flash functions...... 112 13.9.1.2 Generic flash functions...... 117 13.9.2 FlashResult...... 119 13.10 tta.units.ftp...... 120 13.10.1 FTP - FTP unit...... 120 13.11 tta.units.imagegrabber.imagegrabber...... 121 13.11.1 ImageGrabber - image grabber unit...... 121 13.11.2 Drivers...... 121 13.12 tta.units.imageprocessing.animation...... 123

iii 13.12.1 How to use the ImageprocessingAnimation unit...... 123 13.12.1.1 Importing and comparing videos...... 123 13.12.1.2 Searching specific frames...... 123 13.12.1.3 Other Functions...... 124 13.12.2 Comparison Algorithms...... 124 13.13 tta.units.imageprocessing.warping...... 128 13.13.1 ImageProcessingWarping - Warping unit...... 128 13.14 tta.units.isotp.isotp...... 130 13.15 tta.units.multimeter...... 131 13.15.1 Initializing the unit...... 131 13.15.2 Physical Quantities...... 131 13.15.3 Reading data...... 132 13.15.4 Displaying data...... 132 13.15.5 Setting measurement mode...... 132 13.16 tta.units.ocr.ocr...... 132 13.16.1 OCR Unit...... 132 13.16.2 Initializing the unit...... 132 13.16.3 Recognize Functionality...... 133 13.16.4 Bounding Boxes and Color Representation with tesseract...... 133 13.16.5 Tesseract segmentation modes...... 134 13.16.6 Optional Config Options for tesseract...... 134 13.16.7 Unit Reference...... 134 13.17 tta.units.odx...... 135 13.17.1 PDX - PDX unit...... 135 13.17.2 ODX - ODX unit...... 136 13.17.2.1 Attribute access...... 136 13.17.2.2 ODX Links...... 138 13.17.2.3 Flash order and access...... 139 13.17.2.4 ODX flash objects...... 139 13.18 tta.units.pcap.pcap...... 143 13.19 tta.units.powersupply.powersupply...... 144 13.20 tta.units.ptc...... 146 13.20.1 PTC Verdicts...... 146 13.20.2 PTC - PTC unit...... 146 13.21 tta.units.pwm...... 149 13.21.1 PWM Unit...... 149 13.21.2 Custom Drivers...... 150 13.22 tta.units.qpst...... 151 13.22.1 QPST Unit...... 151 13.22.2 QPST Automation Server...... 155 13.23 tta.units.qxdm.qxdm...... 157 13.24 tta.units.relay:...... 159 13.24.1 Relay Unit...... 159 13.24.2 Conrad8RelayBoard-Driver...... 160 13.24.3 Initializing the unit...... 161 13.24.4 Setting Relays...... 161 13.24.5 Getting relay states...... 162 13.24.6 Toggle relays...... 162 13.24.6.1 Reset...... 162 13.25 tta.units.serial...... 163 13.25.1 Serial Unit...... 163 13.25.2 Sending data...... 164 13.25.3 Reading data...... 164 13.25.3.1 Synchronous reading:...... 164 iv 13.25.3.2 Asynchronous reading:...... 164 13.25.3.3 Timeouts...... 165 13.25.4 Implemented Drivers...... 165 13.26 tta.units.template.template...... 166 13.27 tta.units.term.term...... 166 13.28 tta.units.timer.event_source...... 167 13.29 tta.units.timer.timer...... 167 13.30 tta.units.uds...... 168 13.30.1 UDS - UDS unit...... 168 13.30.2 UDSType...... 175 13.30.2.1 UDSType.Error...... 175 13.30.2.2 UDSType.Session...... 176 13.30.2.3 UDSType.Security...... 176 13.30.2.4 UDSType.Reset...... 178 13.30.2.5 UDSType.Communication...... 179 13.30.2.6 UDSType.CommunicationNet1...... 179 13.30.2.7 UDSType.CommunicationNet2...... 180 13.30.2.8 UDSType.DTCSetting...... 181 13.30.2.9 UDSType.DTCSettingOption...... 181 13.30.2.10UDSType.Link...... 181 13.30.2.11UDSType.LinkMode...... 182 13.30.2.12UDSType.DTCClear...... 182 13.30.2.13UDSType.DTCRead...... 182 13.30.2.14UDSType.DTCReadStat...... 183 13.30.2.15UDSType.InputOutputPar...... 183 13.30.2.16UDSType.InputOutputState...... 184 13.30.2.17UDSType.Routine...... 184 13.30.2.18UDSType.DataFormat...... 184 13.31 tta.units.vector.canoe...... 185 13.31.1 CANoe unit...... 185 13.31.2 Executing CAPL Functions...... 191 13.31.3 CANoeNode - Using Nodes...... 191 13.31.4 CANoeDiagnostic - Using the Diagnostic Module...... 192 13.31.5 CANoeSignal - Using Signals...... 194 13.31.6 EnvVariable - Accessing Environment Variables...... 195 13.31.7 SysVariable - Accessing System Variables...... 196 13.31.8 TestModule, TestReport - Running CANoe Test Cases...... 197

14 How to create a TTA unit? 200 14.1 Unit capabilities...... 200 14.1.1 Unit usage...... 200 14.1.2 Unit configuration...... 201 14.1.3 Unit logging...... 201 14.1.4 Thread-safe access to unit methods: async_func decorator...... 201 14.1.5 Making the unit dispatch events...... 202 14.2 Implementing a complete unit...... 202 14.2.1 Define, initialize, shut down and add methods...... 203 14.2.2 Use other units in your unit...... 203

15 TTA Core Reference 205 15.1 tta.core.config_manager...... 205 15.2 tta.core.config_units.generate...... 207 15.3 tta.core.context...... 208 15.4 tta.core.event.event...... 210

v 15.5 tta.core.event.filter...... 210 15.6 tta.core.event.source...... 213 15.7 tta.core.exception...... 216 15.8 tta.core.logger...... 217 15.9 tta.core.unit_base...... 218 15.10 tta.core.unit_driver_base...... 221 15.11 tta.core.unit_exception...... 222 15.12 tta.core.unit_manager...... 222 15.13 tta.core.util...... 227

16 Tutorial TTA Configuration 229

17 Tutorial Android unit (tta.units.android) 231 17.1 Getting started:...... 231 17.2 Operation...... 231 17.3 Initialize the AndroidBase Unit...... 232 17.4 Send a Command to the Device...... 232 17.5 Send a sequence of Commands to the Device...... 232 17.6 Logcat Unit...... 233 17.7 Basic Logcat usage...... 233 17.8 Advanced Logcat usage...... 234 17.9 AndroidIO incl. AndroidDeviceManager...... 235 17.10 Testcase example...... 236

18 Tutorial Relay unit (tta.units.relay) 238 18.1 Getting started:...... 238 18.2 Operation...... 238 18.3 Additional Documentation...... 239

19 Tutorial Serial unit (tta.units.serial) 240 19.1 Creating a Serial Unit...... 240 19.2 Functions of the Serial Unit...... 242 19.3 Sending...... 242 19.3.1 Receiving...... 243 19.3.2 Configuring...... 245 19.3.3 Method overview...... 247 19.4 Using Eventsources...... 251 19.5 Available Drivers...... 253 19.5.1 Driver: pySerial (default)...... 253 19.5.2 Driver: Virtual...... 256 19.5.3 Add custom driver...... 260 19.6 Additional Documentation...... 263

20 Tutorial Testcase Substeps 264 20.1 Getting Started...... 264 20.2 Additional Documentation...... 264

21 License 265 21.1 Python Packages...... 265

22 Tutorial Update License 283 22.1 Getting started:...... 283 22.2 Operation...... 284

23 FAQ & Contact 285 vi 23.1 Your most frequently asked questions...... 285 23.2 How to contact us...... 286

Python Module Index 287

vii CHAPTER ONE

HOW TO INSTALL TTA

This document guides you through the TTA Installation and helps you verify the correct installation of all necessary files. The installation of TTA is very simple, as the TTA installer installs all the softwares and packages you need to use TTA.

1.1 Install steps

After you have downloaded the TTA_Installer_base_XXX.exe or your respective custom installer you can simply exe- cute it.

Note: You need administrator priviledges to install for all users.

Fig. 1: TTA Installation Startscreen.

If TTA is already installed, this should be detected by the installer and you will be asked to deinstall the old version during the installation process.

Warning: In case there exists a TTA installation for another user on your machine and you want to install for all users, please deinstall it before running the installer. The installer can not detect TTA installations of other users.

1 TTA Documentation, Release 1.15.2

1.1.1 Follow the Installer Instructions

The installer asks you at first to accept the License-Agreement. Afterwards, please select the startmenu-folder you want to place your TTA shortcuts in:

Fig. 2: Accept License Agreement.

You can now configure your TTA installation. Hereby you should choose between a system-wide or a private Python installation. Choosing the system-wide installation you may use an existing system-wide version (C:\Python36). This installation makes Pyhton available for all applications on your computer. In contrast, the private installation (C:\Program Files(x86)\MAGNA Telemotive\TTA\Python36) creates a special Python partition for TTA, which is exclusively used by TTA. Furthermore you may specify the packages you want to install alongside your new Python installation. We recommend you do not exclude any of the pre-choosen packages, since this might lead to an unusable TTA. The Doc generation package however is exlcuded from the installation, as it only contains some sphinx packaged that generate the doc- umentation you are reading right now. A precompiled version of the documentation is delivered with your standard TTA Installation anyway. If you have an extension package you can just place it in the same directory as the installer. The installer will find it on startup and show it in the section “TTA Packages”.

Warning: Do not update the pycryptodome or yubikey packages later on as they may cause problems with TTA.

Checking the IDE checkbox ensures the installation of a custom version of Eclipse Mars.2. However, if you want to use your own IDE, you should skip this step. The installer then installs the following elements on your computer (if you keep them checked) : • Python 3.6 • The required Python-packages (via pip-install) • Eclipse (The IDE TTA is using.) • The TTA packages (Those packages contain new functionalities for TTA. They are customer-specific.)

2 Chapter 1. How to install TTA TTA Documentation, Release 1.15.2

Fig. 3: Choose Location of Shortcuts.

Fig. 4: Configuration of your TTA installation.

1.1. Install steps 3 TTA Documentation, Release 1.15.2

• The TTA GUI (It enables you to run test cases in a user-friendly environment.) • The TTA Documentation

Note: This setup installs no external drivers. If you want to use 3rd party hardware you have to install the necessary drivers manually.

1.1.2 Check if my installation is complete

If all went well you should now see the three TTA Icons on your Desktop. Start the TTA GUI by simply double- clicking the TTA Start Icon. • ‘TTA-Eclipse’ opens the IDE Eclipse where you can implement your test cases or new TTA Units. • ‘TTA-Start’ starts the TTA Server which enables you to run the test cases through the GUI and opens the TTA GUI, which is in fact a local website. • ‘TTA-Manual’ opens a local version of the TTA documentation in the web-browser. This documentation is the one related to your current version of TTA.

Fig. 5: The TTA-icons on the desktop.

You might review the successful installation by checking that the TTA folder (C:\Program Files(x86)\MAGNA Tele- motive\TTA) contains all files (compare the screenshot of a private Python installation below). If you have chosen a system-wide installation the Python36 folder is located at C:\Python.

Fig. 6: TTA Folder Structure.

Your Python36\Lib\site-packages folder should contain the tta, tta_demo, tta_base and tta_gui packages as shown below: Finally, your Public Folder (C:\Users\Public\Documents) should contain your tta_workspace, which is linked to your TTA Eclipse Installation. All projects created in Eclipse are stored in this folder by default.

4 Chapter 1. How to install TTA TTA Documentation, Release 1.15.2

Fig. 7: Python Site-Packages containing the corresponding TTA packages.

Fig. 8: TTA Workspace Folder.

1.1. Install steps 5 TTA Documentation, Release 1.15.2

1.1.3 Check if path is set

You should set the path to your Python installation in the Environmental Variables. If you want to use pip from inside any folder you can add the corresponding Scripts folder manually to your Environmental Variables as well. • PATH: C:\Python36 • PATH: C:\Python36\Scripts You might check the correct setup by starting a console window (windows key+r -> cmd) and type the following commands. This should not throw any exceptions similar to the screenshot below: • python • import tta

Fig. 9: Import TTA with Python.

1.1.4 Eclipse

When opening TTA Eclipse for the first time you should see these sample projects:

Fig. 10: TTA Eclipse first startup.

1.2 Basic Functionality

For a quick guide on how to start the GUI and a final check of the tool’s basic functionality, please visit our Getting Started Tutorial.

6 Chapter 1. How to install TTA CHAPTER TWO

GETTING STARTED TUTORIAL

2.1 Your first test run (use of the GUI)

When you start TTA for the first time, you will need first to accept our General Conditions, specified in the displayed disclaimer. If you disagree with the content of our disclaimer, decline it and please contact us as fast as possible.

Fig. 1: TTA disclaimer.

Once our General Conditions accepted, you will be able to run your first test case. The aim of this test case is to check that the installation of TTA has been successful. Open the test case testcase_example, and run it. This test case will open a Folder Explorer and write an Excel document called ‘test’ in the path of the GUI. After the execution of the test, the result ‘Passed’ should be displayed on the bottom left-hand corner under the window containing the traces. If you want to get more details about the TTA GUI and for example how to built test sequences, please visit its dedicated documentation page How to test with TTA ?. You can then open the test report in order to get a quick overview of the structure of TTA test reports. This report is located in the path specified in the Result_path field.

7 TTA Documentation, Release 1.15.2

Fig. 2: TTA GUI with the most important fields highlighted.

Fig. 3: Exemplary test report.

8 Chapter 2. Getting Started Tutorial TTA Documentation, Release 1.15.2

The report is composed of an header which sums up all the informations about your test (name, description, result, execution date and time), and a ‘Test Run Protocol’. The test result is divided in 3 sections: - Preconditions - Steps - Postconditions Each test step is also divided in 4 elements: a description of the test step, its expected result, its actual result and the statement. For each step is its start time and its duration specified. For more informations about the Report structure, especially the three-layer-report, please go to HTML report struc- ture.

2.2 Write Testcases (use of the IDE)

Now that you know how to run test cases with TTA, you can start to develop your own test cases! Click on the ‘TTA-Eclipse’ icon to open the IDE. This will open Eclipse and display the TTA workspace. You can then for example open the test case testcase_example_assert, and see how the TTA test cases are implemented. This test case is implemented as a AdvancedTestCaseBase. Those tests are built with test steps, each step does an action and have an assert statement at the end. The name of the step defines if its a precondition, step or postcondition.

Fig. 4: The TTA configured Eclipse IDE.

You can also generate a test stub of your test case by importing test specifications in TTA-XML, TTA-XLS or TTA- XLSX Format within the GUI. You can find more informations here: TTA test case generator. If you want to modify already existing test cases, you can open them directly from the GUI by clicking on the ‘Edit in IDE’ button. This will directly open the corresponding test case in Eclipse. For more details about the test case structure in TTA, please check How to create a TTA test case script.

2.3 Configure your Test setup

Before you can test something with TTA and real devices, you will need to set the Environment Variables of your computer. Those variables are defining your setup: “address” of the device you want to control (IP Address of a Telemotive HW, COM port of a relay-card, Port to use from a Vector HW, IP Address to use for your computer in case of Ethernet Tests etc. . . Those Environment variables are defined in tta_code/tta/config/default_config.yaml.

2.2. Write Testcases (use of the IDE) 9 TTA Documentation, Release 1.15.2

For more informations on how to configure your setup, please read: tta_tutorial_environment_variables. In the future, it will be possible to configure your Setup directly in the TTA GUI.

10 Chapter 2. Getting Started Tutorial CHAPTER THREE

HOW TO TEST WITH TTA ?

This module provides info regarding testing with the GUI. The TTA-GUI provides a user-friendly interface, which enables to quickly create a test-sequence, by drag-and-drop.

3.1 Start the TTA GUI

In order to start the GUI, click on the TTA-Start Icon. This will start the TTA-Server and open the TTA GUI in your favorite browser. The TTA GUI will enable you to communicate with the TTA Server, in order to run/build test cases or test sequences. The structure of the TTA server will also enable you to control remotely the computer where the TTA Server is currently running, and therefore enable you to run test sequences remotely.

3.2 Test cases database / Test cases pool

The runnable test cases are displayed on the left side of the GUI. In order to be available in the GUI, the test cases need to be stored in the tta_testcases folder. If the test cases are stored in sub-folders, the sub-folders will also be displayed in the TTA GUI.

Fig. 1: Structure of the TTA GUI. Here is pictured how test cases can be preserved in sub-folders.

11 TTA Documentation, Release 1.15.2

3.3 Run a single test

If you quickly want to run a single test, you can directly select it in the test cases database. Then eventually select the path where to store the result and the amount of repetitions of the test you want to run and click on the start button.

Fig. 2: Settings for running a test case and storing results. It is shown that the “testcase_example” was picked to run one time and the result will be preserved in the path “logs”.

The traces block will open and the test case will start running.

Fig. 3: Displaying traces block and status. The actual status of this example is that it’s running and the console shows the test logs.

At the end of the execution of the test case, the status of the test case will be displayed as “Passed”, “Incomplete”, “Failed”, “Blocked” or “Canceled”. It is possible to filter the run log with the search bar and a log level selector.

3.4 Use of test parameters

In some cases, you might want to use test parameter, in order to give special files (diagnostic catalog, etc. . . ) or values (ECU version, number of CAN channels, etc. . . ) as variables to the test case. This can be done in TTA. If a test case uses test parameters, it will be displayed in the GUI. The name of the test parameters will be the same as the one specified in the test case. Those test parameters can be from different types (int, string, float) and will be displayed differently.

12 Chapter 3. How to test with TTA ? TTA Documentation, Release 1.15.2

Fig. 4: Status after the test ended. The result for this example is shown in green for “Passed” and on the left side of the GUI, next to all already implemented and passed test cases etc., a green check-symbol shows up.

Fig. 5: Setting the test parameter. For this example, the parameters integer and string were chosen. In order to facilitate the modification of string as test parameters, the initial value of the string will always be saved and can be restored by clicking on undo button on the right of the input field.

3.4. Use of test parameters 13 TTA Documentation, Release 1.15.2

3.5 Build a test sequence

If you want to run more than one single test, create a test sequence. To create a test sequence, click on the “Add test sequence button”. An empty test sequence will be generated. The name of the test sequence can be edited by the user.

Fig. 6: Building a new test sequence. In this example, the blue circles display which buttons must be clicked to build a test sequence, where test sequences are preserved and how to change it’s name.

If you want to add test cases in the test sequence, drag and drop them from the test case database into the sequence. You can also set the amount of repetitions of the test sequence, or the amount of repetitions of a test case in a test sequence, by clicking on it and changing the number in the field “Repetitions”.

Fig. 7: Adding test cases to a test sequence. “testcase_example_assert” has been moved from the test case database to the “Testsequence_1” and in this case, the test sequence will run one time only.

If your test cases are located in a sub-folder, you can directly drag and drop a whole folder in a test sequence. This sub-folder will be displayed as a sub-test-sequence in the test-sequence.

3.6 Build a test sequence with test parameters

When you are using test parameters, you might want to set the value of a parameter for a whole test sequence, or in some particular test cases, just for one test. This can be done via the two buttons (write and lock), displayed in a test sequence, containing test cases using test parameters.

14 Chapter 3. How to test with TTA ? TTA Documentation, Release 1.15.2

The write button enables you to set the value of the test parameter in all the test cases contained in the test sequence, except, if the lock button of a test case is set. The lock button enables you to ‘lock’ a test parameter from a test case or a test sequence when you are overwriting it. In this case, the test case or test sequence will keep the test parameter at its current value. You can lock parameters in test cases or directly in test sequences, if you are using sub-test-sequences.

Fig. 8: Detailed GUI view of a enabled locker. In the example, the locker is black, which means it’s blocked, the locked test parameter is always displayed in a striped background.

While a parameter, which can be overwritten, will be displayed in a uniform background.

Fig. 9: Detailed GUI view of a disabled locker. Here, the locker is displayed in grey, which means the masking feature is disabled. The parameter could get overwritten, because the “lock” button wasn’t selected.

If a test contains tests with test parameters, you will overwrite this parameter for all the unlocked test parameters in the test sequence, by clicking on the “write” button of a test parameter.

Fig. 10: Position of the “write” button. Pictured is, that this button is located next to the test sequence parameters, which you would want to overwrite.

When you have a sub-test-sequence with test parameters and you click on the “lock” button of a test parameter, you will lock this parameter in the sub-test-sequence. If you want to run the same test two times with different parameters, all the variations of this parameter will be displayed in the test parameter field of the test sequence.

3.7 Run a test sequence

In order to run a test sequence, click on the “Run” button as defined. During the run of the test sequence, you can have an idea of the evolution of the test sequence, by checking the number of repetitions from the test or the test sequence that has been run. If, for some reason, you set a number of repetitions for a test case to 0, this test will be jumped during execution. At the end of the execution, the status displayed will be the status of the last test case from the sequence.

3.7. Run a test sequence 15 TTA Documentation, Release 1.15.2

Fig. 11: Setting the subsequence parameters. In the example there are two test parameters, in form of a string and an integer. The integer parameter was locked, but the string parameter wasn’t, which means that only the integer parameter won’t be overwritten, by the upper test sequence.

Fig. 12: Display of the test parameters in the test parameter field. Here is an example of a test sequence with two test cases, using the same parameter par_test_parameter_str: one with the value First_value, the other one with Sec- ond_value.

Fig. 13: Test sequence status. The hour-glass shows the actual status of the Testsequence_1, it’s running. A green check-symbol, beside the examples, shows that there already have been successfully runs, but some of them haven’t finished yet, there are still running repetitions. When there’s no symbol next to test case etc., it means that it hasn’t been run by now.

16 Chapter 3. How to test with TTA ? TTA Documentation, Release 1.15.2

Fig. 14: Detailed view of the test sequence status. The example of testcase_example_2 shows, that being jumped gets displayed with a crossed-out circle.

3.8 Run a test sequence randomly shuffled

It is possible to shuffle the test case and subsequence positions for a run. Currently there are three options you can choose from, each applies to the current sequence displayed (does not impact parent sequence or subsequence, which have their own shuffle option): • None No shuffling will be applied, test sequence runs respecting the given order. • Test cases Only the positions of the test cases will be shuffled while the positions of subsequences will be left unchanged. For example this option is useful if you have some subsequences you want to run at the start or the end of a sequence always, like maybe checking some special conditions etc. In case you want to run a test case at the beginning or end of a sequence, just put it into a single subsequence alone and choose this option. • All Positions of test cases and subsequences will be shuffled.

Fig. 15: Shuffle button in sequence view.

If you save the sequence, the shuffle option will also be written to the file.

3.8. Run a test sequence randomly shuffled 17 TTA Documentation, Release 1.15.2

3.9 Open the test report

The test report is generated at the end of the execution of the single test case or test sequence. If you run a test sequence, you will be able to see the manager report on top of the test cases reports.

Fig. 16: Positioning of the test results and test report. As here can be seen, you can get to the test report, by clicking the button “Report” next to the test result under the console.

The log folder can be accessed through the sidebar icon at any time.

3.10 Control more than one computer with TTA

TTA offers a Remote Control Concept, that enables you to control several computers, using TTA in parallel. The documentation concerning this feature will be available soon.

3.11 Import tests from Git

For this feature to work correctly you need to have the corresponding tool installed. Extended tutorial and a download can be found on https://git-scm.com/. If you want to use a version controlling tool for your testcases, you can add them wihin the connection menu (the globe in the right sidebar). The second tab in this menu opens the Version Control settings. After the GUI has been reloaded the repository can be found in the dropdown menu under the testcase list on the right menu bar. The file icons should have an additional icon in the lower right that indicates their current status (up-to-date, modified, added, untracked) which can be identified by hovering over it. If needed, the complete range of git commands can be used within TTA-Eclipse. Therefore the “Git Repositories” View needs to be enabled in Window → Show View → Other. . . This View should have an option to add local git repositories and the window it opens will guide through the process of finding and adding the version controlled folder. A right click on the new item will give a complete list of git commands that can be run within TTA-Eclipse.

3.12 Import tests from Apache Subversion

For this feature to work correctly you need to have the corresponding tool installed. Extended tutorial and a download can be found on https://subversion.apache.org/.

18 Chapter 3. How to test with TTA ? TTA Documentation, Release 1.15.2

Fig. 17: Connection window with one git repository connected.

Fig. 18: Connection window with one git repository connected.

3.12. Import tests from Apache Subversion 19 TTA Documentation, Release 1.15.2

Connecting Apache Subversion within the GUI works the same way as Git, so please follow the steps in the chapter above. To add your repository within Eclipse you first need to install the Plugin Subclipse. To install a plugin in Eclipse you need to navigate to Help → Install New Software. . .

Fig. 19: Install the latest Subclipse plugin from Eclipse Plugin Wizard.

To find the correct version of Subclipse, you need to check which version of SVN you are using and look it up on https://github.com/subclipse/subclipse/wiki. To add the corresponding version, write the correct download link into the field next to “Work with:”. After selecting the desired packages (at least the package “Subclipse” is necessary) you can follow the install wizard to enable the plugin. After a restart of Eclipse, open the the menu File → Import. . . and select the new SVN entry to import the repository. The Import Wizard should be self explanatory, but it is important to select the local repository in tta_testcases/svn/ and create a new Eclipse project. Otherwise the files won’t be linked to each other. This should generate a new folder in the ecxlipse navigator which can execute SVN commands when selecting Team from the right-click dialog on this project. For further help please consult the Subclipse Wiki on https://github.com/subclipse/subclipse/wiki

20 Chapter 3. How to test with TTA ? CHAPTER FOUR

TTA TEST CASE GENERATOR

The test cases need to be based on the Behavior Driven Development and be written in a Gherkin-conform style. These test cases can then be handed over to the generator in on of the following file formats: .feature, .pdf, .ptc, .xls, .xlsx, .xml, .zip This module provides information regarding the generation of a test case Python script template from a TTA description.

4.1 Start the script in Eclipse

The test case generator is integrated in the GUI, but you can also start it in Eclipse directly. The following code is an illustrative example how to generate a Python script from a TTA-XML description. The generation of descriptions with the other valid formats is working in the same way:

from tta.testcase.generator import Generator generator= Generator() str_script= generator.generate(r"C:\path_to_the_template\testcase_template_XML.xml",

˓→".xml") with open(r"C:\Path_to_the_testcase\tta_testcase.py","wb+") as fobj: fobj.write(str_script.encode("UTF-8"))

The Python script then will be written to “C:\path_to_the_testcase\tta_testcase.py”.

4.2 Generate the test case in the GUI

In order to generate the test case structure within the GUI, click on the “Generate test case(s)” button which will open a new window.

Fig. 1: Position of the button to open the test case generator menu.

You can drop the template files in the drag & drop field within this menu or open a file selector to import the files. For a reference on how these files have to look like, you can click on the respective type to open an exemplary file.

21 TTA Documentation, Release 1.15.2

Fig. 2: Functions of the test case generator menu

4.3 Keyword Mapping

If ‘Use key word mapping?’ is turned on and a keyword mapping file (e.g. “\keyword_map.py”) is given, every occurrence of a keyword in the dropped file will be matched to its correspond- ing code in the keyword catalog. When a keyword cannot be matched, the ‘Use key word mapping?’ button is turned off or no key word mapping file is used for the generator, an empty test case scaffolding will be generated. Every step in this test case will have a placeholder as seen below: def step_001_first_step(self): """ First step description with generated Demo_1 code

:name: First step :expected: Then Step is passed """ raise NotImplementedError() # TODO: implement this step

22 Chapter 4. TTA test case generator CHAPTER FIVE

HOW TO CREATE A TTA TEST CASE SCRIPT

With TTA, it is very easy to create and run a test script. First, a test case class has to be implemented, then it can be executed with TTA’s Runner. Collections of test scripts, containing TTA TestCaseBase derived classes, can be run all together, using TTA’s TestSuite and derivatives. First, the usage of the minimalist TestCaseBase class is described to understand the basic structure of TestCaseBase. However, the recommended way is to use the AdvancedTestCaseBase class, as it offers a lot of functions which are generally useful for a test case developer.

5.1 Simple Test Case

Your test case script can be as simple as:

''' Import all necessary TTA Classes Units can be found at tta.units ''' from tta.testcase import TestCaseBase, ResultEnum from tta.runner import Runner class MyTestCase(TestCaseBase): """My first TTA test case"""

def run(self): """Test case's main function.""" self.logger.info("Hello world")

test_result= self.create_test_result("My Test Case", "This test case is a simple example to

˓→show how to implement a test case.")

step1= test_result.test_step_results.add("step_01_test_something", "This step does something.", "Something is done") # do something

if something_has_been_done: step1.actual="Something is done" step1.result= ResultEnum.PASSED else: step1.actual="Nothing is done" (continues on next page)

23 TTA Documentation, Release 1.15.2

(continued from previous page) step1.result= ResultEnum.FAILED

if __name__ =='__main__': runner= Runner() runner.run_test_case(MyTestCase)

The test case class must be derived from TestCase and it must implement the run method which contains your test’s logic. With the help of create_test_result you can get a TestResult object to fill. The Runner will take care of saving it to a file at the end of the test run and depending on your configuration, convert the report to an HTML or to write it to a database.

5.2 Advanced Test Case

Additional to the simple test case from above, you can use the AdvancedTestCaseBase class as base class for your test script. The main benefits of using the AdvancedTestCaseBase are: • Simple definition of preconditions / test steps / postconditions by implementing functions named “precondi- tion_XXX”, “step_XXX”, “postcondition_XXX”. • Automatic report generation. • Automatic test case abortion on error / failed test step. • Automatic documentation of errors in the report. • Simple assert functions to execute and automatically add result items to your report. The usage of AdvancedTestCaseBase is very easy:

from tta.testcase import AdvancedTestCaseBase from tta.runner import Runner from tta.units.example import Example class MyTestCase(AdvancedTestCaseBase): """My second TTA test case"""

def __init__(self, parameter_values): AdvancedTestCaseBase.__init__(self, parameter_values) self.example= Example() # For parameters see tta\config\default_config.yaml

def precondition_01_pre1(self): """ First precondition

:expected: precondition ok """ # check a precondition precondition= True self.assertEqual(precondition, True)

def step_01_first_step(self): """ The first step checks if everything is good.

:expected: all good (continues on next page)

24 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

(continued from previous page) """ # perform your test step if all_good: result= True else: result= False self.assertEqual(result, True)

def step_02_second_step(self): """ The second step checks something else. :name: My Second Test Step :expected: something else good """ pass # add your code here

def postcondition_01_cleanup_dut(self): """ Postconditions are optional - just as preconditions are.

:expected: all clean """ pass # add your code here if __name__ =='__main__': runner= Runner() runner.run_test_case(MyTestCase)

5.2.1 Execution order

When the runner executes this test case class, the functions will be called in a defined order: 1. All precondition functions in order of their numbers. If all preconditions are passed: 2. All step functions in order of their numbers 3. All postcondition functions in order of their numbers

5.2.2 Test step function naming conventions

In order to be recognized as a precondition/step/postcondition function, the function names must match these rules: • The function name must start with precondition_, step_ or postcondition_ • followed by a number (>= 1 digits) - execution order will be based on these numbers • followed by another _ and any amount of small (a-z) or capital letters (A-Z), _ or numbers (0-9) Examples of valid and invalid function names:

5.2. Advanced Test Case 25 TTA Documentation, Release 1.15.2

valid (will be called) invalid (will not be called) precondition_01_first_precondition step_hello_1 precondition_2_2nd_precondition step_1 step_001_This_is_my_Step precondition_01_prepare postcondition_99_Cleanup postcondition

5.2.3 Test initialization

You can initialize your test with the python __init__ function. Here, you might initialize any unit your test needs by self.unitname = Unit. Afterwards, you only need to call self.unitname in your code to execute the unit. TTA will shut down the imported units at the end of the test sequence automatically. Note, that any unit module needs to be imported, just like other modules. You might also define local variables your test case uses here by self.variable = value.

5.2.4 Test step documentation and reports

For a useful test report, your test case class must include docstrings with information about the test case itself and its test steps: class MyTestCase(AdvancedTestCaseBase): """ Description of test case.

The class docstring describes what the test case does. The following :name: tag is optional.

:name: My Test Case """

force_documentation= True

def step_01_first_step(self): """ The function docstring is the step's description and should describe what the test step is going to do. The following :name: tag is again optional. The :expected: tag should always be provided and contain the test step's expected outcome.

:name: Alternative Test Step Name :expected: all good """ # perform your test step if all_good: result= True else: result= False self.assertEqual(result, True)

def step_02_second_step(self): """ This is the second step. It has no :name: tag.

(continues on next page)

26 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

(continued from previous page) :expected: The function's name will be used in the report. """ # Step is Passed is result is False if all_good: result= True else: result= False self.assertEqual(result, False)

The test report created by TTA will have the name of the test case class, unless the :name: tag is provided in the class docstring. In that case, this value is used as test result name. The text body of the class docstring will be stored to the report, as the test case’s description.

Note: It is very important to leave a blank line between the text body and the part with the tags! If not, the docstring will not be parsed properly!

The same applies to the single test step functions. If the :name: tag is provided with a value, it will be used as the test step’s name in the report and the text body of the function docstring will be stored as the test step’s description. Additionally, each test step function’s docstring requires the :expected: tag to be provided. Use it to describe the expected outcome of the test step. It is possible to use multiline text for :name: and :expected: tags, see the reStructuredText Markup specification about fields: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html# field-lists.

5.2.5 Assert functions

Inside the code of each test step function, it is sufficient to only include one statement. This statement is called the Assert. The Assert compares the value of a variable of the TestStep with the expected result. This is similar to the syntax of the Python unittest package. The assert functions are members of the AdvancedTestCaseBase and will access its report and result objects. Every assert is adding its result to the current step report (either directly or in a sub step, see Assert types / automatic sub steps):

def step_01_first(self): current= 2.01 self.assertEqual(current, 2.00) # False -> result will be failed

There is also a special assert function, which can parse and evaluate the :expected: field in the docstring: assertActual. Some advanced examples for assertActual are demonstrated in testcase_example_assert.py in the tta_testcases project, with examples for the other assert functions. Or see assertActual. The Assert will give the status of each TestStep to the Runner. Depending on this status, the Runner will or won’t pursue the execution of the test.

5.2.5.1 Arguments and return type

Arguments for all assert functions in common are “result”, “msg” and kwargs. For assert types and automatic sub steps see the following section Assert types / automatic sub steps. The result argument can hold a result object you have defined yourself. E. g. you might want to make a more complicated sub step result, then just create one and provide it in “result” argument. Example:

5.2. Advanced Test Case 27 TTA Documentation, Release 1.15.2

# Assert on existing result object sub_res= TestStepResult("Signal test","Check if PDU ID field correctly set") sub_res.add_image(grabber.get_image()) # Add an image to object "sub_res" self.assertEqual(can_msg.data[0], 142, result=sub_res) # Assert will report into

˓→result object "sub_res"

Further the “msg” argument can be used to provide messages depending on the actual result. Those will be added directly after the actual result value in the report. If a single str object is given, it will be treated as a message for “Failed”. If a tuple/list of two str objects is given, the first string is for “Failed” and the second for “Passed” (like (msg_failed, msg_passed)). Think about that the assert call in the source code is added to the report, thus you might want to use variables (see example): Example:

# Message for failed result val_stat= 23 self.assertEqual(val_stat, 42, msg="Value is not 23, state of device is wrong!")

# Messages for failed and passed result assert_msg=("Property registry_content(145) not available!", "Property registry_content(145) found and activated!") val_prop= 145 self.assertEqual(val_prop, 145, msg=assert_msg) # Shorter report entry due to

˓→variable assert_msg

Every assert function will return the result it is reporting to. This is useful if you automatically generate a sub step with the assert (see Assert types / automatic sub steps).

5.2.5.2 Multiple asserts per test step

It is possible to use multiple asserts per step. On default, a Failed result won’t stop the step execution. Thus all asserts will be evaluated and reported. This can be changed to stop the step execution on the first Failed result. In this case just set the self.assert_abort variable of the test case to AssertType.Step(“Step”). Default is Assert- Type.SubStep(“SubStep”), what means that the assert only “aborts” itself (the sub step). Example:

# Default: check all asserts self.assert_abort= AssertType.SubStep # This is the default data=[1,3,7, 18] self.assertEqual(data[2],7) # will be evaluated self.assertNotEqual(data[0], 221) # will be evaluated

# Abort on first assert, which is failed self.assert_abort= AssertType.Step # Abort on sub step data=[0x67, 0x60] self.assertIsNotNone(data) # will be evaluated self.assertEqual(data[2],7) # will not be evaluated if first assert is Failed self.assertNotEqual(data[0], 221) # will not be evaluated if one of preceding

˓→asserts are Failed

Note: All single assert results will be combined/considered into the step result - the combination is logical AND. So if one assert is failed, the step result will be set to failed as well.

28 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

5.2.5.3 Assert types / automatic sub steps

You can define which assert type should be used in argument “result”. Default is AssertType.Step: in this case the assert uses the current step result or combines into the current step result (logical AND, for multiple asserts in the same test step). If you use AssertType.SubStep, a sub step result will be generated automatically for the assert. The latter is recom- mended, because the report is much more readable then - especially if you want to use multiple asserts per step. Here, you can overload default name and description of the sub step by using keyword arguments “name” and “description” as needed. Since the source code of the assert command is added to the report, you might want to use variables for arguments not related to the assert result evaluation directly. Example:

# Short form val= 23 self.assertEqual(val, 23, result=AssertType.SubStep) # generate sub step for result

# Provide name and description for sub step result in report assert_desc={'name':'Compare list','description':'Compare if recognized text in

˓→list'} list_val=["one","two","three"] val=["four"] self.assertIn(val, list_val, result="SubStep", **assert_desc) # generate sub step ˓→for result

# Generate sub step for result and add an image afterwards val= 23 sub_res= self.assertEqual(val, 23, result=AssertType.SubStep) my_img= self.grabber.get_image() sub_res.add_image("Screenshot", my_img)

Hint: You can change the default behavior by setting self.assert_type in the test case class. Default is As- sertType.Step(“Step”). To have automatic autogeneration of sub steps generally, set self.assert_type to Assert- Type.SubStep(“SubStep”).

5.2.5.4 Set a step result with an exception

With more complex testing scenarios it might be helpful to define helper functions/classes. Those helpers can do specific tasks which are used on several occasions in a test. To make things easier the helpers can raise a special exception if they want to set a step result directly: TTAAbortWithResultError. Thus it does not matter how many levels of different functions you are invoking. The TTAAbortWithResultError will be instantiated with a message string and a result (ResultEnum). The runner then will notice this exception and set the current step result to the exception result and make an entry in the report for the provided message. Example: from tta.testcase import TTAAbortWithResultError, ResultEnum class HelperExample: ... def get_profile(self): self.connect_to_server() (continues on next page)

5.2. Advanced Test Case 29 TTA Documentation, Release 1.15.2

(continued from previous page) prof_glob= self.get_profile_in_global_database() prof_reg= self.get_profile_in_regional_database() return self.merge_profile([prof_glob, prof_reg])

def get_profile_in_regional_database(self): prof_reg= self.load_profile_from_database(self.db_regional) if prof_reg['Error']: # We are in: helper -> get_profile -> get_profile_in_regional_database raise TTAAbortWithResultError("No regional profile available at all.", ResultEnum.BLOCKED) class MyTestCase(AdvancedTestCaseBase): ... def step_04_check_profile(self): """ Check if our profile is updated from our current provider """ res= self.helper.get_profile() # no regional profile -> set result

˓→to BLOCKED

self.assertEqual(res.profile.provider,"My special test provider")

If you already have defined exceptions yourself and you want just “map” those to a specific TTAAbortWithResultError, you can inherit from predefined exceptions with the appropriate name directly (TTAAbortWithError, see below). Example: from tta.testcase import TTAAbortWithBlockedError class NoRegionalProfileError(TTAAbortWithBlockedError): """ No regional profile available, set to blocked """ class HelperExample: ... def get_profile_in_regional_database(self): prof_reg= self.load_profile_from_database(self.db_regional) if prof_reg['Error']: # We are in: helper -> get_profile -> get_profile_in_regional_database raise NoRegionalProfileError("No regional profile available at all.")

class tta.testcase.testcase_assert.TTAAbortWithResultError(message, result) Intentional abort by user, provide desired step result Parameters • message (str) – Exception message • result (ResultEnum) – Result which should be set for current step class tta.testcase.testcase_assert.TTAAbortWithPassedError(message) Intentional abort by user, set result to PASSED class tta.testcase.testcase_assert.TTAAbortWithIncompleteError(message) Intentional abort by user, set result to INCOMPLETE class tta.testcase.testcase_assert.TTAAbortWithFailedError(message) Intentional abort by user, set result to FAILED

30 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

class tta.testcase.testcase_assert.TTAAbortWithBlockedError(message) Intentional abort by user, set result to BLOCKED class tta.testcase.testcase_assert.TTAAbortWithCanceledError(message) Intentional abort by user, set result to CANCELED

5.2.6 Reporting

Any information like text fields or images can be added to the self.current_step_result, which is from the type TestStepResult. Please see this class’ documentation for the full interface description. This example class sets the static member force_documentation to True, which means that the test will not run when any part of the mandatory documentation is missing. This is optional and turned off by default. Turn this feature on, by setting the static member to True in a test case base class commonly, used in your test automation project. This will force all test case implementers to add the necessary docstrings. The above example will result in a test report like this:

Fig. 1: Exemplary test report with one passed and one failed test step. Since one test step has the status failed, the test result is set to failed (upper part). The Test Run Protocol displays the test step description, the expected result and the actual result, which should be compared for error analysis.

5.2.7 Error handling

TTA’s Runner takes care of exception handling. In case there is an exception in your test case, which is not caught by you, the Runner will catch it and end the test case execution. If you use the Simple Test Case, your execution will just stop and the report will be written as is, i.e. there will be no information about the exception in your report and the report’s result will be the one you set. If you did not set any result, it may be undefined or NORUN. The exception will be written to TTA’s log files though.

5.2. Advanced Test Case 31 TTA Documentation, Release 1.15.2

If you use Test initialization, things are different: As TTA knows during which test step the uncaught exception occurred, it will write information about the error to the report and set its result accordingly: With an error in a precondition or a test step function, the overall test result will be set to CANCELED and the execution will be stopped. If the error occurs in one of the postcondition functions, only this postcondition’s result will be set to CANCELED, but the overall test result will be unaffected and all following postconditions will be executed as well. If we raise an uncaught exception in step_02_second_step of the above example, the report will look like this:

Fig. 2: Test report with uncaught exception. The test is cancelled due to an exception, which is indicated with a yellow coloring. Instead of giving an actual result, the description of the exception is displayed at the end of the test step in question.

5.3 Assert functions reference class tta.testcase.testcase_assert.AssertMixin Assert functions assertActual(result=None, expected=None, msg=None, **kwargs) Continue if formula in expected description returns True on evaluation, otherwise abort step with “failed”. Formula must be evaluable by Python and return a boolean. Keyword replacement applies to names with “$”-prefix. “$result” and “$expected” are reserved and not allowed (but as subscript they can be used like “$obj.result” etc.).

32 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

Example expressions: • “0 < $value < 7” • “$x**2 < $x” • “$value.data[0] == 0x3C” • “$value[0] == 5.6 and $value[1] == 1.2” Example:

def step_01_mystep(self): ''' My test step

:expected: -4.3 <= $value <= 5.5 ''' current_val= 5.02 self.assertActual(value=current_val) # uses expression string from

˓→':expected:'

voltage_val= 12.05 self.assertActual(expected="$value < 16.0", value=voltage_val) # provide

˓→expression string directly

Parameters • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • expected (str) – Expected result formula; if None, “:expected:” from step doc-string is used • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). • kwargs (dict) – Keyword arguments (should contain all used variable names)

assertAlmostEqual(actual, expected, delta=0.0, places=7, result=None, msg=None, **kwargs) Continue if both arguments are almost equal, otherwise abort step with “failed”. Parameters • actual (float) – Actual float • expected (float) – Expected float • delta (float) – Tolerated difference • places (int) – Round actual and expended to this many digits (after floating point) • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertCalled(bound_method, timeout=4.0, result=None, msg=None, **kwargs) Check if a bound_method was called inside the given time interval Parameters

5.3. Assert functions reference 33 TTA Documentation, Release 1.15.2

• bound_method (bound_method) – A method bound to a class-instance • timeout (int) – the interval in which the method must be called • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertEqual(actual, expected, result=None, msg=None, **kwargs) Continue if both arguments are equal, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertFalse(actual, result=None, msg=None, **kwargs) Continue if actual is False, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertGreater(actual, expected, result=None, msg=None, **kwargs) Continue if actual > expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertGreaterEqual(actual, expected, result=None, msg=None, **kwargs) Continue if actual >= expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object

34 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

• result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIn(actual, expected, result=None, msg=None, **kwargs) Continue if actual is contained in expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIs(actual, expected, result=None, msg=None, **kwargs) Continue if both arguments are the same objects, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIsInstance(actual, expected, result=None, msg=None, **kwargs) Continue if actual is instance of expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIsNone(actual, result=None, msg=None, **kwargs) Continue if actual is None, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default).

5.3. Assert functions reference 35 TTA Documentation, Release 1.15.2

• msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIsNot(actual, expected, result=None, msg=None, **kwargs) Continue if both arguments are not the same objects, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertIsNotNone(actual, result=None, msg=None, **kwargs) Continue if actual is not None, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertLess(actual, expected, result=None, msg=None, **kwargs) Continue if actual < expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertLessEqual(actual, expected, result=None, msg=None, **kwargs) Continue if actual <= expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed).

36 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

assertNotAlmostEqual(actual, expected, delta=0.0, places=7, result=None, msg=None, **kwargs) Continue if both arguments are not almost equal, otherwise abort step with “failed”. Parameters • actual (float) – Actual float • expected (float) – Expected float • delta (float) – Tolerated difference • places (int) – Round actual and expended to this many digits (after floating point) • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertNotEqual(actual, expected, result=None, msg=None, **kwargs) Continue if both arguments are not equal, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertNotIn(actual, expected, result=None, msg=None, **kwargs) Continue if actual is not contained in expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertNotIsInstance(actual, expected, result=None, msg=None, **kwargs) Continue if actual is not instance of expected, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • expected (obj) – Expected object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default).

5.3. Assert functions reference 37 TTA Documentation, Release 1.15.2

• msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). assertTrue(actual, result=None, msg=None, **kwargs) Continue if actual is True, otherwise abort step with “failed”. Parameters • actual (obj) – Actual object • result (TestResult,AssertType) – Result object or AssertType.Step (“Step”, de- fault) or AssertType.SubStep (“SubStep”, generates sub step result for assert). If None, self.current_step_result is used (default). • msg (str,tuple,list) – Message depending on actual result. If str: msg_failed, else (msg_failed, msg_passed). class tta.testcase.testcase_assert.AssertType Types for assert invocations: current step or generate substep Step = 'Step' Step SubStep = 'SubStep' Substep

5.4 Simple Test Case reference class tta.testcase.testcase_base.TestCaseBase(parameter_values=None) Base class for test cases This class provides the minimum functionality of a TTA test case. Parameters parameter_values (ParameterSet) – Set of parameter values create_test_result(name=None, description=”) Returns a new test result object with the specified name and description. If name is None, the test result will get the name of the current TestCase class. Parameters • name (str) – test result’s name. • description (str) – test description Return type TestResult get_outgoing_values() Returns dictionary containing all values of Parameter objects declared with IN_OUT or OUT direction. get_test_results() Returns all TestResult objects which were created using create_test_result(). Return type list of TestResult logger = None Test case’s logger. Use it to write information to TTA’s log files:

self.logger.info('Some information')

38 Chapter 5. How to create a TTA test case script TTA Documentation, Release 1.15.2

Type Logger

meta_data = {} Dictionary containing test case’s meta data. Type dict run() Test case’s main function. This is the entry point for the test case execution. TTA’s Runner will run this function. Override it to add test case logic.

5.5 Advanced Test Case reference class tta.testcase.testcase_base.AdvancedTestCaseBase(parameter_values=None) Advanced base class for test cases This class provides advanced features for TTA test cases. Test cases derived from this class can use the following features: • define preconditions / test steps / postconditions by defining function named “precondition_XXX”, “step_XXX”, “postcondition_XXX” • automatic report generation • automatic test case abortion on error / failed test step See TTA doc for detailed information. Parameters parameter_values (ParameterSet) – Set of parameter values current_step_result = None When inside a precondition_XXX/step_XXX/postcondition_XXX function, this variable holds the current TestStepResult object for this test step. Use it to add information about the test step run and set its actual and result members:

self.current_step_result.actual="what was observed" self.current_step_result.result= PASSED

Type TestStepResult

force_documentation = False This static member indicates if a full documentation of the single step functions should be forced. If your test case class (or a common custom base class you are using) sets this member to True the test case will only run if all precondition/step/postcondition function contain docstrings with all required information: • Description text • :expected: tag describing step’s expected result • see Test initialization for details logger = None Test case’s logger. Use it to write information to TTA’s log files:

self.logger.info('Some information')

5.5. Advanced Test Case reference 39 TTA Documentation, Release 1.15.2

Type Logger

run() This implementation of run() will find all precondition / test step / postcondition functions and run them. Additionally it will prepare the test report. stop_if_worse_than = None This variable can be used to change the default “stopping” behavior of test runs. Default means that every step with a result worse than “PASSED” will stop the test run. Order is: PASSED, INCOMPLETE, FAILED, BLOCKED, CANCELED. Type ResultEnum test_name = None This variable is to be used to override any other test name definition. Setting it you can dynamically assign a test name within the test case, for example.

40 Chapter 5. How to create a TTA test case script CHAPTER SIX

TUTORIAL TESTCASE PARAMETERS

With TTA it is possible to define testcase parameters that will be shown in the GUI and can be adjusted before starting. You can also set a description for each parameter that can be toggled in the user interface. This is especially usefull if you have parameters with similar names or if you are using abbreviations.

Fig. 1: Testcase parameters in user interface.

6.1 Getting started:

To add parameters to you testcase open your testcase in your prefered editor, after that you can add custom parameters like this:

my_param= ParameterStr(value, description='Your Description.',

˓→direction=ParameterDirection.IN)

Following values can be set: • ParameterStr: Sets the type of your parameter to String or a different type. A few possible types are listed further below. • value: Here you can define a default value that will be used if no other value is set in the interface (will be shown as placeholder text as well). If omitted, this parameter will be mandatory. • description: You can set a custom String as a description that will be later visible in the interface. • direction: Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both

41 TTA Documentation, Release 1.15.2

6.2 Operation

Our TTA user interface also provides some additional functionality regarding testcase parameters. For example it allows you to override parameters of all testcases in a sequence from its parent if you want to quickly change a set of testcase parameters. You can also individually lock certain parameters to not be overwritten by this function. If you set a custom value in the GUI you also have the option to revert back to the default value specified in your testcase code at any time.

6.3 Additional Documentation

If there is a description available for your parameter the i indicator gets shown on the left hand side of your input field. By clicking this button you can toggle the description to be shown.

Fig. 2: Toggle parameter description.

Other Parameter values: class tta.testcase.testcase_base.Parameter(default=(mandatory parameter with no default), description=”, direc- tion=, shortname=None) Subclass for a generic parameter that accepts any type of value. Parameters • default_value (str) – Default value to apply if parameter not provided. If omitted, this parameter will be mandatory. • description (str) – Parameter description. • direction (ParameterDirection) – Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both • shortname (str) – If not None, shorter name for the parameter class tta.testcase.testcase_base.ParameterInt(default=(mandatory parameter with no default), description=”, direc- tion=, shortname=None) Subclass for a parameter accepting only integer values. Parameters • default_value (str) – Default value to apply if parameter not provided. If omitted, this parameter will be mandatory. • description (str) – Parameter description.

42 Chapter 6. Tutorial Testcase Parameters TTA Documentation, Release 1.15.2

• direction (ParameterDirection) – Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both • shortname (str) – If not None, shorter name for the parameter type alias of builtins.int class tta.testcase.testcase_base.ParameterStr(default=(mandatory parameter with no default), description=”, direc- tion=, shortname=None) Subclass for a parameter accepting only string values. Parameters • default_value (str) – Default value to apply if parameter not provided. If omitted, this parameter will be mandatory. • description (str) – Parameter description. • direction (ParameterDirection) – Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both • shortname (str) – If not None, shorter name for the parameter type alias of builtins.str class tta.testcase.testcase_base.ParameterFloat(default=(mandatory parameter with no default), description=”, direc- tion=, shortname=None) Subclass for a parameter accepting only floating point values. Parameters • default_value (str) – Default value to apply if parameter not provided. If omitted, this parameter will be mandatory. • description (str) – Parameter description. • direction (ParameterDirection) – Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both • shortname (str) – If not None, shorter name for the parameter type alias of builtins.float class tta.testcase.testcase_base.ParameterSet(**kwargs) An instance of ParameterSet describes a set of parameter values that can be passed to a test case instance. Constructor takes any amount of keyword arguments. get(param_name) Get a parameter value :param param_name: Name of parameter :type param_name: str to_dict() Returns dictionary representation of this parameter set. Return type dict

6.3. Additional Documentation 43 TTA Documentation, Release 1.15.2 class tta.testcase.testcase_base.ParameterBool(default=(mandatory parameter with no default), description=”, direc- tion=, shortname=None) Subclass for a parameter accepting only boolean values. Parameters • default_value (str) – Default value to apply if parameter not provided. If omitted, this parameter will be mandatory. • description (str) – Parameter description. • direction (ParameterDirection) – Defines parameter’s direction. IN = readonly by TC, OUT = does not accept values but TC provides value after finishing, IN_OUT = combination of both • shortname (str) – If not None, shorter name for the parameter type alias of builtins.bool

44 Chapter 6. Tutorial Testcase Parameters CHAPTER SEVEN

TTA RUNNER REFERENCE

The TTA Runner reference describes TTA’s runner components.

7.1 tta.runner.runner

This module contains the Runner class wich executes a TTA test case. Copyright (C) MAGNA Telemotive GmbH class tta.runner.runner.ProcessStdout(queue) Follow write operations on sys.stdout flush() Flush stdout isatty() Is this a tty write(data) Write data to stdout and to internal buffer list class tta.runner.runner.Runner The Runner class is used to execute a single TTA test case. get_context() Get context object of runner Return type Context classmethod get_test_case_class(filename, _logger=None) Load test case class from python file Load module specified by filename and return first sub class of TestCaseBase found in module. Parameters filename (str) – Python file containing the test case class Return type class Raises TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. run_file(filename, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified Python file. Parameters • filename (str) – Python file containing the test case class

45 TTA Documentation, Release 1.15.2

• parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured. Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises • TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. • TTARuntimeError – When an exception occurs during execution of the test case script. run_file_detached(filename, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified Python file, in detached process Parameters • filename (str) – Python file containing the test case class • parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured. Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises • TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. • TTARuntimeError – When an exception occurs during execution of the test case script. run_single(filename, parameters) Run specified test case. Parameters • filename (str) – testcase name • parameters (tuple) – parameters run_suite(test_suite) Run specified test suite. Parameters test_suite (TestSuite) – Test suite to run run_test_case(test_case_class, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified class. Parameters • test_case_class (class) – TestCase class • parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured.

46 Chapter 7. TTA Runner Reference TTA Documentation, Release 1.15.2

Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises TTARuntimeError – When an exception occurs during execution of the test case script. set_queue_detached(queue) Set queue if testcase is executed detached in different process Parameters queue (multiprocessing.Queue) – Queue object for stdout of process stop_run(timeout=5) Stop running testcase respectively running sequence, as fast as possible store_results(test_results, for_suite=False, name=’new report’, description=”) Stores test result objects from specified TestCase instance to xml. :return: Report created by test_case_instance. Might be None :rtype: TTAReport exception tta.runner.runner.TTAInvalidTestScriptError Raised whenever a script is trying to be run which is not a valid TTA script (i.e. does not contain a class derived from TestCaseBase) exception tta.runner.runner.TTARunnerError Base Error class for all errors raised by TTA’s Runner. exception tta.runner.runner.TTARuntimeError Raised when execution of a test case fails critically. Will always be raised with the original exception as context.

7.2 Runner and Suite for Test Case execution

TTA’s Runner and TestSuite classes provide the interfaces to execute single or multiple TTA test cases. The Runner class takes care of setting up all of the TTA environment needed for a test case run (e.g. creating a Context or loading the configuration). Usage is as easy as this:

from tta.runner import Runner, FileListSuite

runner= Runner() runner.run_file("C:\\TTA_testcases\\my_testcase.py")

The TestSuite class can be used to orchestrate the execution of multiple TTA test cases. While this class itself is not intended to be instantiated directly, it defines an interface for deriving classes, in order to provide an iterator for the Runner to know which test case to run next. Existing Suite-implementations are for instance the FileListSuite or the FileTreeSuite. Instances of TestSuite derived classes will be provided the necessary information and then passed to the Runner for execution:

suite= FileListSuite("My Test Case List") suite.add_file("C:\\TTA_testcases\\my_testcase.py") suite.add_file("C:\\TTA_testcases\\my_testcase_2.py") suite.add_file("C:\\TTA_testcases\\my_testcase_3.py") runner.run_suite(suite)

7.2.1 tta.runner package reference

class tta.runner.runner.Runner The Runner class is used to execute a single TTA test case.

7.2. Runner and Suite for Test Case execution 47 TTA Documentation, Release 1.15.2

get_context() Get context object of runner Return type Context classmethod get_test_case_class(filename, _logger=None) Load test case class from python file Load module specified by filename and return first sub class of TestCaseBase found in module. Parameters filename (str) – Python file containing the test case class Return type class Raises TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. run_file(filename, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified Python file. Parameters • filename (str) – Python file containing the test case class • parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured. Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises • TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. • TTARuntimeError – When an exception occurs during execution of the test case script. run_file_detached(filename, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified Python file, in detached process Parameters • filename (str) – Python file containing the test case class • parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured. Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises • TTAInvalidTestScriptError – When specified file does not contain a valid Test- CaseBase derived class. • TTARuntimeError – When an exception occurs during execution of the test case script. run_single(filename, parameters) Run specified test case.

48 Chapter 7. TTA Runner Reference TTA Documentation, Release 1.15.2

Parameters • filename (str) – testcase name • parameters (tuple) – parameters run_suite(test_suite) Run specified test suite. Parameters test_suite (TestSuite) – Test suite to run run_test_case(test_case_class, parameter_values=None, handle_lifecycle=True) Runs test case implemented in specified class. Parameters • test_case_class (class) – TestCase class • parameter_values (dict) – dictionary containing parameter values to apply to test case • handle_lifecycle (bool) – If True, lifecycle manager will be started before and shut down after test case run. Moreover the logger will be configured. Returns Report created by test run (might be None) and dict of outgoing parameter values Return type tuple of TTAReport, dict Raises TTARuntimeError – When an exception occurs during execution of the test case script. set_queue_detached(queue) Set queue if testcase is executed detached in different process Parameters queue (multiprocessing.Queue) – Queue object for stdout of process stop_run(timeout=5) Stop running testcase respectively running sequence, as fast as possible store_results(test_results, for_suite=False, name=’new report’, description=”) Stores test result objects from specified TestCase instance to xml. :return: Report created by test_case_instance. Might be None :rtype: TTAReport This module contains different TTA test suite class implementations. Copyright (C) MAGNA Telemotive GmbH class tta.runner.suite.FileListSuite(name=’unnamed’) Test suite based on a list of files which has to be provided by the user. add_file(filename) Adds a file containing a TTA test case to the list of test cases to be executed by this suite. Parameters filename (str) – Test script’s filename add_files(filenames) Adds multiple files containing TTA test cases to the list of test cases to be executed by this suite. Parameters filenames (list of str) – Test scripts’ filenames get_next_test() Will be called for each iteration step. Returns Test script’s path Return type str

7.2. Runner and Suite for Test Case execution 49 TTA Documentation, Release 1.15.2

reset_iteration() Will be called when the iteration is started. Implementation optional. class tta.runner.suite.FileTreeItem(tc_id, filename, repetition=1, parameter_values=None) Item class for FileTreeSuite class tta.runner.suite.FileTreeSuite(name=’unnamed’, repetition=1, shuffle_type=None) Test suite based on a recursive list of files (FileTreeItems). Elements can be FileTreeItems or FileTreeSuite objects. add_file(tc_id, filename, repetition=1, parameter_values=None) Adds a file containing a TTA test case to the list of test cases to be executed by this suite. Parameters • filename (str) – Test script’s filename • repetition (int) – Planned repetitions of test case add_files(filenames, repetition=1, parameter_values=None) Adds multiple files containing TTA test cases to the list of test cases to be executed by this suite. Parameters • filenames (list of str) – Test scripts’ filenames • repetition (int) – Planned repetitions of test case add_suite(suite) Adds a complete suite containing TTA test cases to the list of test cases to be executed by this suite. Parameters suite (FileTreeSuite) – Adds a suite to this suite get_items() Get item list get_next_test() Will be called for each iteration step. Returns Test script’s path Return type str get_total_iterations() Get number of iterations in total is_empty(strict=False) Return False if suite contains elements Parameters strict (bool) – If False, check only for FileTreeItems (test cases) Returns True if there are elements Return type bool reset_iteration() Will be called when the iteration is started. Implementation optional. shuffle() Shuffle FileTreeSuite object in place class tta.runner.suite.SuiteShuffle Different types of shuffle methods for FileTreeSuite objects ALL = 'ALL' Shuffle all item positions, suites and testcases

50 Chapter 7. TTA Runner Reference TTA Documentation, Release 1.15.2

NONE = 'NONE' No shuffling TESTCASES = 'TESTCASES' Shuffle only testcase positions, keep suites at their original position class tta.runner.suite.TestSuite(name=’unnamed’) Base class for all test suites. implements the iterator interface. Parameters name (str) – Test suite’s name get_next_test() Must be overridden. Will be called for each iteration step. Returns Test script’s path Return type str reset_iteration() Will be called when the iteration is started. Implementation optional.

7.2. Runner and Suite for Test Case execution 51 CHAPTER EIGHT

REPORTING

Reporting is a fundamental part of testing. TTA offers rich reporting capabilities to create useful test run reports. TTA reports are stored as XML files, along with a test script’s log files. This XML format is the base for many other target formats, including HTML and others. The reporting package contains functions to create rich test result reports. This is an example of what the output formats of TTA’s reporting will look like:

8.1 Overall overview

8.1.1 Report Structure

A TTA report can contain any amount of test results. A default TTA test result is divided into several parts: • Precondition results • Test step results • Postcondition results Although they have a different name, precondition and postcondition, the results also just contain test step results. The separation only serves the differentiation between actual test results and the test’s pre- and postconditions, which are not part of the test itself. A test step result can contain any amount of different elements like • Text elements • Media links, e.g. image elements • Test step results themselves

52 TTA Documentation, Release 1.15.2

Each test step contains a description and an expected result. The test script must write a value to the actual result field of the test step result and also set the test step result’s ‘result’ value.

8.1.2 Basic Usage

In the following, it is described how to create a TTA report and some test results (including the necessary imports for this and the rest of the examples on this page): from tta.core.lifecycle_manager import get_current_lifecycle_manager from tta.reporting.report import TTAReport, TestResult from tta.reporting.constants import PASSED, FAILED, NO_RUN from tta.reporting.htmlconverter import write_html_reports

# test result objects are collected in a report: report= TTAReport() result_a= TestResult("Demo Result A","This is a demo result. The first one.") result_a2= TestResult("Demo Result A","This is a demo result. The first one.") result_b= TestResult("Demo Result B","This is also a demo result. The second one.")

# add the TestResult objects to the report: report.add_test_result(result_a) report.add_test_result(result_a2) report.add_test_result(result_b)

Now you need to fill the test results with content:

# Add a step result to the preconditions: add(name, description="", expected="") pre1= result_a.precondition_results.add("Precondition 1", "This precondition must be fulfilled.", "Precondition fulfilled") pre1.actual="Precondition fulfilled" pre1.result= PASSED pre2= result_a.precondition_results.add("Precondition 2", "This precondition must be fulfilled.", "Precondition fulfilled") pre2.actual="Precondition fulfilled" pre2.result= PASSED

# Add a step to the actual test steps: add(name, description="", expected="") step1= result_a.test_step_results.add("Step 1", "Use description to describe what the test is

˓→doing", "Expected outcome") step1.actual="Actual outcome" step1.result= PASSED step2= result_a.test_step_results.add("Step 2", "Use description to describe what the test is

˓→doing", "Expected outcome") step2.actual="Actual outcome" step2.result= FAILED post1= result_a.postcondition_results.add("Postcondition 1", (continues on next page)

8.1. Overall overview 53 TTA Documentation, Release 1.15.2

(continued from previous page) "Pre- and postconditions are optional", "Postcondition fulfilled") post1.actual="Postcondition fulfilled" post1.result= PASSED result_a2.result= NO_RUN result_b.result= NO_RUN

In the example above, the variables pre1, step1, step2 and post1 are of the same type tta.reporting.bindings. TestStepResult. In the last two lines, result_a2 and result_b are given explicit results, which result_a does not provide. If you do not set the result value explicitly, it will be automatically determined based on this matrix:

Section results precondition OK OK NOK X X test OK NOK X X X postcondition OK/NOK X/OK X X X test environment OK OK OK NOK X overall result: Passed Failed Blocked Canceled NoRun

In order to store the report to a file, do this:

# store to XML: with open("demo_report.xml","wb") as fhdl: fhdl.write(report.to_xml_string())

# store to HTML: write_html_reports(report.test_results,"./html")

8.1.3 HTML report structure

The final line of the above example code uses TTA’s default HTML export, which will create three different report view stages.

8.1.4 PDF report structure

Similar to defining a HTML report you can also choose to have your report exported into the .pdf format. If you want to do this just add the following line as before:

# store to PDF: write_pdf_reports(html_folder, filename)

The structure of these .pdfs mirrors the structure of the HTML report and links accordingly.

8.2 Single test case overview

The single test case overview shows the available results and, by clicking on a single result, it will open the according test run protocol.

54 Chapter 8. Reporting TTA Documentation, Release 1.15.2

Fig. 1: Exemplary single test case results. This pictures an overview over all test runs of the exemplary test ‘generic_test_005’, as well as more detailed information about how often and when it was implemented and if it ‘Failed’, was ‘Canceled’ or ‘Passed’.

8.3 Test run protocol

The test run protocol shows information for a single run of the test case, including results and information for every individual test step.

8.3.1 tta.reporting package reference

8.4 tta.reporting.report

This module contains helper functions to get instances of TTA’s reporting classes. Copyright (C) MAGNA Telemotive GmbH tta.reporting.report.TTAReport(name=’new report’, description=”, created=None) Creates an instance of TTAReport node. Return type TTAReport tta.reporting.report.TestResult(name=”, description=”, id_=None, start=None, end=None) Creates an instance of TestResult node. Parameters • name (str) – TestResult’s name • description (str) – Description • id (str) – Test id, e.g. id from test management tool. • start (datetime) – timestamp of test’s start. If None, current timestamp will be used. • end (datetime) – timestamp of test’s end. If None, current timestamp will be used. Return type TestResult

8.3. Test run protocol 55 TTA Documentation, Release 1.15.2

Fig. 2: Exemplary test run protocol. In the lower part each step of the exemplary test, called ‘generic_test_003’ is shown, but at a specific date and time. Here, each of the four steps include information about the ‘ID Duration’, result as ‘Passed’ and the actual result to be ‘None’.

56 Chapter 8. Reporting TTA Documentation, Release 1.15.2 tta.reporting.report.get_worst_result(results) Returns worst present result value. Iterates through all results and checks which one has the worst result value. Returns the worst value. Items of results can be strings containing a result value or report objects with a result attribute. Return type str tta.reporting.report.is_worse_result(result_a, result_b) Return True if result_a is worse than result_b. Parameters • result_a (str) – Result which is to be checked if it is worse than the other. • result_b (str) – Result which is to be checked if it is better than the other. Return type bool tta.reporting.report.load_result(id_) Load TestResult with specified id from database. :param id_: results (internal) row id :type id_: int :rtype: TestResult tta.reporting.report.type_hint(hint_class, instance) Simulate type hint for pylint ast parser and PyDev code completion

8.5 tta.reporting.bindings class tta.reporting.bindings.TTAReport(*children, attrib=None, nsmap=None, **_extra) This class represents a TTAReport xml element. add_test_result(test_result) Adds a test result element to this report instance. Parameters test_result (TestResult) – TestResult object to add add_test_results(test_results) Adds multiple test result elements to this report instance. Parameters test_results (list of TestResult) – TestResult objects to add classmethod create(name=”, description=”, created=None) Creates an instance of TTAReport node. Parameters • name (str) – TestResult’s name • description (str) – Description • created (datetime) – timestamp of report’s creation. If None, current timestamp will be used. Return type TTAReport created Timestamp on which TTAReport was created Return type datetime description Element’s description Return type str

8.5. tta.reporting.bindings 57 TTA Documentation, Release 1.15.2

name Element’s name Return type str test_results List of test results contained in this TTAReport instance. Returns list of test results Return type list of TestResult to_xml_string() Returns xml string representing the TTAReport. class tta.reporting.bindings.TestResult(*children, attrib=None, nsmap=None, **_extra) This class represents TestResult elements. end TestResult’s end timestamp Return type datetime end_now() Set element’s end attribute to the current timestamp. id TestResult’s unique identifier. This is usually a uuid. Return type str meta_data Returns list of MetaDataItem/MetaDataList elements. Return type MetaDataList postcondition_results List of TestStepResult elements containing the results of postcondition steps. Return type TestStepContainer precondition_results List of TestStepResult elements containing the results of precondition steps. Return type TestStepContainer start TestResult’s start timestamp Return type datetime start_now() Set element’s start attribute to the current timestamp. test_step_results List of TestStepResult elements containing the results of the test steps. Does not include pre- and postcondition steps. Return type TestStepContainer

58 Chapter 8. Reporting TTA Documentation, Release 1.15.2 class tta.reporting.bindings.TestStepContainer(*children, attrib=None, nsmap=None, **_extra) This class represents elements containing TestStepResult elements, i.e. “PreconditionResults”, “TestStepRe- sults” and “PostConditionResults” add(name, description=”, expected=”, id_=None, start=None, end=None) Adds a new TestStepResult element to this container and returns it. Parameters • name (str) – New TestStepResult’s name. • description (str) – test step’s description • expected (str) – test step’s expected result • id (str) – TestStep id, e.g. id from test management tool. • start (datetime) – start of test step execution • end (datetime) – end of test step execution Return type TestStepResult class tta.reporting.bindings.TestStepResult(*children, attrib=None, nsmap=None, **_extra) This class represents TestStepResult elements. actual Actual result. Return type str add_image(title, image) Adds a Text element to this TestStepResult’s content. Parameters • title (str) – Image element’s title • image (PIL.Image) – Image object Returns newly created Image element Return type Image add_test_step_result(name, description=”, expected=”, id_=None, start=None, end=None) Adds a new TestStepResult element to this container and returns it. Parameters • name (str) – New TestStepResult’s name. • description (str) – test step’s description • expected (str) – test step’s expected result • id (str) – TestStep id, e.g. id from test management tool. • start (datetime) – start of test step execution • end (datetime) – end of test step execution Return type TestStepResult add_text(title, value) Adds a Text element to this TestStepResult’s content.

8.5. tta.reporting.bindings 59 TTA Documentation, Release 1.15.2

Parameters • title (str) – Text element’s title • value (str) – Text element’s content Returns newly created Text element Return type Text content TestStepResult’s content. This can be any list of Text, Image, Link etc. elements. Return type list end TestResult’s end timestamp Return type datetime end_now() Set element’s end attribute to the current timestamp. expected Expected result. Return type str id TestStep’s identifier. Return type str start TestResult’s start timestamp Return type datetime start_now() Set element’s start attribute to the current timestamp. class tta.reporting.bindings.Text(*children, attrib=None, nsmap=None, **_extra) Represents Text element. created Timestamp on which TestStepContentItem was created Return type datetime title Element’s title Return type str value Element’s value. Return type str class tta.reporting.bindings.Image(*children, attrib=None, nsmap=None, **_extra) Represents Image element.

60 Chapter 8. Reporting TTA Documentation, Release 1.15.2

created Timestamp on which TestStepContentItem was created Return type datetime link Link to media file as written in xml attribute ‘value’. Return type str title Element’s title Return type str value Linked image object Loads image from stored link and returns image object. Return type PIL.Image class tta.reporting.bindings.MetaDataList(*children, attrib=None, nsmap=None, **_ex- tra) Contains a list of MetaDataItem/MetaDataList elements. add_item(key, value) Adds a MetaDataItem with the specified key and value. Parameters • key (str) – key attribute value of desired element. • value (str) – value to set add_list(key) Adds a MetaDataList with the specified key and returns it. Parameters key (str) – key attribute value of desired element. Return type MetaDataList get(key, default=None) Returns the MetaDataItem or MetaDataList element with the specified key value. If multiple elements with this field value are present, only the first one will be returned! For full access MetaDataList.items() has to be iterated. Parameters • key (str) – key attribute value of desired element. • default – Value to return when specified key is not found. Return type MetaDataItem or MetaDataList items() Returns unsorted list of all contained MetaDataItem/MetaDataList elements. Return type list of MetaDataItem/MetaDataList key Element’s key attribute value Return type str

8.5. tta.reporting.bindings 61 TTA Documentation, Release 1.15.2

keys() Returns list of all available keys. If the same key is present more than once it only occur once in this list! Ambiguous keys will not be accessible through MetaDataList[key]! This will only return the first occurrence. For full access Meta- DataList.items() has to be iterated. Return type list of str class tta.reporting.bindings.MetaDataItem(*children, attrib=None, nsmap=None, **_ex- tra) Represents a MetaDataItem element containing a field name and a value. key Element’s key attribute value Return type str value Element’s value. Return type str

8.6 tta.reporting.constants

This module contains constant values used for TTA’s reporting. class tta.reporting.constants.ItemTypeEnum Enumeration of result item types. tta.reporting.constants.LOGGER_NAME = 'Reporting' Logger name used by reporting. class tta.reporting.constants.ParentRelationEnum This enumeration is used to describe the relation of a result entry in TTA’s reporting database to its parent. class tta.reporting.constants.PrintableEnum Enum overwriting __str__ function to just return pure value without enum name. tta.reporting.constants.RESULT_SEVERITY = {: 0, : 1, : 2, : 3, : 4} Severity of the different results. Larger number = worse class tta.reporting.constants.ResultEnum Enumeration of accepted result values. BLOCKED = 'Blocked' Use this constant to mark a test step as blocked. A test step is blocked if a precondition failed or if the step is not applicable etc. CANCELED = 'Canceled' Use this constant to mark a test step as canceled. A test step / test case is canceled when execution was not finished due to an external issue, e.g. the test environment was not set up properly. FAILED = 'Failed' Use this constant to mark a test step as failed. INCOMPLETE = 'Incomplete' Use this constant to mark a test step as incomplete. A test step is incomplete if the step is not passed but not failed either and if you do not want to use blocked (incomplete will be overruled by failed).

62 Chapter 8. Reporting TTA Documentation, Release 1.15.2

NO_RUN = 'NoRun' Use this constant to mark a test step as norun. This means the test has not been executed and this report does not contain a valid result for it. PASSED = 'Passed' Use this constant to mark a test step as passed. class tta.reporting.constants.ResultTypeEnum This enumeration is used to describe the type of a result entry in TTA’s reporting database. It can be either a result (root of a test case’s report) or a step.

8.7 tta.reporting.htmlconverter

This module contains methods to write test reports to HTML files. tta.reporting.htmlconverter.write_html_reports(report, target_folder, in- clude_details=True, in- clude_test_case_overview=True, in- clude_overall_overview=True, back- link=None) Writes HTML reports for all specified test result objects. Parameters • report (TTAReport) – Report object to write HTML reports for • target_folder (str) – Folder to store HTML reports • include_details (bool) – Include detailed data from test step results. • include_test_case_overview (bool) – If True, for each test case an overview containing all its results will be created. • include_overall_overview (bool) – If True, an overview containing all test cases will be created. • backlink (tuple) – Name and URL (tuple, or just URL as str) of custom html to back- link to. If None, no backlink will be added.

8.7. tta.reporting.htmlconverter 63 CHAPTER NINE

DEVICE CONFIGURATION

This page lists configuration instructions for various devices which can be used with TTA.

9.1 Telemotive data loggers

It is possible to use blue PiraT Mini and blue PiraT 2 (next generation) data loggers as CAN interface devices. This feature is available since firmware version 2.1.1. For this to work, the logger must have a valid Testautomation license (“Testautomation-Framework”) installed. To install a license you start and connect the Telemotive System Client and go to “Firmware Update -> Update licenses. . . ”. You can then upload the license file. After uploading you should restart the data logger.

Fig. 1: Firmwareupdate and Update Licenses.

First the Logger needs to be configured using the Telemotive System Client, during this process a few Settings need to be adjusted. Testautomation: The Testautomation option needs to be activated. It can be found at “General->Test automation” and will be available after installing the license. Activate Online Streaming: Under “Online Streaming -> Online Streaming” the check mark for “Online Streaming active” needs to be set. CAN channels: The CAN channels you want to use need to be activated also. In addition, the check mark next to “Acknowledge ON” needs to be set. For use in TTA you can either specify the calling parameters in the config.yaml or alternatively configure them when you call the CAN-Unit in your testcases. Argument “device_id” contains the IP address or hostname of the corresponding data logger, for “driver” use value “DriverBPNG”.

64 TTA Documentation, Release 1.15.2

Fig. 2: Test Automation Settings.

Fig. 3: Activated Online Streaming.

Fig. 4: CAN Settings.

9.1. Telemotive data loggers 65 CHAPTER TEN

XML-DESCRIPTION OF A TEST CASE

This page brings some explanation about how to describe a test case in the TTA-XML Test case descriptions format.

10.1 XML Structure

The TTA-XML description is divided in 6 parts: • Test description • Test parameters • Preconditions • Test steps • Postconditions • Test data The test description defines the aim of the test case. The test parameters block defines the parameters of the test case. The test preconditions, test steps and postconditions define all the steps of your test case. The test data specifies some parameters from the test case, such as the test id and test author, in order to be able to store the test in a database for example.

10.2 Structure of a TestStep

In the preconditions block, test steps block and postconditions block, the structure of a test step remain the same. You first specified the name of the TestStep with the attribute “name”, then you provide a short description of it in the “Description” tag and the expected result in the “Expected” tag. Example of a TestStep

This is the description of the TestStep The tester understood the structure of a TestStep

66 TTA Documentation, Release 1.15.2

10.3 Example

Example of Testcase XML description:

The test will prove if the DUT goes to Bootloader mode after

˓→receiving the Programming Session change request The device has to be turned off No bus traffic Power has to be applied and tester present has to be enabled

˓→on the bus Device goes to application mode Send: 10 01 Default Session Diagnostic Session Control

˓→Description> Receive: 50 01 Positive response Send: 10 03 Extended Session Diagnostic Session Control

˓→Description> Receive: 50 03 Positive response Send: 10 02 Programming Session Diagnostic Session Control

˓→Description> Receive: 7F 10 Response Pending Receive: 50 02 Positive response (bootloader sends it)

˓→Expected> Shutdown device No bus traffic 1 Max Mustermann 0000

10.3. Example 67 CHAPTER ELEVEN

TTA DYNAMIC CODE COMPLETION

A nice feature to help to develop test cases is the code completion. A huge part of it, the statical code completion is already available in Eclipse/Pydev and can be used, during the development of TTA test cases. However, nothing is implemented in Eclipse/Pydev, regarding dynamic code completion. A lot of informations in Automotive are stored in documents (PDX- and ODX-data for Flash-relevant informations, or the Catalog of available Diagnostics commands for an Headunit) that are dynamically parsed, in order to be imported in test cases. This is how dynamic structures are generated. The aim of the TTA dynamic code completion is to facilitate the development of test cases, by triggering as soon as you are writing the import of a dynamically generated structure, its code completion. This facilitates the development of test cases, as you will directly know where which information is stored, without even running the test case. For now, the dynamic code completion is generated on 2 events : on saving a file and on opening a file. Basically, the dynamic code completion generator will open the path to the file called in the constructor, which gen- erated a dynamic structure and generates the .pypredef file (which is used by Pydev to generate the code completion). If the path to the file is not valid, which means that the file does not exist, only the static code completion will be available.

11.1 Trigger on Save

If you implement a test case which implies the use of a dynamically generated structure, such as a PDX, you need to first save your test case, in order to generate the code completion of the corresponding file.

11.2 Trigger on Open

The dynamic code completion is also generated, when you open a new test case in Eclipse (by double-click or drag- and-drop from the navigator). This enables you to work parallel on different test cases and always have the code completion, corresponding to the dynamically defined structure you imported in your test case.

68 CHAPTER TWELVE

TTA LIB REFERENCE

The TTA lib reference describes the basic libraries offered by TTA:

12.1 tta.lib.catalog

This library provides functionality to parse different xml-based message-catalogs into python dictionaries. The parser supports the following formats: • Fieldbus Exchange Format (FIBEX) for CAN and Ethernet • AUTOSAR System Description (ARXML) for CAN

12.1.1 tta.lib.catalog.MessageCatalogParser

This is the main class to use for parsing any xml-based message-catalog. Example: A catalog can be parsed by calling the static method “parse” of the class “MessageCatalogParser”:

# import the module from tta.lib.catalog import MessageCatalogParser

# read in a file (the parser decides wether it's a fibex or a arxml) # the parser returns a dictionary parsed_dict= MessageCatalogParser.parse_file("filepath.xml")

As mentioned in the example, the MessageCatalogParser is able to automatically distinguish between fibex and arxml. That’s why we recommend to use this class when parsing a xml-based message-catalog. class tta.lib.catalog.catalog.MessageCatalogParser Using this unit a user is able to parse (currently xml-based) message catalogs like: • Fieldbus Exchange Format (FIBEX-documents) • Autosar System Descriptions (*.arxml-Files) classmethod parse_file(filepath) parse a single message-catalog into a python dictionary :param str filepath: Path to the message-catalog as string :return: a parsed message catalog :rtype: dict

69 TTA Documentation, Release 1.15.2

12.1.2 tta.lib.catalog.fibex module

The fibex module provides meta-information about the fibex file to be parsed. Each method inside the module takes a document parsed using the “parse” function of the lxml-package. Created on 18.01.2018 This module can be used to retrieve meta information about fibex files. tta.lib.catalog.fibex.get_document_info(lxml_etree_element) returns following information about the document if it’s a valid fibex: • type: “fibex” • version: d+

Parameters lxml_etree_element (lxml.etree) – xml root element Returns dict containing the described info Return type dict tta.lib.catalog.fibex.get_document_version(lxml_etree_element) returns the version number of a (valid) document Parameters lxml_etree_element (lxml.etree) – xml root element Returns version number Return type string tta.lib.catalog.fibex.get_project_information(lxml_element) returns general information about the document like: Parameters lxml_etree_element (lxml.etree) – xml root element Returns

• described channel f.e. “BODY-CAN” • view f.e. “lokal” • configuration_status f.e. ‘S15A-15-07-410 (Freeze KW27/14)’

Return type dict tta.lib.catalog.fibex.get_protocols(lxml_etree) returns a list of protocols used in this document Parameters lxml_etree – xml root element Returns list of protocols in the document Return type list tta.lib.catalog.fibex.is_supported(lxml_etree_element) returns true if the documents root elements tag is “FIBEX” Parameters lxml_etree_element (lxml.etree) – xml root element Returns true if the root tag is “FIBEX” Return type bool

70 Chapter 12. TTA Lib Reference TTA Documentation, Release 1.15.2

tta.lib.catalog.fibex.parse_document(lxml_etree) parses an arxml document and returns the resulting dict Parameters lxml_etree – xml root element Returns dict containing the parsing result Return type dict

12.1.3 tta.lib.catalog.arxml module

Similar to the fibex module, the arxml module provides meta-information about the arxml document to be parsed. Each method inside the module takes a document parsed using “parse” function of the lxml-package. Created on 18.01.2018 tta.lib.catalog.arxml.get_document_info(lxml_etree_element) returns following information about the document if it’s a valid fibex: Parameters lxml_etree_element (lxml.etree) – xml root element Returns

• type: “fibex” • version: d+

Return type dict tta.lib.catalog.arxml.get_document_version(lxml_etree_element) returns the version number of a (valid) document Parameters lxml_etree_element (lxml.etree) – xml root element Returns version number Return type string tta.lib.catalog.arxml.get_project_information(lxml_element) returns general information about the document like: Parameters lxml_etree_element (lxml.etree) – xml root element Returns

• described channel f.e. “BODY-CAN” • view f.e. “lokal” • configuration_status f.e. ‘S15A-15-07-410 (Freeze KW27/14)’

Return type dict tta.lib.catalog.arxml.is_supported(lxml_etree_element) returns true if the documents root elements tag is “AUTOSAR” Parameters lxml_etree_element (lxml.etree) – xml root element Returns true if the root tag is “AUTOSAR” Return type bool

12.1. tta.lib.catalog 71 TTA Documentation, Release 1.15.2 tta.lib.catalog.arxml.parse_document(lxml_etree) parses an arxml document and returns the resulting dict Parameters lxml_etree – xml root element Returns dict containing the parsing result Return type dict

12.1.4 resulting dictionary (CAN)

The parser returns the dictionaries with the same keys and almost the same values (there are some minor differences in the naming conventions of both filetypes) for both message-catalog types. The content of some minor important field can differ between the formats. A resulting dictionary for CAN is structured like this:

{ "FFF":{ "long_name_de":"...", "long_name_en":"...", "short_name":"...", "signals": [{ "bit_position":0, "long_name_de":"...", "long_name_en":"...", "short_name":"...", "description_de":"...", "data_type":{ "bit_length":8, "category":"FIXED_LENGTH", "base_datatype":"uint8" }, "is_high_low_byte_order": true, "compu_methods":{ "Linear":{ "compute_rational":{ "numerators":[ 0.0, 1.0 ], "denominators":[ 1.0 ] } }, "Identical":{ "internal_constraints": [{ "upper_limit": 255.0, "lower_limit": 0.0, "validity": null }], "category":"IDENTICAL" }, "physical_constraints": [{ "upper_limit": 255.0, "lower_limit": 0.0, "validity": null }] } (continues on next page)

72 Chapter 12. TTA Lib Reference TTA Documentation, Release 1.15.2

(continued from previous page) }] } }

12.1. tta.lib.catalog 73 CHAPTER THIRTEEN

TTA UNITS REFERENCE

The TTA units reference describes the basic units offered by TTA:

13.1 tta.units.android.android

This module provides the basic communication layer between the Android device and TTA. All other classes and Android related units should be based on this base class. The Android Unit contains the ADB class, which controls the connection to the device. It also contains the AndroidBase class, which provides the basic communication with the device. Features: • Open and close connection to the Android device via the adb shell. • Read serial number from the shell, if more than one device is connected. • Get the output from the adb shell. • Collect commands and execute a command sequence. class tta.units.android.android.ADB Class container for different adb commands, all static methods classmethod check_adb() Check for adb.exe to be reachable via path environment variable, but do not check at import, just when it is used. static connect(host) Connect device with ADB server via TCP/IP Parameters host (str) – Host to connect to: “:[]” Returns True if command was successful Return type bool static devices() Returns the list with detected devices, even if only one is detected. Returns List of device identifiers Return type list static disconnect(host=”) Disconnect device with ADB server via TCP/IP Parameters host (str) – Host to connect to: “:[]”, if empty, all devices get disconnected

74 TTA Documentation, Release 1.15.2

Returns True if command was successful Return type bool static kill_server() Kill the adb server to clean up all static pull(folder, output_folder) Pulls a file from device to host Param str folder: path to the folder on the device Param str output_folder: path to the outputfolder on host class tta.units.android.android.AndroidBase(device_id=None) This unit is the layer between TTA and the android device Android API to simulate an android user Parameters device_id (str) – Device identifier (can be either a usb device serial or a host target) add_command_to_sequence(command) Append a new command to the to the current sequence, return true if command is added Parameters command (list) – New command or list of commands clear_command_sequence() Clear the command sequence close_shell_connection(android_shell=True) Close the connection to the process and return the output from the shell Parameters android_shell (bool) – Defines if the android shell is started Return type bool execute_command_sequence(android_shell=True) Execute a prepared sequence of commands Parameters android_shell (bool) – Defines if the android shell is started Returns Number of commands executed Return type int execute_single_command(command, android_shell=True) Execute a single command and forwards this to the device Parameters • command (str) – single command e.g. input tap 100 100 • serial (str) – defines the serial of the device • android_shell (bool) – defines if the android shell is started Returns Stdout of command execution Return type bytes get_process_output() Return a list of strings with the output of the console Returns Output list Return type list

13.1. tta.units.android.android 75 TTA Documentation, Release 1.15.2

is_screen_off() Returns True if screen is off Returns True if screen is off Return type bool is_shell_alive() Check whether the adb connection is still working and alive Returns State of adb connection Return type bool open_shell_connection(android_shell=True) Create the new adb process Parameters android_shell (bool) – Defines if the android shell is started Return type subprocess.Popen

13.2 tta.units.android.logcat

This android module provides the Logcat functionality from the Logcat in the adb shell Features: • Get Logcat logs from the device • Search in logfiles or in the live log for specific log line • Create events for log lines • Use Logcat filter • Create listener threads for each device

13.2.1 Logcat Unit

The Logcat Unit Object includes the following features • Get Logcat logs from the device • Search in logfiles or in the live log for specific log line • Create events for log lines • Use Logcat filter The Logcat Unit is based on the android base class, Android Logcat API to simulate an Android User class tta.units.android.logcat.Logcat This Unit provides Events due to Logevents Android Logcat API to simulate an Android User: class Logcatlistener(serial, threadqueue, events, lc_filter, logcat) this is the class for a subthread within the logcat unit find_log_line(serial, event_string, logs=None) searches for a special log line in the log files

76 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters • serial (str) – defines the serial number of the target device • event_string (str) – specifies the specific log line • logs (list) – optional parameter to analyze given logs get_logs(serial, use_filter=True) this method receives the Log Buffer from the devices and flushes the buffer after receiving the data Parameters • serial (str) – defines the serial number of the target device • use_filer (bool) – choose if a filter is used of not run_in_thread() this method is the main loop for the logcat listener thread set_alive_status(status=False) this changes the alive Status of according to the parameter Parameters status (bool) – defines the status of the Thread set_listener_intervall(interval) sets the interval the listener gets the logs from the device and analyzes these logs Parameters interval (float) – interval time in seconds wait_interval() this method waits until the interval time is over, during that time the message queue will be checked add_event_string(new_event_string, serial=’all’) this method adds a new event_string to the the devices, the logcat unit will be looking for these strings Parameters • new_event_string (str) – defines the desired log line • serial (str) – defines the serial number of the target device create_new_thread(serial) this creates a daemon thread in the logcat unit with the method self.run_in_thread() the structure of the thread dict is {:[thread_opbject, queue, status/bool],<>:[. . . .] Parameters serial (str) – defines the serial number of the target device Return type Queue find_log_line(serial, event_string, logs=None) Searches for a special log line in the logfiles Parameters • serial (str) – defines the serial number of the target device • event_string (str) – specifies the specific log line get_logs(serial, use_filter=True, clear=True) This method receives the Log Buffer from the devices and flushes the buffer after receiving the data Parameters • serial (str) – defines the serial number of the target device • use_filter (bool) – If True use associated filter • clear (bool) – If True clear log after retrieving Return type list

13.2. tta.units.android.logcat 77 TTA Documentation, Release 1.15.2

set_filter(serial, buffer=”, logformat=”, level=’V’) this sets the log level for the Logs to be checked possible levels: V - Verbose (lowest priority) D - Debug I - Info W - Warning E - Error F - Fatal S - Silent (highest priority, on which nothing is ever printed) Parameters • serial (str) – defines the serial number of the target device • buffer (str) – defines the log buffer: radio, events, main • logformat (str) – defines how the logs are formated • level (str) – choose which level shall be used start_thread(serial=’all’) start a listener thread for a specific device Parameters serial (str) – defines the serial number of the target device stop_thread(serial=’all’) stops a listener thread for a specific device Parameters serial defines (str) – the serial number of the target device

13.2.2 basic logcat usage

Initialize the Logcat Unit, as soon as the unit is initialized, a screening for connected devices is started and the log buffer of every device is cleared Example:: from tta.units.android.logcat import Logcat logcat= Logcat() serials= logcat.get_serials()

Get logs from the device: there are two ways to get logs from the device. The first way is to use the method logcat. get_logs()() from the Logcat Unit. The second way is to use events (described in ADVANCED LOGCAT USEAGE, which can be found down below). Similar to the android unit, it is also possible to get the serials available from the Logcat unit. Moreover, it is possible to set some filter, which reduces the returned amount of data. Specification of ADB Logcat command: https://developer.android.com/studio/command-line/logcat.html Example: 1. Set the filter for the desired device with the serial number 2. Wait some time until the logs can be written (remember the buffer was cleared before) 3. Get the Logs from the device and print these to the console 4. find a defined line in the logs, here it is possible to send already recorded logs or record new logs

# 1. logcat.set_filter(serials[0], logformat="time", level="W") # 2. time.sleep(10) # 3. logs= logcat.get_logs(serials[0]) if logs: for ele in logs: (continues on next page)

78 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

(continued from previous page) print("\t\t Logs:"+ str(ele)) # 4. res= logcat.find_log_line(serials[0],"DCD ON") print("------new recorded ------" print(res) print("------new recorded ------") res= logcat.find_log_line(serials[0],"DCD ON", logs) print("------old recorded ------") print(res) print("------old recorded ------")

Note: the method find_log_line() returns the desired logline

13.2.3 Advanced logcat usage

There is a second way to get logs from the device, in this example, events will be used. These events can be used to set a listener for a certain log line, this listener runs in an independent thread. Each device has its own listener thread, to activate events with logcat (there a several steps necessary). Example: 1. Add a event to the event list, it is possible to add several lines to a listener, in this example the keywords “DCD” and “Battery” will trigger an event 2. Create the listener thread for the specified device 3. Create the EventSource to receive the events 4. Start the listener thread so the events can be triggered 5. Collect the data from the event source and the thread queue 6. Stop the listener thread so the unit can shutdown

#imports from tta.units.android.logcat import Logcat logcat= Logcat() serials= logcat.get_serials()

# 1. logcat.add_event_string("DCD") logcat.add_event_string("Battery")

# 2. Note: currently there is also a queue returned, which is a direct link to the

˓→listener # the found log lines are also in this queue thread_queue= logcat.create_new_thread(serials[0])

# 3. src= EventSource(logcat)

# 4. logcat.start_thread(serials[0])

# 5. in this demo, there's a waiting time and during this time, the events are logged # you can do your stuff instead for i in range(0, 10): (continues on next page)

13.2. tta.units.android.logcat 79 TTA Documentation, Release 1.15.2

(continued from previous page) time.sleep(1) print("waiting:"+ str(i)) print("##################### EVENTSOURCE ########################") while src.qsize() !=0: print("------src.get(): ------") print(src.get()) print("------\r\n") while thread_queue.qsize() !=0: print("------thread_queue.get():------") print(thread_queue.get()) print("------\r\n") print("##################### EVENTSOURCE ########################")

# 6. logcat.stop_thread(serials[0])

Note: Please make sure to stop the thread if it is not needed any more.

13.3 tta.units.audio

This module provides a TTA unit interface to record and analyze audio signals. Among other things, it allows you to identify warning signals, music, speech or navigation voices and evaluate its quality. Most of all, you can automate your voice control and voice testing. Features: • Record an audio signal (using the microphone input) • Play an audio signal • Identify a reference audio signal in a recorded signal • Analyze the recorded signal using signal processing techniques • Create a speech signal with speech synthesis • Create graphics for the reporting

13.3.1 How to use the audio unit

This chapter explains, how to use the Audio Unit, starting with signals. The following sections point out how to record, replay and analyze an audio signal.

13.3.1.1 Signal

The audio Unit is focused around Signals, which means that usually functions are called on the Signal object and these objects are used to store all the important data we receive from the recorder or a local file. To load a file as a Signal object you can use: classmethod Signal.from_file(filepath) Load Audio Signal from File Parameters filepath (str) – Location where the audiofile is stored Returns Object including all relevant information about the audiofile

80 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Return type AudioData Vice versa if you want to create a Signal from recorded samples use the following method: classmethod Signal.from_recorder(recoder) Retrieve Audio Signal from Recorder Parameters recorder (Recorder) – Recorder Instance Returns Recorded Signal For further instructions on how to use the recorder see down below.

13.3.1.2 Recorder

To record a Signal you first have to intiialize a recorder and point it to the needed audio source. To get a list of all detected input devices use the method: static Recorder.get_available_devices() Get all available input devices Returns Available Audio Input devices Return type list Once you are sure which device you need you can initialize the recorder as such:

import time from tta.units.audio.audio import Signal from tta.units.audio.recorder import Recorder

rec= Recorder(iface_name=) # Init Recorder for device rec.start_recording() time.sleep(5) rec.stop_recording() sig= Signal.from_recorder(rec) # Turn into signal

Note: If you dont specify an iface_name then the Windows standard device will be chosen.

Save to File It is also possible to export the recorded signal to a file like so:

sig= Signal.from_recorder(rec) sig.to_file()

13.3.1.3 Player

Similar to the Recorder the Player works in the same manner, you first have to chose an Audio Interface to output the sound on via get_available_devices() and afterwards you can use the player as such:

from tta.units.audio.player import Player player= Player(iface_name=) player.play_signal() # Play Signal from signal object player.wait() # Wait for signal to finish playing player.play_recorder() # Play from recorder player.stop_playing()

13.3. tta.units.audio 81 TTA Documentation, Release 1.15.2

13.3.1.4 Identification

Use the following method to identify a reference signal in the recorded signal: Signal.compare(other) Compare Signal objects by calculating the normalized cross-correlation between their samples Parameters other (Signal) – AudioData Signal object containing samples This allows you to compare two signal objects to each other channel by channel and receive the best match:

from tta.units.audio.audio import Signal

= Signal.from_file() ref= Signal.from_file()

tar.compare(ref)

Warning: Make sure the samplerate and bit width of the audiofile matches up.

Resampling If you have files with different samplerates that you want to compare you can use the built in functionality in this Audio Unit to achieve that, simply set the samplerate property in the Signal object. Signal.samplerate() Getter Returns Samplerate Setter Changes Samplerate to given value and resamples data accordingly Returns Samplerate Return type int

Note: The identification is slower than the recording. After the stop method is called the thread runs as long as the recording queue is not empty.

13.3.1.5 Signal processing

With the Audio Unit, you can analyze audio signals using the following four different signal processing: 1. Total harmonic distortion (THD) 2. Signal to noise ratio (SNR) 3. Fast Fourier-Transformation (FFT) 4. Get the dominant frequency Calculate THD: class tta.units.audio.audio.Signal.get_THD This method returns the THD value of an audio file. Parameters signal_frequency (int) – the dominant frequency of the signal (if it’s unknown use getDominantFrequency) Returns return the total harmonic distortion in % of the file

82 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Return type float Calculate SNR: class tta.units.audio.audio.Signal.get_SNR Returns the ‘signal to noise ratio ‘ (SNR) from an Audio signal which is saved as a .. Returns the SNR value in dB Return type float Calculate FFT: class tta.units.audio.audio.Signal.get_FFT Gets the whole FFT spectrum in the range between 0 Hz an samplerate/2 Hz. Returns fft_frequencys as array, fft_coeff as array Return type fft_frequency, fft_coeff, img Calculate Dominant Frequency: class tta.units.audio.audio.Signal.get_DominantFrequency Gets the dominant frequency of an Audio signal. Returns dominant frequency of the audio signal Return type float

13.3.1.6 Speech processing

You can simulate a speech control of your test resource using the speech processing feature. There are two modes, in which the speech processing can run: online or offline.

Note: If you operate the speech processing online, the unit uses Google tools. Operate the unit offline, if you do not want to involve Google in your testing in anyway.

To switch the connection use the method: It is also possible to adjust the speech speed. To change the speech speed use the method: To change the language use the method: To see all available languages use: To translate the text to a voice signal use:

Note: To get more offline Languages use the program eSpeak (without eSpeak only the Windows-Anna speech package is available).

Below you can find a code example for the speech processing to put in your test case: def step_001_online_speech_slow_en(self): """ set text-to-speech to online-access

:name: step_001_online_speech_slow_en :expected: allow the text-to-speech engine to access google text-to-speech. """ (continues on next page)

13.3. tta.units.audio 83 TTA Documentation, Release 1.15.2

(continued from previous page)

all_results= False

# allow online connection self.tts.set_SpeechOnlineConnection(True)

# use English language result1= self.tts.set_SpeechLanguage('en')

# use speech speed slow result2= self.tts.set_SpeechSpeed('slow')

# speak the text "Hello Word!" result3= self.tts.textToSpeech("Hello World!")

# check if all results are True if (result1 == True) and (result2 == True) and (result3 == True): all_results= True

self.assertTrue(all_results)

13.3.1.7 Plotting

If you want assistance in visualizing your data you can use the Plotter class of the Audio Unit, here you get a variety of functions aiming to best represent the given data: class tta.units.audio.plot.Plotter Plot Audio Signals classmethod plot_fft(freq, coef, title=’Spectrum’, size=(16, 9)) Takes the output of get_FFT() and plots it nicely Parameters • freq (np_array) – FFT Frequencies • coef (np_array) – FFT Coefficient classmethod plot_signal(signal, size=(16, 9)) Parameters signal (Signal) – Signal object with data to plot static plot_snr(snr) Parameters snr (np_array) – SNR values to plot classmethod plot_thd(samples, samplerate, freq, coef, number_of_periods=5, size=(16, 9)) Takes relevant data and plots samples alongside FFT

13.3.1.8 Module

This package contains the TTA Audio-Unit @author: qi11269, qi11402 class tta.units.audio.audio.AudioData(samplerate, dtype, channels, samples=b”) Audiodata class Constructor

84 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters • samplerate (int) – Samplerate of the audio file • dtype (int) – Samplewidth • channels (int) – How many channels are available • samples (list) – List of individual frames bdata Returns Samples Return type list data Returns Data Return type np_array duration Returns Duration of audio file Return type int (seconds) is_compareable(other) Check if two audiodata objects are comparable Parameters other (AudioData) – Object containing information about an audio file class tta.units.audio.audio.Signal(samplerate, dtype, channels, samples=b”, filepath=None) Signal Class inherits from AudioData Constructor Parameters • samplerate (int) – Samplerate of the audio file • dtype (int) – Samplewidth • channels (int) – How many channels are available • samples (list) – List of individual frames • filepath (str) – Location of the audio file compare(other) Compare Signal objects by calculating the normalized cross-correlation between their samples Parameters other (Signal) – AudioData Signal object containing samples classmethod from_file(filepath) Load Audio Signal from File Parameters filepath (str) – Location where the audiofile is stored Returns Object including all relevant information about the audiofile Return type AudioData classmethod from_recorder(recoder) Retrieve Audio Signal from Recorder Parameters recorder (Recorder) – Recorder Instance Returns Recorded Signal

13.3. tta.units.audio 85 TTA Documentation, Release 1.15.2

get_DominantFrequency() Gets the dominant frequency of an Audio signal. Returns dominant frequency of the audio signal Return type float get_FFT() Gets the whole FFT spectrum in the range between 0 Hz an samplerate/2 Hz. Returns fft_frequencys as array, fft_coeff as array Return type fft_frequency, fft_coeff, img get_NoisePower(reference_signal) Records the noise for the defined duration time and computes the noise power. It must be ensured that no signal is outputed in order to only measure the noise. Parameters duration (int) – recording time of the noise in seconds. get_SNR() Returns the ‘signal to noise ratio ‘ (SNR) from an Audio signal which is saved as a .wav. Returns the SNR value in dB Return type float get_THD(signal_frequency=0) This method returns the THD value of an audio file. Parameters signal_frequency (int) – the dominant frequency of the signal (if it’s un- known use getDominantFrequency) Returns return the total harmonic distortion in % of the file Return type float play(block=True) This method plays the corresponding audio signal. plot() Plot the current signal Returns Plot as Image Return type PIL Image samplerate Getter Returns Samplerate Setter Changes Samplerate to given value and resamples data accordingly Returns Samplerate Return type int split(number_of_frames) Splits the array of frames at a given point Parameters number_of_frames (int) – where to split the signal Returns Partial Signal Return type list to_file(filepath) Save Audio Signal to File

86 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters filepath (str) – Location where the audiofile will be stored class tta.units.audio.audio.SignalProcessing Handles all calculations such as: CrossCorrelation, THD, FFT, DominantFrequency, SNR classmethod compare(target, reference, result, normalized=True) Compare lists of samples from AudioData objects Returns Normalized Cross-Correlation Return type float classmethod get_DominantFrequency(audio_data) Gets the dominant frequency of an Audio signal. Returns dominant frequency of the audio signal Return type float static get_FFT(audio_data) Gets the whole FFT spectrum in the range between 0 Hz an samplerate/2 Hz. Returns fft_frequencys as array, fft_coeff as array Return type fft_frequency, fft_coeff, img classmethod get_NoisePower(target, reference) Records the noise for the defined duration time and computes the noise power. It must be ensured that no signal is outputed in order to only measure the noise. Parameters duration (int) – recording time of the noise in seconds. classmethod get_SNR(audio_data) Returns the ‘signal to noise ratio ‘ (SNR) from an Audio signal which is saved as a .wav. Returns the SNR value in dB Return type float classmethod get_THD(audio_data, signal_frequency=0) This method returns the THD value of an audio file. Parameters • signal_frequency (int) – the dominant frequency of the signal (if it’s unknown use getDominantFrequency) • plot (bool) – True: The method create an image of the signal (spectrum and zoomed signal). Get the image with the get_img_THD() method. Returns return the total harmonic distortion in % of the file Return type float

13.4 tta.units.can.bpng

This module defines the interface classes for Telemotive BPNG data loggers, this covers blue PiraT Mini and blue PiraT 2. At the current state, the module only contains the BPNGComDll interface for CAN communication. class tta.units.can.bpng.BPNGCom(ip_addr=’192.168.0.233’, sendonly=False) BPNGCom class, interface to BPNG loggers (bP Mini and bP 2) Parameters ip_addr (str) – IP address of data logger

13.4. tta.units.can.bpng 87 TTA Documentation, Release 1.15.2

close_can(channel=0) Close CAN channel: unregister callback for receiving messages Parameters channel (int) – CAN channel close_driver() Close connection to data logger open_can(channel=0, baudrate=500000, callback_recv=None, callback_error=None) Open CAN channel: register callback for receiving messages Parameters • channel (int) – CAN channel to connect to • baudrate (int) – Baud rate (is ignored at the moment) • callback_recv (callable) – Callback function for receiver • callback_error (callable) – Callback function for error counter Signature of callback_recv:

def callback_recv(ident, dlc, dat0, dat1, dat2, dat3, dat4, dat5, dat6, dat7, channel, flag, timestamp_high, timestamp_low)

Signature of callback_error:

def callback_error(self, channel, counter)

open_driver() Open driver resp. connect to data logger send(channel, ident, data) Send a CAN message Parameters • channel (int) – CAN channel to send message to (first is ‘0’) • ident (int) – CAN identifier of message • data (list) – List of data bytes class tta.units.can.bpng.BPNGComUnit(ip_addr=’192.168.0.233’) BPNGCom Unit class, Unit wrapper for BPNGCom (monostate behavior needed) Parameters ip_addr (str) – IP address of data logger class tta.units.can.bpng.CANMsgFlag Enum class for flags of incoming CAN message CF_ERROR = 1 CAN error frame CF_TXMESSAGE = 64 CAN tx (transmit) message CF_TXREQUEST = 128 CAN tx (transmit) message request class tta.units.can.bpng.CErrFrameCntr Struct for getting error feedback class tta.units.can.bpng.CReceivedData Struct for received CAN messages

88 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2 class tta.units.can.bpng.CanMsgStruct Struct for sending CAN messages

13.5 tta.units.can

This module provides a TTA unit interface to different CAN bus devices. It further contains classes for CAN messages and CAN message filters, which select user defined messages, received by the unit. A CAN bus hardware device usually offers multiple channels (which can be configured to individual baud rates). This is because you want to connect the CAN device to multiple CAN networks. So one channel can be connected to a specific CAN network. The device then is able to send CAN messages and to receive them (whereby a time stamp is logged for both, sent and received messages). To access a CAN bus device from TTA, you have to open a CAN unit object. This CAN unit object then can interact with a specific channel of the device. That means, one CAN unit is associated to one device channel on one device. The CAN unit then has functions/interfaces to send and receive CANMessage objects on the associated chan- nel/network.

13.5.1 CAN - CAN unit

The CAN unit object is associated to a CAN device’s channel. You can define the device_id, the channel and the baud rate, which should be used when connecting. The device_id might be either a domain name, or an IP address, or a device serial number (as string). The channel index number defines the channel to use, the index starts at 0. The baud rate argument defines the baud rate in bits per second - e. g. 500000 means 500 kBit resp. 500000 bits per second. For receiving messages the CAN unit has an EventSource interface (see Receiving CAN messages). Example: Two blue PiraT Mini loggers can be accessed from your PC via TCP/IP network and have the domain names mini1.net and mini2.net. To use HSCAN1/HSCAN3 (high speed CAN) on mini1.net and HSCAN4 (low speed CAN) on mini2.net, you have to create 3 CAN units: can1_HS1= CAN(device_id="mini1.net", channel=0, baudrate=500000) can1_HS3= CAN("mini1.net",2) # baudrate default is 500000 can2_HS4= CAN("mini2.net", channel=3, 125000)

Please note that the channel index starts at 0, while the channel symbolic name, defined by the device manufacturer, often starts at 1 (e. g. HSCAN1, HSCAN2, HSCAN3, . . . ) class tta.units.can.CAN(device_id=’192.168.0.233’, channel=0, baudrate=500000, virtual=False, driver=’DriverVector’, tracefile=None, init_par=None) The CAN Unit provides access to the CAN bus. It supports different types of hardware. Parameters • driver (str) – Driver name or class (e. g. “DriverVector”, “DriverBPNG” . . . ) • device_id (str) – Identifier of device, can be IP-address, serial number or None • channel (int) – CAN channel • baudrate (int) – Baud rate of CAN channel • _virtual (bool) – If True, Unit starts in virtual mode (no driver attached, developer only)

13.5. tta.units.can 89 TTA Documentation, Release 1.15.2

send(msg) Send a CAN message Parameters msg (CANMessage) – CAN message Returns Handle to message in interface module Return type int send_multiple(list_msg, repetitions=1, cycle=0, delay=0) Send a CAN message Parameters • list_msg (CANMessage) – List of CAN messages • repetitions (int) – Repetitions (only DriverVector) • cycle (int) – Cycle time (microseconds) (only DriverVector) • delay (int) – Delay after sending starts (microseconds) (only DriverVector) start_streaming() Start streaming offline trace

13.5.2 CANMessage, CANMsgType - CAN messages

Any data, which is sent to, or received from a CAN bus channel, is formatted in a CAN message. CAN messages contain a data payload within a CAN frame. The properties of the frame are defined with a CANMsgType Enum, but the correspondent integer values can be used too. Supported are CAN 2.0A/B and CAN FD frames, the appropriate frame bits are defined in the type attributes (ident_type, frame_type, dir_type, rate_type, which holds values of CANMsgType). Example: You can create CANMessage objects, or modify, or compare them:

# Create messages my_ident= 0x478 my_data=[0x07, 0x08] my_value= 0x99 msg1= CANMessage(0x777,[0x01, 0x02, 0x04]) msg2= CANMessage(0x677, list_data) msg3= CANMessage(my_ident, [0x01, 0x07, my_value, 0x00]) msg4= CANMessage(0x677,[0x07, 0x08]) msg5= CANMessage(0x123456, my_data) # automatically extended identifier

# Compare messages msg1 == msg2 # will return False msg2 == msg4 # will return True, CANMessage objects have same values

Some more special examples:

# Short identifier, but CAN 2.0B frame with extended identifier msg6= CANMessage(0x331, my_data, ident_type=CANMsgType.Ident.Extended)

# Remote frame (automatically extended identifier) msg7= CANMessage(0x1D007812, my_data, frame_type=CANMsgType.Frame.Remote)

# CAN FD automatically, with higher alternate bit rate; payload data (continues on next page)

90 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

(continued from previous page) # list contains 10 bytes, will be padded to 12 bytes for CAN FD format list_data=[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A] msg8= CANMessage(0x3C2, list_data) msg8.rate_type= CANMsgType.Rate.Alternate

class tta.units.can.CANMessage(ident, data, dlc=None, channel=-1, ident_type=, frame_type=, rate_type=, dir_type=, timestamp=0, flags=0) Class for CAN messages Properties of CAN message class Parameters • ident (int) – CAN identifier • data (list) – Data • dlc (int) – Data length count • channel (int) – Channel of message (if provided, otherwise -1) • ident_type (CANMsgType.Ident) – Identifier type (base=11 Bit/CAN 2.0A, ex- tended=29 Bit/CAN 2.0B) • frame_type (CANMsgType.Frame) – Frame type (data, remote, error, overload, data FD) • rate_type (CANMsgType.Rate) – Rate type (standard, alternate=CAN FD only) • dir_type (CANMsgType.Dir) – Direction type (RX/TX) class tta.units.can.CANMsgType Class for all enums of CAN message properties class Dir Enum for transfer direction type Rx = 0 CAN direction is receive: RX Tx = 1 CAN direction is send: TX class Frame Enum for frame type Data = 0 CAN data frame DataFD = 4 CAN FD data frame Error = 2 CAN error frame Overload = 3 CAN overload frame

13.5. tta.units.can 91 TTA Documentation, Release 1.15.2

Remote = 1 CAN remote frame (RTR bit set) class Ident Enum for CAN identifier type Base = 0 CAN identifier for base format, 11 bits, CAN 2.0A Extended = 1 CAN identifier for extended format, 29 bits, CAN 2.0B class Rate Enum for bit data rate type Alternate = 1 CAN alternate data rate, higher data rate only available for CAN FD Standard = 0 CAN standard data rate, used for CAN 2.0A/B and CAN FD

13.5.3 Sending CAN messages

You can easily send CAN messages directly via CAN units: can= CAN("192.168.0.233",2) msg= CANMessage(0x323,[0x01, 0x02]) can.send(msg) can.send(CANMessage(0x777,[0x03, 0x0F]))

Not all CAN bus hardware devices support all message flags for message transmit - e. g. remote or overload flags usually are not available. Unsupported flags in CANMessage objects will be ignored.

13.5.4 Receiving CAN messages

For receiving, the CAN unit provides an EventSource interface. You just have to create an EventSource and attach it to the unit. The EventSource then will receive events from the unit, which contain the corresponding message. Example: can= CAN("192.168.0.233",0) src= EventSource(can) time.sleep(2.0) # wait for 2 seconds src.close() for ev in src: tta_time= ev.timestamp # timestamp in TTA dev_time= ev.timestamp_device # timestamp from CAN device msg= ev.value # value holds CANMessage object print(tta_time, dev_time, msg)

As the CAN unit is operating on a CAN bus hardware device, the event can provide “timestamp_device”, which will be the time stamp referring to the device’s internal clock. This clock usually is more accurate than the clock of the operating system, where TTA runs. Use timestamp_device, if you need reliable and undistorted time stamps for CAN

92 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2 messages you can compare with millisecond precision (or higher precision, dependent on the CAN bus hardware device capabilities). If you want to receive only certain messages, a CANFilter can be used with an EventSource. Example: can= CAN("192.168.0.233",0)

# Receive only messages if identifier is either 0x12F OR 0x300 flt= CANFilter(0x12F)| CANFilter(0x300) src= EventSource(can, flt) time.sleep(2.0) # wait for 2 seconds src.close()

See also: tta.core.event.event tta.core.event.filter tta.core.event.source

13.5.5 CANFilter, CANFilterRange, CANFilterType - CAN filter for EventSources

This module defines three CANFilter classes, which help selecting certain CAN messages received in an EventSource. They filter for CAN message values (CANFilter), value ranges (CANFilterRange) and message type (CANFilterType): CANFilter Filter for values in message identifier, dlc and data bytes. Bit masks can be applied to identifier and data bytes of incoming messages before value is compared. CANFilterRange Filter for ranges of values in message identifier and data bytes. Bit masks can be applied to identi- fier and data bytes of incoming messages before value is range checked. CANFilterType Filter for message types. Example:

# Filter for identifier 0x12F flt1= CANFilter(0x12F)

# Filter for identifiers in range [0x120..0x130] flt2= CANFilterRange((0x120, 0x130)) # Filter for identifier 0x12F and 2nd data byte to have "5" in lower 4 bits flt3= CANFilter(0x12F,[ None, 0x05], data_mask=[None, 0x0F])

# Filter for messages with extended identifiers flt4= CANFilterType(CANMsgType.Ident.Extended) # Filter for messages with remote bit set flt5= CANFilterType(frame_type=CANMsgType.Frame.Remote)

class tta.units.can.CANFilter(ident=None, data=None, dlc=None, ident_mask=None, data_mask=None) Event filter for CAN messages, filtering identifier, dlc, data bytes by (masked) value If data_mask is not None, it must have defined a mask integer for every integer in data. Parameters • ident (int) – CAN identifier to match • data (list) – List of data bytes to match, “None” matches anything • dlc (int) – Length of data field to match

13.5. tta.units.can 93 TTA Documentation, Release 1.15.2

• ident_mask (int) – Bitmask for matching CAN identifier • data_mask (list) – List of bitmasks for data bytes, “None” means “skip” accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation class tta.units.can.CANFilterRange(ident_range=None, data_range=None, ident_mask=None, data_mask=None) Event filter for CAN messages, filtering identifier, data bytes by (masked) range Range is a tuple/list where the first element is the lower bound and the second element is the upper bound. Both bounds are inclusive. E. g.: (3,5) matches 3, 4 and 5. Parameters • ident_range (tuple) – CAN identifier range (if int, it will be extended to range inter- nally) • data_range (list) – List of data ranges (tuples) to match, “None” matches anything • ident_mask (int) – Bitmask for matching CAN identifier • data_mask (list) – List of bitmasks for data bytes, “None” means “skip” accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation class tta.units.can.CANFilterType(ident_type=None, frame_type=None, rate_type=None, dir_type=None) Event filter for CAN messages, filtering type of message If type value is “None”, the type is ignored. Parameters • ident_type (CANMsgType.Ident) – Ident type (Standard/Extended)

94 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• frame_type (CANMsgType.Frame) – Frame type (Data/Remote/Error/Overload) • rate_type (CANMsgType.Rate) – Rate type (Fixed/Flexible) • dir_type (CANMsgType.Dir) – Direction type (Rx/Tx) accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation

13.6 tta.units.datalogger.datalogger

Module for DataLogger unit and related functions class tta.units.datalogger.datalogger.DataLogger(driver=None, device_id=None, trace_path=None, of- fline_path=None) The DataLogger unit provides functions for accessing data logger devices. Parameters • driver (str) – Specifies the image grabber device driver to use • device_id (str) – Host name or identifier for data logger device, no connection if None • trace_path (str) – Path to trace file directory • offline_path (str) – Path to offline data set (ZIP-file or directory) convert_data(spans, channels) Download converted traces Examples: convert_data((datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now()), (“A-FlexRay”, “CANOE”))

convert_data((datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now()), ((“CAN”, 1), “CANOE”)) convert_data((datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now()), [(“A-FlexRay”, “CANOE”), ((“CAN”, 1), “CANOE”)]) convert_data([(datetime.datetime(2015, 10, 2, 9, 0), datetime.datetime(2015, 10, 2, 11, 30)), (datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now())], [(“A-FlexRay”, “CANOE”), (“MY-CAN”, “CANOE”), ((“CAN”, 1), “CANOE”)])

Parameters

13.6. tta.units.datalogger.datalogger 95 TTA Documentation, Release 1.15.2

• spans (list) – List of time span tuples consisting of (, ) pairs each (or only one pair), where start and end are datetime objects • channels (list) – List of channel tuples consisting of (, ) pairs each (or only one pair), where channel is either a channel name (str) or a partial tuple (DataLogger.CHANNEL_TYPE, idx) or a full qualified channel tuple like obtained with get_channels(), and format is of DataLogger.FORMAT_TYPE.

download_data(spans, do_sort=True, do_zip=False) Download offline traces Example: download_data((datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now())) download_data([(datetime.datetime(2015, 10, 2, 9, 0), datetime.datetime(2015, 10, 2, 11, 30)), (datetime.datetime(2015, 10, 2, 13, 0), datetime.datetime.now())])

Parameters • spans (list) – List of time span tuples consisting of (, ) pairs each (or only one pair), where start and end are datetime objects • bool_sort (bool) – If True, sort traces • bool_zip (bool) – If True, save offline trace to ZIP archive Returns Path to saved traces ZIP file or directory Return type str

get_time() Get time from data logger Returns Time from data logger Return type datetime is_connected() Get connection state Returns If True, device is connected Return type bool set_time(date) Set time on data logger Parameters date (datetime) – Date time to set

13.7 tta.units.ethernet

13.8 Ethernet Unit

The Ethernet Unit enables you to send frames over Ethernet with TTA. This includes all the frames from layer 2 to 7 (Ethernet frames, ARP, DHCP, UDP, TCP, ICMP, IPv4 and SOME/IP). The implementation of this unit makes use of the (win)pcap library and therefore all packets (sent and received) are constructed/parsed starting from Layer 2.

96 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.8.1 Identify your Ethernet Interfaces

The Interfaces class provides access to information about your physical network adapters connected to the computer. This includes: Adapter-ID, description, mac address, name. For every adapter you want to use, you can call the ‘get_adapter’ method and get a TTA unit instance of the Network adapter class, which can be used for sending and capturing packets. Example Use the Ethernet adapter Ethernet_Adapter_1 from tta.units.ethernet.ethernetbase import Interfaces adapter= Interfaces.get_adapter('Ethernet_Adapter_1') class tta.units.ethernet.ethernetbase.Interfaces Base class for Ethernet functionality Constructor static get_adapter(adapter_name) Get the ethernet adapter with given name Parameters adapter_name (string) – Name of the Adapter on the computer Returns Ethernet Unit Return type NetworkAdapter static get_adapter_info() Get info about all connected adapters Returns Informations about all network adapters Return type list of tuples static get_all_adapters() Get a list of connected network adapters Returns Informations about all network adapters Return type list of NetworkAdapter

13.8.2 Configure the Network Adapter

As we are building and reading messages directly from Layer 2, it is not mandatory to apply any special IP/network configuration to the network adapter you want to use; addresses have to be provided by the user when building mes- sages and the adapter is switched to promiscuous mode when capturing packets. If you require (for any special purposes) to have a special IP/network configuration for your adapter, this needs to be done using the OS command line or other tools. Example Get adapter information: from tta.units.ethernet.ethernetbase import Interfaces avail_interfaces= Interfaces.get_adapter_info() print("Adapter info:") for adapter in avail_interfaces: print("ID:", adapter[0]) print("Description:", adapter[1]) print("MAC:", adapter[2]) (continues on next page)

13.8. Ethernet Unit 97 TTA Documentation, Release 1.15.2

(continued from previous page) print("Name:", adapter[3]) print("++++++++++++++++++++++++++") class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer get_ip(idx=0) Get the IP address currently assigned to this adapter Returns Result as list of int(bytes) Return type list get_mac() Get the MAC address of this adapter Returns Result as list of int(bytes) Return type list get_netmask(idx=0) Get the netmask currently set for this adapter Returns Result as list of int(bytes) Return type list

13.8.3 Send Messages

13.8.3.1 Send single message

The send() function of a NetworkAdapter enables you to send data over Ethernet. This function takes a byte object as parameter, and it will send the data as ‘raw data’. If you want to take full benefit of the Ethernet TTA Unit (or simply just don’t want to build every packet by your own), you can generate messages with the provided protocol classes in Ethernet Structures (please refer to: Ethernet Protocols), and use the provided ‘’ method to create a byte object which can be sent. Example Use the Ethernet adapter “Ethernet”, which you can find in the Network Connections: from tta.units.ethernet.ethernetbase import Interfaces adapter= Interfaces.get_adapter("Ethernet") random_udp=

˓→'aaaaaaaaaaaabbbbbbbbbbbb08004500001c000000004011f97dc0a80001c0a80002823584d000087784

˓→' import binascii adapter.send(binascii.unhexlify(random_udp))

98 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2 class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer send(sdata) Send data on this adapter Parameters sdata (bytes) – Ethernet frame to be sent

13.8.3.2 Send multiple data

In case you want to send multiple data (in order to test the bus load for example), use can use the transmit_packets method. This is however only provided for Windows, since other OS do not support this feature in the pcap library. “Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less)” (cf. www.winpcap.org) This method is therefore mainly intended to be used in case the relative timing of packets is of importance. Using this method, you can send as much data as you want in one call. The parameters ldata and mult_rep will set the amount of data to send: ldata contains the data as a byte_array, and mult_rep set the number of times that these data should be sent. The bsync argument (following the specification of the winpcap library) determines if relative time stamps of the packages shall be considered. When creating a list of messages, the fdist argument can be used to set the time spacing between messages (e.g. to control the resulting bus load). This function also contains a mechanism that protects your computer from extensive memory usage: if the provided data needs a lot of memory, the function will cut your data in buffers which do not exceed 10 MB. The first one of them is directly sent while creating following buffers which are queued up to a maximum number of 5 (only when the oldest of five buffers in the queue is completely sent and destroyed, new buffers are created). This enables you to send data of any size, however it comes with a flaw in timing precision. The processing of successive buffers requires a certain amount of CPU cycles and the kernel driven synchronization of time stamps cannot be maintained over borders of the data buffers. Hence the timing precision for large amounts of data might not be as exact as you wish it to be. If you really need very high timing precision for large amounts of data or in case you want to define a customized spacing between each packet to be sent, you have to construct your own transmission logic using the basic winpcap functions provided in the library. There are methods for creating such buffer queues, filling them with data and transmit the buffer (the ethernet unit provides wrapping methods to directly call those functions). This way you can determine your own buffer size for the send queues, however, you need to take care of memory usage by yourself. The wrapped function for queuing data in the winpcap library needs to be provided with a pcap header object and the data buffer. In order to do so, you could use the ‘create_packet_from_bytes’ function in the Packet class (see Convenience Functions) and hence define a specific time stamp (relative to other packets) for each message to be queued. Example Use the Ethernet adapter “Ethernet” for multiple data transmission: import binascii from tta.units.ethernet.ethernetbase import Interfaces adapter= Interfaces.get_adapter("Ethernet") random_udp=

˓→'aaaaaaaaaaaabbbbbbbbbbbb08004500001c000000004011f97dc0a80001c0a80002823584d000087784

˓→' (continues on next page)

13.8. Ethernet Unit 99 TTA Documentation, Release 1.15.2

(continued from previous page) otransmission= adapter.transmit_packets([binascii.unhexlify(random_udp)], 500, #

˓→single packet sent 500 times bsync=True, fdist=500, # use

˓→relative time spacing of 500µs between messages exec_sync=False, # use asynchronous

˓→transmission in order to so something else in between autostart_send=False) # delay start

˓→of transmission, e.g. for timing

# do some stuff (e.g. create a similar object with another adapter for parallel

˓→transmissions) otransmission.start() # start transmission # do some more stuff otransmission.join() # wait until all packets sent # done class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer allocate_send_queue(icaplen) Allocate a send queue destroy_queue(send_queue) Destroy a send queue send_queue_queue(send_queue, pktheader, pktdata) Put frames in send queue transmit_packets(ldata, mult_rep=1, bsync=True, fdist=0, exec_sync=True, au- tostart_send=True) Transmit a list of frames transmit_queue(send_queue, bsync=True) Transmit send queue

13.8.3.3 Send data contained in a pcap file

You can also choose to send data contained in a pcap file. For that, use the send_from_pcapfile() function. Example Use the Ethernet adapter “Ethernet” in order to (re-)send data from a saved pcap trace: from tta.units.ethernet.ethernetbase import Interfaces adapter= Interfaces.get_adapter("Ethernet") adapter.send_from_pcapfile(r"C:\temp\example.pcap", bsync=True, exec_sync=True)

100 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2 class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer send_from_pcapfile(fpath, bsync=True, exec_sync=True) Send all frames given in a pcap file

13.8.4 Capture Packets

Ethernet packets can be captured using the basic ‘capture’ method. A filter can be applied to captured packets in order to retrieve only a subset of all incoming messages. Although it is also possible to decode and analyze captured messages (i.e. ‘filtering’ the objects, see late sections), it is highly recommended to use this option (if applicable) as it directly associates a filter with the capture in the kernel driver (cf. www.winpcap.org) and is hence much more efficient. For a detailed description of the filter syntax, please refer to e.g. https://www.winpcap.org/docs/docs_40_2/ html/group__language.html Additionally you can specify the maximum amount of packets to be captured. Using captures, you have two different options: You can either directly call the ‘capture’ method of the unit, or you use the threaded mechanism including the ‘start_capture’ and ‘stop_capture’ methods. Be aware that the direct call of the ‘capture’ method is blocking, so you need to set a maximum number of packets to be captured, otherwise your program will be stuck forever. A call of the asynchronous ‘start_capture’ returns a new instance of a capture unit (in a parallel thread) which can be used just as long as you wish to catch messages on this adapter. Please make sure to call the ‘stop_capture’ method as soon as you don’t need it any more in order to free resources. (Do not stop the capture right after you call a send command. The stop_capture command will usually be executed before the last packets could be put on the ethernet bus, so you will probably miss some packets. Insert an artificial delay - 1 sec or so - in order to avoid that) If don’t want the capture to start immediately, you can just create a capture and start it by calling the ‘capture’ method on the returned pcap unit instance. Another main difference of those two options is the way you retrieve captured messages. For the direct call you have to pass a callback function taking exactly 2 arguments (the pcap header containing time stamp information and a variable containing the data of the message) which is called each time a packet passing the filter is received. For an asynchronous capture, the packets are forwarded to (a) TTA event source(s) which you have to create and link with the capture instance. Captured (and filtered) packets are put in this/these event sources and can queried by the user at any time. In case you need to specify a callback function for incoming packets, you can use the event observer mechanism by registering (an) observer(s) and overriding the ‘on_message’ method. Objects retrieved from the event source are of type event, whereas their value attribute always contains a instance of the RawPacket class, which provides access to the pcap header object (including the time stamp of the capture) and the message byte object. If you you need to analyze the packet on protocol level, you can use the decode methods of this object in order to get a protocol class instance. Example Capture traffic using a synchronous call of the capture method: from tta.units.ethernet.ethernetbase import Interfaces adapter= Interfaces.get_adapter("Ethernet") import time def callback(oheader, odata): (continues on next page)

13.8. Ethernet Unit 101 TTA Documentation, Release 1.15.2

(continued from previous page) print("Captured packet at", time.localtime(oheader.contents.ts.tv_sec)) print("Message:", odata)

# make sure there is at least very little traffic on this adapter, otherwise the call

˓→won't return adapter.capture(callback, ilimit=1) # no filter, capture only 1 packet (max) class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer capture(fcallback, sfilter=None, ilimit=-1) Synchronous capture on this interface set_filter(ocapture, sfilter) Set a filter for a given capture handle Example Capture traffic using the asynchronous methods for packet capturing: import binascii import time from tta.units.ethernet.ethernetbase import Interfaces from tta.core.event.source import EventSource, TimeoutEventSource adapter= Interfaces.get_adapter("Ethernet") cap= adapter.start_capture(sfilter="udp") # alternatively call cap = adapter.create_

˓→capture(sfilter="udp") and then cap.capture() event_source= TimeoutEventSource(EventSource(cap), close_after=3) # source will be

˓→closed after 3 seconds random_udp=('aaaaaaaaaaaabbbbbbbbbbbb08004500001c00000000' '4011f97dc0a80001c0a80002823584d0000877840815') for _ in range(5): adapter.send(binascii.unhexlify(random_udp)) time.sleep(1) adapter.stop_capture(cap) event= None for event in event_source: # blocks until the event source is closed -> use

˓→TimeoutEventSource like shown or explicitly close the source print(event.value.bframe) if event: from tta.units.ethernet.ethernet_protocols import UDP print("Destination IP:",".".join(str(b) for b in event.value.decode(UDP).ip_

˓→header.dest_ip)) class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters

102 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer create_capture(sfilter=None, ilimit=-1, custom_callback=None, custom_arg=None, buffer_size=20, **kwargs) Start asynchronous packet capturing Returns generated capture Return type PacketCapture start_capture(sfilter=None, ilimit=-1, custom_callback=None, custom_arg=None, buffer_size=20, **kwargs) Start asynchronous packet capturing Returns generated capture Return type PacketCapture stop_capture(ocapture, async=True, unregister=False) Stop an active asynchronous capture It is also possible to record traces on a network adapter. Therefore, use the start_pcap_dump and stop_pcap_dump methods to save all network traffic to a dump file. class tta.units.ethernet.ethernetbase.NetworkAdapter(device_guid, device_desc, de- vice_mac, device_name) Class to store adapter information Parameters • device_guid (int) – Number of the device_guid on the computer • device_desc (string) – Description of the Adapter on the computer • device_mac (byte_array) – MAC address of the network adapter • device_name (string) – Name of the adapter on the computer start_pcap_dump(file_path, sfilter=None, ilimit=-1, buffer_size=20, **kwargs) Start dumping the traffic on the file with given path stop_pcap_dump(oactive_dump, async=True, unregister=False) Stop an active traffic dump

13.8.5 Convenience Functions

The Packet class provides useful functions for data conversion in order to send packets. class tta.units.ethernet.ethernetbase.Packet Basic packet class for static methods operating on general ethernet frames/packets static create_packet_from_bytes(bframebytes, otimestamp=None) Create a pcap frame which can be passed to a send queue static get_bytes_of_frame(ethframe) Get frame as byte object Returns Result as list of int(bytes) Return type list

13.8. Ethernet Unit 103 TTA Documentation, Release 1.15.2

static ip_to_bytes(str_ip) deprecated: use function in util instead static mac_to_bytes(str_mac) deprecated: use function in util instead

13.8.6 Ethernet Protocols

The ethernet unit provides several protocol classes (restraint to typical and most commonly used ethernet protocols) in order to simplify the process of constructing and analyzing messages. (De-)Serialization of packets is hereby not implemented from scratch, but makes use of an open source module called dpkt. Whereas this module implements protocol nesting from bottom to top layers (according to OSI model), the protocol classes here provide access from top to bottom, as it might be more convenient to directly access the highest layer of interest. Additionally it provides some further protocol types like Testability and SOME/IP and uses rather intuitive attribute names for protocol fields. However, the user is free to choose between the dpkt protocol classes, the ones provided by the ethernet unit, or any other module of choice. Just keep in mind that you need to create serialized byte objects in order to send data via the network adapter unit instance. The following part of the documentation will now only consider protocol classes provided by the ethernet unit. Every protocol class is derived from the BasePacket class providing a basic implementation of the ‘pack’ method, which is used for serialization of the packet into a byte object. This class is supposed to be considered as an interface and should not be used directly. For each protocol defined in the ethernet unit, you have access to the specific fields via attributes of the object. In order to make the serialization work, you need to make sure that the values you set for those fields/attributes are of correct type. Most of the values are expected to be integers, e.g. the field defining the protocol type in layer 2 ethernet headers. Only some attributes need to be directly set as byte object, like addresses (IP, MAC) and fields of variable length like IP options etc. Message objects can either be built by hand, meaning you create an instance of a protocol class and provide values for all attributes, or you provide the message as byte object (this must be the only given argument then), which is then decoded. class tta.units.ethernet.ethernet_protocols.BasePacket Base packet interface pack() Get the ethernet frame as bytes. Returns Result as list of int(bytes) Return type list

13.8.7 Ethernet

The Ethernet class defines Ethernet telegrams. Like mentioned above, mac_source and mac_destination need to be provided as a byte object. You can also specify the VLAN ID to use in your Ethernet frame, as an inner or outer VLAN. In order set values for (inner and outer) VLANS, you must provide an object of type VLAN. class tta.units.ethernet.ethernet_protocols.Ethernet(*args, mac_source=b’x00’ * 6, mac_dest=b’x00’ * 6, eth_type= dpkt.ethernet.ETH_TYPE_IP, inner_vlan=None, outer_vlan=None) Ethernet header

104 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters args (bytes) – Ethernet message Variables • mac_source (bytes) – Source MAC address • mac_dest (bytes) – Destination MAC address • inner_vlan (VLAN) – inner VLAN • outer_vlan (VLAN) – outer VLAN class tta.units.ethernet.ethernet_protocols.VLAN(tag_protocol_id=33024, priority_code_point=0, drop_eligible_indicator=0, vlan_id=0) Vlan tag Variables • tag_protocol_id (int) – Tag protocol ID • priority_code_point (int) – Priority code point • drop_eligible_indicator (int) – Drop eligible indicator • vlan_id (int) – VLAN ID

13.8.8IP

The IP class defines IP telegrams. class tta.units.ethernet.ethernet_protocols.IP(*args, ethernet_header=None, ver- sion=4, inet_header_length=5, dscp=0, ecn=0, total_length=100, identification=0, flags=0, frag- ment_offset=0, time_to_live=64, protocol=0, header_checksum=0, source_ip=b’x00’ * 4, dest_ip=b’x00’ * 4, options=b”) IP header Parameters args (bytes) – IP message Variables • ethernet_header (Ethernet) – Ethernet header • version (int) – IP protocol version • inet_header_length (int) – Length of the protocol header • dscp (int) – Differentiated Services Code Point • ecn (int) – Explicit Congestion Notification • total_length (int) – Total length of the (IP) message • identification (int) – Identification field • flags (int) – IP flags (Fragmentation) • fragment_offset (int) – Offset for fragmented data • time_to_live (int) – TTL value

13.8. Ethernet Unit 105 TTA Documentation, Release 1.15.2

• protocol (int) – Identifier for contained protocol • header_checksum (int) – Header Checksum • source_ip (bytes) – Source IP address • dest_ip (bytes) – Destination IP address • options (bytes) – IP options

13.8.9 ICMP

The ICMP class defines ICMP telegrams. Even though it can be used as it is, some more specific objects are available to create different types of ICMP Messages. • ICMPEcho • ICMPDestinationUnreachable • ICMPTimeExceeded • ICMPParameterProblem • ICMPRedirect • ICMPSourceQuench class tta.units.ethernet.ethernet_protocols.ICMP(*args, ip_header=None, type=8, code=0, checksum=0) ICMP base packet Parameters args (bytes) – ICMP message Variables • ip_header (IP) – IP header • type (int) – Type of the ICMP message • code (int) – ICMP code • checksum (int) – ICMP checksum class tta.units.ethernet.ethernet_protocols.ICMPEcho(*args, type=8, id=0, seq=0) ICMP Echo packet Parameters args (bytes) – ICMP message Variables • type (int) – type of the ICMP message • id (int) – ICMP Echo ID • seq (int) – Sequence number class tta.units.ethernet.ethernet_protocols.ICMPDestinationUnreachable(*args, code=0) ICMP Destination Unreachable packet Parameters args (bytes) – ICMP message Variables code (int) – ICMP Code class tta.units.ethernet.ethernet_protocols.ICMPTimeExceeded(*args, code=0) ICMP Time Exceeded packet Parameters args (bytes) – ICMP message

106 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Variables code (int) – ICMP Code class tta.units.ethernet.ethernet_protocols.ICMPParameterProblem(*args, code=0, pointer=0) ICMP Parameter Problem packet Parameters args (bytes) – ICMP message Variables • code (int) – ICMP Code • pointer (int) – Error pointer class tta.units.ethernet.ethernet_protocols.ICMPRedirect(*args, code=0, gate- way_internet_address=0) ICMP Redirect packet Parameters args (bytes) – ICMP message Variables • code (int) – ICMP Code • gateway_internet_address (int) – Gateway address class tta.units.ethernet.ethernet_protocols.ICMPSourceQuench(*args) ICMP Source Quench packet Parameters args (bytes) – ICMP message

13.8.10 ARP

The ARP class defines ARP telegrams. class tta.units.ethernet.ethernet_protocols.ARP(*args, ethernet_header=None, hw_address_type= dpkt.arp.ARP_HRD_ETH, protocol_address_type= dpkt.arp.ARP_PRO_IP, hw_address_length=6, proto- col_address_length=4, opera- tion=dpkt.arp.ARP_OP_REQUEST, sender_hardware_address=b’x00’ * 6, sender_protocol_address=b’x00’ * 4, target_hardware_address=b’x00’ * 6, target_protocol_address=b’x00’ * 4) ARP packet Parameters args (bytes) – ARP message Variables • ethernet_header (Ethernet) – Ethernet header • hw_address_type (int) – Hardware address type • protocol_address_type (int) – Protocol address type • hw_address_length (int) – Hardware address length • protocol_address_length (int) – Protocol_address_length

13.8. Ethernet Unit 107 TTA Documentation, Release 1.15.2

• operation (int) – Operation type • sender_hardware_address (bytes) – Sender hardware address • sender_protocol_address (bytes) – Sender protocol address • target_hardware_address (bytes) – Target hardware address • target_protocol_address (bytes) – Target protocol address

13.8.11 UDP

The UDP class defines UDP telegrams. The src_port and dest_port are specified as integer. class tta.units.ethernet.ethernet_protocols.UDP(*args, ip_header=None, src_port=33333, dest_port=34000, length=8, checksum=0) UDP packet Parameters args (bytes) – UDP message Variables • ip_header (IP) – IP header • src_port (int) – Source port • dest_port (int) – Destination port • length (int) – Length of the UDP message • checksum (int) – Checksum

13.8.12 TCP

The TCP class defines TCP telegrams. The src_port, dest_port, seq_number and ack_number e.g. are here specified as integer. class tta.units.ethernet.ethernet_protocols.TCP(*args, ip_header=None, src_port=33333, dest_port=34000, seq_number=3735928559, ack_number=0, off_res=80, flags=0, window_size=65535, checksum=0, urgent_pointer=0, options=b”) TCP packet Parameters args (bytes) – TCP message Variables • ip_header (IP) – IP header • src_port (int) – Source port • dest_port (int) – Destination port • seq_number (int) – Sequence number • ack_number (int) – Acknowledge number • off_res (int) – Offset and reserved field • offset (int) – Offset only

108 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• flags (int) – TCP flags • window_size (int) – Window size • checksum (int) – Checksum • urgent_pointer (int) – Urgent pointer • options (bytes) – Options parse_options() Parse TCP options, if any

13.8.13 DHCP

The DHCP class defines DHCP telegrams. class tta.units.ethernet.ethernet_protocols.DHCP(*args, udp_header=None, op_code= dpkt.dhcp.DHCP_OP_REQUEST, hardware_addr_type= dpkt.arp.ARP_HRD_ETH, hw_addr_length=6, hops=0, transaction_id=0xdeadbeef, sec- onds=0, flags=0, ciaddr=0, yi- addr=0, siaddr=0, giaddr=0, client_hardware_addr=b"x00" * 16, sname=b"x00" * 64, file=b"x00" * 128, options=b"") DHCP packet Parameters args (bytes) – DHCP message Variables • udp_header (UDP) – UDP header • op_code (int) – operation code • hardware_addr_type (int) – Hardware address type • hw_addr_length (int) – Hardware address length • hops (int) – Hops • transaction_id (int) – Transaction ID • seconds (int) – Seconds since client began address acquisition • flags (int) – Flags • ciaddr (int) – Client IP address • yiaddr (int) – ‘Your’ (client) IP address • siaddr (int) – Server IP address • giaddr (int) – Relay agent IP address • client_hardware_addr (bytes) – Client hardware address • sname (bytes) – Optional server host name • file (bytes) – Boot file name • options (bytes) – DHCP options

13.8. Ethernet Unit 109 TTA Documentation, Release 1.15.2

13.8.14 SomeIP

The SomeIP class defines Some/IP telegrams. class tta.units.ethernet.ethernet_protocols.SomeIP(*args, tp_header=None, service_id=65535, method_id=33024, length=0, client_id=0, session_id=0, protocol_version=1, inter- face_version=1, message_type=0, return_code=0) Some/IP packet Parameters args (bytes) – Some/IP message Variables • tp_header (TCP or UDP) – Transport protocol header • service_id (int) – Service ID • method_id (int) – Method ID • length (int) – Length of the message • client_id (int) – Client ID • session_id (int) – Session ID • protocol_version (int) – Protocol version • interface_version (int) – Interface version • message_type (int) – Message type • return_code (int) – Return code • message_id (int) – Message ID • request_id (int) – Request ID

13.8.15 SomeIPSD

The SomeIPSD class defines Some/IP service discovery telegrams. class tta.units.ethernet.ethernet_protocols.SomeIPSD(*args, tp_header=None, flags=64, reserved=0, len_entries=0, entries=b”, options=b”) Some/IP service discovery packet Parameters args (bytes) – Some/IP SD message Variables • tp_header (TCP or UDP) – Transport protocol header • flags (int) – Some/IP SD flags • reserved (int) – Reserved • len_entries (int) – Length of entries field • entries (bytes) – Service Discovery entries

110 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• len_options (int) – Length of options field • options (bytes) – Service Discovery options add_configuration_option(list_configs) Add a configuration option Parameters list_configs – list of configurations which have to be added. Use nested lists of key, value pairs (bytes) :type list_configs: list add_endpoint_option(ip_address=None, port=None, protocol=17) Add and endpoint option append_entry(sdentry) Append a SD entry parse_entries() Get a list of all SD entries parse_options() Get a list of all options

13.8.16 RawPacket

Packets of this type are not supposed to be used for message creation. This is the standard object which is provided in event queues filled by asynchronous captures. The serialized byte object and the pcap header (including the time stamp) can be directly accessed via attributes of instances of this class. For further analysis those objects provide methods to decode the byte stream into an instance of one of the above protocol classes (or a dpkt object, respectively). It is recommended to provide the protocol to the decode function, if known, otherwise it has to be guessed. class tta.units.ethernet.ethernet_protocols.RawPacket(*args, **kwargs) Raw packet class. Instances of this type are returned by a pcap listener decode(cls_protocol=None, sprotocol=”) Decode the raw packet object into a custom packet protocol object, if available Parameters • cls_protocol (BasePacket) – class used for decoding • sprotocol (str) – name of the protocol used for decoding Returns instance of corresponding custom packet class Return type BasePacket Raises AttributeError – if no matching packet class is found or incorrect protocol given decode_to_dpkt() Decode the raw packet object into a dpkt object get_ts() Get the pcap timestamp for this message stored in the header object

13.9 tta.units.flash

This module represents a TTA unit, providing the functionality for both partial and complete implementations of a flash-cycle, as well as building blocks for programming test cases at a user-friendly high level, using the UDS-protocol.

13.9. tta.units.flash 111 TTA Documentation, Release 1.15.2

The Flash Unit contains classes and functions, built in a way that the tester does not need to have deep knowledge of the UDS-protocol. The Flash-Unit already integrates the PDX/ODX-Unit for the run of a flash cycle. Hence, the tester does not have to interpret the ODX-f file. The tester only needs to provide the path of the PDX-Container, as a parameter to the Unit. However, if the tester wants to use single functions from the flash cycle, a minimum knowledge about the flash process and correlated necessary information from the ODX structure might be needed. For now, the DLL enabling the Seed&Key authorization mechanism for the flash process should also be given as a parameter to the Unit (in the form of a path to the DLL). In the future, the DLL will be directly integrated in the Unit, so the tester does not need to pass it each time. If you want to implement tests at a lower level, or if you want to have more customization opportunities in your test cases, please refer directly to the UDS-Unit.

13.9.1 Flash - Flash unit

13.9.1.1 Flash functions

The flash unit object is associated to a CAN hardware. In order to be able to send UDS-messages, you need to define the hardware_address, the src_address, the ident_base and the ecu_address. The hardware_address might be an IP address (for a bluePiraT or other Telemotive hardware for example), a device serial number (as string) or None (for Vector hardware). The src_address defines the address of the ECU you want to flash on the CAN-bus. The ident_base is the base address of the CAN-Bus, while ecu_address is the address of the ECU to flash. Should a flash function cause a negative answer from the ECU, an exception is raised (at the UDS unit level). Those exceptions can be caught in a try/except block and inspected. All the flash functions return a FlashResult . The interpretation of the UDS answer can be found in the .result while the whole answer can be found in the uds_result. Example • Wake-up signal : Before you can send any UDS message to the ECU, please note that you first need to send a UDS TesterPresent in order to wake-up the ECU. For that:

# Open flash unit flash= Flash("", 0x7E, 0x700, 0x14) # Wake-up signal flash.testerPresent()

• Periodical TesterPresent : If you want to keep the ECU awake or in a session other than the DefaultSession, you will need to send at least one TesterPresent every two seconds. For this a function is already implemented:

# Open flash unit flash= Flash("", 0x7E, 0x700, 0x14) # Keep the ECU awake flash.testerPresentEnable() # Do something with the ECU ... Some code... # Let the ECU go in sleep mode again flash.testerPresentDisable()

• Move to Extended Session :

112 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Move the ECU to Extended Session:

# Open flash unit flash= Flash("", 0x7E, 0x700, 0x14) # Move to Extended Session res= flash.extendedSession()

• Seed and Key behavior : Exchange Seed and Key with the ECU:

# SecurityAccess - RequestSeed seed= flash.requestSeed() # Compute the Key option= PDX("C: \\Path_to_PDX\\pdx.pdx").get_odx().flash.get_single_session().

˓→securitys[0].fw_signature.content # Extracted SA2 value from PDX key= flash.computeKey("C: \\Path_to_DLL\\DLL_for_this_ECU.dll", option, seed.result) # SecurityAccess - SendKey res= flash.sendKey(key)

• Send wrong Key Send the wrong key to the ECU:

# SecurityAccess - SendKey : Send a wrong key res= flash.sendKey([0xFF, 0xFF, 0xFF, 0xFF])

• Send a wrong CRC to check Send the wrong CRC to check to the ECU:

# Check CRC with a wrong CRC res= flash.checkCRC("FFFFFFFF")

• Send the correct CRC to check Send the correct CRC to check to the ECU:

# Extract the CRC value from the PDX, e.g. for an ODX file with only a single session,

˓→ cf. ODX Unit for further details crc= PDX("C: \\Path_to_PDX\\pdx.pdx").get_odx().flash.get_single_session().get_

˓→datablocks()[0].securitys[0].fw_signature.content # Check CRC with the correct CRC res= flash.checkCRC(crc)

class tta.units.flash.Flash(device_id=’192.168.0.233’, channel=0, src_addr=126, ident_base=1792, addressing=0, ecu_addr=20, padding=170) Flash-Unit Parameters • device_id (str) – Identifier of device, can be IP-address, serial number or None • channel (int) – CAN channel • src_addr (int) – Address of the ECU on the CAN-Bus • ident_base (int) – Base address of the CAN-Bus

13.9. tta.units.flash 113 TTA Documentation, Release 1.15.2

• addressing (int) – Address mode (ISOTP.ADDR_BASE=0x00, ISOTP.ADDR_EXTENDED=0x01, ISOTP.ADDR_IDENT=0x02) • ecu_addr (int) – Address of the ECU • padding (int) – Byte value for padding up to full 8 byte frame checkCRC(crc, length=4) Send a UDS RoutineControl - CRC-Check Parameters • crc (int/str) – String form of the hex value of the CRC Checksum (or int) • length (int) – Number of bytes used for CRC (default is 4, 32 bits) Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult checkProgrammingDependencies() Send a UDS RoutineControl - CheckProgrammingDependencies Returns Returns True if all the Programming Dependencies are fulfilled and returns the answer to the UDS Request Return type FlashResult checkProgrammingPreconditions() Send a UDS RoutineControl - CheckProgrammingPreconditions Returns Returns True if all the Programming Preconditions were OK and returns the answer to the UDS Request Return type FlashResult computeKey(dll, security, list_seed) Compute Key Parameters • dll (string) – Path to the dll to be used for the computation of the Key • security (string) – Security string to be given to the dll and contained in the ODX- file • list_seed (list) – Seed as a int(bytes) Returns Result the key as int(bytes) Return type FlashResult Raise tta.core.exception TTADLLError defaultSession() Send a UDS DiagnosticSessionControl - DefaultSession Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult disableFaultSave() Send a UDS ControlDTCSettings - DisableFaultSave

114 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Returns Returns True if all DTCs were correctly deactivated and returns the answer to the UDS Request Return type FlashResult disableNonDiagnosticCommunication() Send a UDS CommunicationControl - DisableNonDiagnosticCommunication Returns Returns True if the non-diagnostic Communication was deactivated and returns the answer to the UDS Request Return type FlashResult enableFaultSave() Send a UDS ControlDTCSettings - EnableFaultSave Returns Returns True if all DTCs were activated and returns the answer to the UDS Request Return type FlashResult enableNonDiagnosticCommunication() Send a UDS CommunicationControl - EnableNonDiagnosticsCommunication Returns Returns True if the non-diagnostic Communication was activated and returns the an- swer to the UDS Request Return type FlashResult eraseMemory(memory_adress) Send a UDS RoutineControl - Erase Memory Parameters memory_adress (int) – memory_adress at which to start to erase Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult extendedSession() Send a UDS DiagnosticSessionControl - Extended Diagnostic Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult hardReset() Send a UDS ECUReset - HardReset Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult programmingSession() Send a UDS DiagnosticSessionControl - ProgrammingSession Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult requestDownload(mem_addr, mem_size, compression_encryption=0) Send a UDS RequestDownload Parameters

13.9. tta.units.flash 115 TTA Documentation, Release 1.15.2

• mem_addr (int) – start address of the data to flash • mem_size (int) – memory size of the data to flash • compression_encryption (int) – highest 4 bits defines the compression method while the lowest 4 bits defines the encryption method Returns Returns the maxLength, maximal size of a data block to be transfered and returns the answer to the UDS Request Return type FlashResult requestSeed() Send a UDS SecurityAccess - RequestSeed Returns Returns the seed as a int(bytes) and the answer to the UDS Request Return type FlashResult sendKey(list_key) Send a UDS SecurityAccess - SendKey Parameters list_key (list) – Key to be sent to the ECU as a int(bytes) Returns Returns True if the Key send was correct and returns the answer to the UDS Request Return type FlashResult testerPresent() Send a UDS TesterPresent in broadcast, with SupprPosResponse bit set Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult testerPresentDisable() Disable the sending of a UDS TesterPresent every 2 seconds testerPresentEnable() Send a UDS TesterPresent each 2 seconds transferData(max_length, path, break_percent=-1) Send UDS TransferData for all the data contained in the path when break_percent = -1. Breaks after break_percent of the flash in case break_percent bigger than 0 Parameters • max_length (int) – max_length of a data block • path (string) – path to the binary data to flash • break_percent (int) – percentage of the transfer after which to stop the transfer if break_percent is set to -1, the transfer continues until the end Returns Returns True if the data transfer was OK and returns the answer to the UDS Request Return type FlashResult transferExit() Send a UDS TransferExit Returns Returns True if the method is correctly executed and returns the answer to the UDS Request Return type FlashResult

116 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

transferSingleData(block_cnt, data) Send a single UDS TransferData with block number block_cnt for the data Parameters • block_cnt (int) – data block number • data (string) – data to transfer to the ECU Returns Returns True if the transfer of the block was OK and returns the answer to the UDS Request Return type FlashResult uploadData(pdx_path, file_id) Upload the file with id = ID, defined in the PDX Data, in the ECU Parameters • pdx_path (string) – path to the pdx-container containing all the relevant details for the flash cycle • id (string) – id of the binary to flash Returns Returns True if the method is correctly executed Return type FlashResult Raise tta.core.exception TTAODXError writeFingerprint(fingerprint=None) Send a UDS WriteDataByIdentifier - LogicalBlockProgrammingFingerprint Parameters fingerprint (list) – int(bytes) of 9 bytes containing the Fingerprint to write. Per default, the fingerprint written is the date + “TELEMO” Returns Returns True if the Fingerprint is correctly written and returns the answer to the UDS Request Return type FlashResult

13.9.1.2 Generic flash functions

All the Flash functions used, are mapped to available standards. If you need to check RoutineControl, Read or Write Data other than the one specified for a typical flash cycle, you need to use the generic functions. Example • RoutineControl : Check the ControlRoutine 0x0002 res= flash.routineControl(0x0002)

• CommunicationControl : Disable the normal communication for AllNetworks Rx and Tx res= flash.communicationControl(UDSType.Communication.DisableRxAndTx, UDSType.

˓→CommunicationNet1.Normal| (UDSType.CommunicationNet2.AllNetworks <<4))

• ReadDataByIdentifier : Read the Data at Identifier 0x0123

13.9. tta.units.flash 117 TTA Documentation, Release 1.15.2

res= flash.readDataByIdentifier(0x0123)

• WriteDataByIdentifier : Write 0x0000 at Identifier 0x0123 res= flash.writeDataByIdentifier(0x0123, 0x0000)

class tta.units.flash.Flash(device_id=’192.168.0.233’, channel=0, src_addr=126, ident_base=1792, addressing=0, ecu_addr=20, padding=170) Flash-Unit Parameters • device_id (str) – Identifier of device, can be IP-address, serial number or None • channel (int) – CAN channel • src_addr (int) – Address of the ECU on the CAN-Bus • ident_base (int) – Base address of the CAN-Bus • addressing (int) – Address mode (ISOTP.ADDR_BASE=0x00, ISOTP.ADDR_EXTENDED=0x01, ISOTP.ADDR_IDENT=0x02) • ecu_addr (int) – Address of the ECU • padding (int) – Byte value for padding up to full 8 byte frame communicationControl(enable_disable, networks) Send a UDS CommunicationControl with as parameter the parameters given in the call Parameters • enable_disable (UDSType.CommunicationControl) – Control type • networks (UDSType.CommunicationNet) – Communication and network type Returns Returns True if the method is correctly called and returns the answer to the UDS Re- quest Return type FlashResult readDataByIdentifier(mem_address) Send a UDS ReadDataByIdentifier with as parameter the parameter given in the call Parameters mem_address (int) – Identifier value (range is 0..65535) Returns Returns the value read as an int(bytes), if the method is correctly called and returns the answer to the UDS Request Return type FlashResult routineControl(routineIdentifier, data=None) Send a UDS RoutineControl with as parameter the parameter given in the call Parameters • routineIdentifier (int) – routine identifier • list – data to give as parameter as an int(bytes) Returns Returns True if all the status of the RoutineControl is OK and returns the answer to the UDS Request

118 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Return type FlashResult securityAccess(access_type, parameter=None) Send a UDS SecurityAccess with as parameter the parameters given in the call Parameters • access_type (UDSType.SecurityAccess) – Access type • parameter (list) – Parameter to give to the UDS Request (i.e. Key) Returns Returns True or an int(bytes) containing the Seed if the method is correctly called and returns the answer to the UDS Request Return type FlashResult writeDataByIdentifier(mem_address, data) Send a UDS WriteDataByIdentifier with as parameter the parameter given in the call Parameters • mem_address (int) – Identifier value (range is 0..65535) • data (list) – int(bytes) to write in the memory Returns Returns True if the method is correctly called and returns the answer to the UDS Re- quest Return type FlashResult

13.9.2 FlashResult

All functions contained in the flash unit return a FlashResult object. This object carries a ‘result’ attribute representing an interpreted result of the answer, returned from the UDS Service and a ‘uds_result’ attribute, which is the raw data received from the ECU. This structure is built, in order to enable two-level debugging : the test-developer might want to focus on the pure result of each UDS Service (using only the ‘result’ attribute), during implementation of the test cases, whereas the ‘uds_result’ is intended for debugging or trace analysis. Example: • ReadDataByIdentifier Read the Data at Identifier 0x0123 res= flash.readDataByIdentifier(0x0123) >>> ECU returned the UDS Message : 0x22 0x01 0x23 0x01 0x01 # Print the status of the UDS Request print(res.result) >>> 257 # Get the raw data returned from the ECU : print(res.uds_result) >>>[0x22, 0x01, 0x23, 0x01, 0x01]

class tta.units.flash.FlashResult(result, uds_result=None) Class for result of flash function Parameters • result (bool/list) – If True or value of type int(bytes), function call was successful

13.9. tta.units.flash 119 TTA Documentation, Release 1.15.2

• uds_result (obj) – Result from UDS request

13.10 tta.units.ftp

This module provides a file transport (FTP) unit for transferring files, using the most common “FTP” protocols: • FTP • FTPS (FTP via SSL) • SFTP (FTP via SSH(Secure Shell)) (not implemented yet) It contains typical functions for navigating through the directories of remote file systems, transferring files from local to remote file systems and vice-versa.

13.10.1 FTP - FTP unit

To open a connection, instantiate a FTP unit and provide the host name or the IP address. If you want to connect as guest to FTP or FTPS servers, you can use “ftp” or “anonymous” as user names. In case the server listens on another port than 21, the port can be changed with argument “port”. Example: An FTP server is running on a host with name “ftp.site.org” and with the IP address 192.168.15.100: ft= FTP(FTP.FTP,"ftp.site.org","ftp") # guest login ft= FTP(FTP.FTP,"192.168.15.100","ftp") # guest login # or login "myname" with password "mypass" ft= FTP(FTP.FTPS,"my.site.org","myname","mypass")

Instead of transferring files from a remote to a local file system, or the other way around, the two functions get_data() and put_data() can be used to get or put data directly into remote files: data= ft.get_data("/etc/vsftpd.conf") ft.put_data("/etc/vsftpd.conf.saved", data)

class tta.units.ftp.FTP(driver=None, host=None, user=None, passw=None, port=21) The FTP unit provides file transfer functions. It supports FTP, FTPS(FTP via SSL) and SFTP(FTP via SSH). Parameters • host (str) – Host name or IP address to connect to • user (str) – User name • passw (str) – Password • port (int) – TCP port to connect to get_data(remotepath) Read data directly from file and return it Parameters remotepath (str) – Path to remote file Returns Data of file read in binary mode Return type bytes

120 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

get_file(remotepath, localpath) Transport file from remote path to local path Parameters • remotepath (str) – Path to remote file • localpath (str) – Path to local file list_dir(remotepath=’.’) List directory contents of remote path Parameters remotepath (str) – Path to remote file put_data(remotepath, data) Write data directly to file in remote path Parameters • remotepath (str) – Path to remote file • data (bytes) – Binary data to write into file put_file(localpath, remotepath) Transport file from local path to remote path Parameters • localpath (str) – Path to local file • remotepath (str) – Path to remote file rm_file(remotepath) Remove file at remotepath (only file, not directory) Parameters remotepath (str) – Path to remote file

13.11 tta.units.imagegrabber.imagegrabber

This module provides the ImageGrabber unit and appropriate driver implementations.

13.11.1 ImageGrabber - image grabber unit

The ImageGrabber unit provides an interface to different image grabbing devices. Devices usually can be identified by either a serial number or an IP address in the network. Example: Initialize a Ruetz frame grabber and use special parameter uiDataEnable, then show image on screen: grabber= ImageGrabber("DriverRuetz", uiDataEnable=1) img= grabber.get_image() img.show()

13.11.2 Drivers

Currently the following drivers are available:

13.11. tta.units.imagegrabber.imagegrabber 121 TTA Documentation, Release 1.15.2

• DriverEpiphan Driver for Epiphan frame grabbers. This driver supports video capture. • DriverRuetz Driver for Ruetz frame grabbers. There are special parameters available you can pass to the driver library directly: uiImgHeight, uiImgWidth, uiOffsetX, uiOffsetY, uiGrabOnlySecondPixel, uiGrabOnlySecondLine, uiDataEnable, uiDualView. About the meaning of the different parameters please consult the manual of the Ruetz frame grabber or contact the manufacturer. • DriverADBCam Driver for ADB (Android Debug Bridge) devices like smart phones, tablets etc. The Driver does activate the camera application and takes a picture which is then returned. • DriverDummy Dummy driver for testing purposes.

ImageGrabber unit, provides interface to image grabber devices. class tta.units.imagegrabber.imagegrabber.ImageGrabber(driver=None, de- vice_identifier=None, resolution_width=None, resolution_height=None, **kwargs) The ImageGrabber unit can be used to get images from image grabber devices. Drivers: DriverEpiphan, DriverRuetz, DriverADBCam, DriverDummy. DriverRuetz special parameters (define as keyword argument on init): uiImgHeight, uiImgWidth, uiOffsetX, uiOffsetY, uiGrabOnlySecondPixel, uiGrabOnlySecondLine, uiDataEnable, uiDualView. Parameters • driver (str) – Specifies the image grabber device driver to use • device_identifier (any) – Specifies which image grabber device to use (e.g. serial number - depends on driver) • resolution_width (int) – Width of images to grab • resolution_height (int) – Height of images to grab get_image() Grab an image. :rtype: Image start_video(name=’video.avi’, crop=None, max_fps=None) Start video grabbing Parameters • name (str) – Name of AVI video file to save the images to • crop (tuple) – Crop region, defined by tuple (x, y, width, height) • max_fps (int) – Maximal FPS rate (frames per second) stop_video() Stop video grabbing and write to AVI file

122 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.12 tta.units.imageprocessing.animation

This module provides a TTA unit interface to analyze and compare short videos to determine if a certain animation was displayed correctly. Among other things it allows you to search for the first appearance of a particular frame, compare two similar video files frame by frame or search for the best match of a given reference in a video file. Features: • Compare two video frame by frame • Search given frame in video • Return frame at timestamp • Create graphics for the reporting

13.12.1 How to use the ImageprocessingAnimation unit

13.12.1.1 Importing and comparing videos

After initializing the ImageProcessingAnimation unit you can extract all frames into a given folder by calling the import_video() function. This step will be needed for later comparison:

from tta.units.imageprocessing import animation

ip= animation.ImageProcessingAnimation() ip.import_video("PATH TO VIDEO","OUTPUT FOLDER")

Now that we have all the frames from both our videos we can simply compare them by calling the compare_video function, this will return several metrics which can be used to determine the similarity between the individual frames. If you want to calculate and save the difference frames you can also set calc_diff=True:

mse,ssim,psnr= ip.compare_video("PATH TO VIDEO 1","PATH TO VIDEO 2") print(mse[15]) # Prints out calculated MSE value for frame 14

After we have received the calculated values we can now test if the average error is below a certain threshold like so:

self.assertLess(np.average(mse),1000) self.assertGreater(np.average(ssim),0.9) self.assertLess(np.average(psnr),30)

We can also plot these values with MatPlotLib and add the image to our report:

img= ip.plot(mse, ssim, psnr) # Create Plot self.current_step_result.add_image("plot", img) # Add to report

Here is an example what the plotted image will look like, here the x-Axis is a timeline showing the number of the frame whereas the y-Axis represents the related metric written above.

13.12.1.2 Searching specific frames

The ImageProcessingAnimation unit currently provides two ways of searching for specific frames in a video, either by reference or by timestamp. Search by timestamp

13.12. tta.units.imageprocessing.animation 123 TTA Documentation, Release 1.15.2

Fig. 1: Example plot comparing two videos.

For this step we only need the path to the video we want to search our frame in alongside our timestamp in ms. In this example we will receive the frame displayed at 1.5s: ip= animation.ImageProcessingAnimation() img= ip.get_frame_at_timestamp(self.target_video.value, 1500)

Search by reference (First Appearence) For this search we will first need to call import_video() to extract all individual frames from our target video. After that is finished we are able to search for the first frame in the received folder that matches with our reference. Here we are able to determine a threshold, for example a threshold of 0.015 means that at most 1.5% of the total pixels are allowed to be different for it to still count as a match: ip= animation.ImageProcessingAnimation() img= Image.open("PATH TO REFERENCE IMAGE") score, diff_img, frame= ip.search_match(img,"PATH TO VIDEO FRAMES", 0.015)

Search by reference (All Appearences) To search for all images that match over your threshold you can use ip.search_all_matches() instead.

13.12.1.3 Other Functions

Get Timestamp of Frame If you need to know the timestamp (in ms) for a given Frame you can use the function get_timestamp(FRAME, VIDEOPATH). You can either use the filename “frame50.jpg” or the number of the frame you want the timestamp for. Export Video Once you have a folder full of Diff-Images you can use the export_video() function to turn your output into a video file. Get First Frame The method get_first_frame() returns the first non-black frame of a given video, this might be usefull to determine the offset between your target and reference video for comparison purposes.

13.12.2 Comparison Algorithms

The metrics used for comparison are:

124 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• MSE (Mean Squared Error) One obvious way of measuring this similarity is to compute an error signal by subtracting the test signal from the reference, and then computing the average energy of the error signal. The mean-squared-error (MSE) is the simplest, and the most widely used, full-reference image quality measurement. This metric is frequently used in signal processing and is defined as follows:

Fig. 2: MSE equation.

• PSNR (Peak Signal to Noise Ratio) The PSNR is evaluated in decibels and is inversely proportional the Mean Squared Error. It is given by the equation:

Fig. 3: PSNR equation.

• SSIM (Structural Similarity Index Metric) The SSIM is the best method to evaluate image quality and the SSIM is given by the equation below:

Fig. 4: SSIM equation.

Generally SSIM is regarded as the best comparison algorithm out of these three as it aims to represent human percep- tion insted of pure mathematical comparison like MSE and PSNR. The best way to determine similarity of two videos is likely to calculate all three values and set a threshold for each one. Here is an example how these metrics change with different input images, in this graph it is always compared against the original image. ImageProcessingAnimation

13.12. tta.units.imageprocessing.animation 125 TTA Documentation, Release 1.15.2

Fig. 5: Sample values for image comparison.

126 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2 class tta.units.imageprocessing.animation.ImageProcessingAnimation(target_path=’./’) ImageProcessessing Unit Verifies and compares images/videos to see if they match reference images Init Function Parameters string – target_path where videos are stored compare_video(reference_video, target_video, offset=0, calc_diff=False) Compare given video with reference video Parameters • string – path to video to compare against • string – path to actual video • offset (int) – offset of frames from reference to target for comparison • calc_diff (bool) – if true difference images are calculated and written to thresh folder export_video(path, width, height) Takes a folder of singular frames and exports them into a video-file. Parameters • string – path to given file • int – width of the video • int – height of the video get_first_frame(video) Get first non black frame Parameters string – path to folder with video frames Returns name of first frame that is not completely black get_frame_at_timestamp(video_path, timestamp) Get frame at a certain timestamp Parameters • string – path to the video • int – timestamp in ms • int – framerate of the video get_timestamp(frame, video) Get Timestamp for given frame Parameters • frame (int/str) – Number or name of the frame (50 or “frame50.jpg”) • video (str) – Path to the videofile import_video(video, output_path=”) Saves video frame by frame to a target location ./video/ this is used for furter operations Parameters • string – path to the given video • string – path to save frames to classmethod plot(mse, ssim, psnr) Plots MSE, SSIM & PSNR values with matplotlib

13.12. tta.units.imageprocessing.animation 127 TTA Documentation, Release 1.15.2

Parameters • np_array – Array with MSE values per frame • np_array – Array with SSIM values per frame • np_array – Array with PSNR values per frame search_all_matches(original, video_path, threshold=0.1) Search best match for given image Parameters • Image (PIL) – image to search • str – path to folder with video frames search_match(original, video_path, threshold=0.1) Search best match for given image Parameters • Image (PIL) – image to search • str – path to folder with video frames

13.13 tta.units.imageprocessing.warping

The module contains functions to support grid shaped warping of CV2 images and additionally provides some helpers for extrapolation and grid ordering.

13.13.1 ImageProcessingWarping - Warping unit

The unit only supports “grid-based” warping currently. Example: Open the unit:

from tta.units.imageprocessing.warping import ImageProcessingWarping ipw= ImageProcessingWarping()

To use the warping function, just provide source and destination point definitions as lists and a CV2 image file (numpy.ndarray). Both lists, src_points and dst_points must have the same length and contain point definitions. Every point is a tuple containing x and y coordinates. As CV2 operates on image pixel coordinates only, x and y refer to pixel positions. Float values for subpixel positions are allowed. Define points, load image and warp:

src_points=[(0,0), (10,0), (0, 10), (10, 10)] dst_points=[(1,1), (9,1), (1,9), (9,9)] orig_im= cv2.imread("orig.bmp") # provide image of size 10x10 warped_im= ipw.grid_warp(orig_im, src_points, dst_points, (10, 10))

If you want to use extrapolation because the image you want to warp is bigger than the grid definition provided, just give shape and grid ordering:

128 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

src_points=[(100, 100), (110, 100), (100, 110), (110, 110)] dst_points=[(101, 101), (109, 101), (101, 109), (109, 109)] orig_im= cv2.imread("orig.bmp") # provide image of e. g. size 200x200 warped_im= ipw.grid_warp(orig_im, src_points, dst_points, (200, 200), extrap= True,

˓→grid_shape=(2,2), grid_order="row")

class tta.units.imageprocessing.warping.ImageProcessingWarping(mode=’grid- based’) ImageProcessingWarping Unit Helps with warp transformations of following grid point definitions. Offers extrapolation if warping should also be applied to bigger surrounding image. Init Function Parameters mode (str) – Warping method to use, currently only “grid-based” is supported extrap_next(points) Extrapolate next neighbors at start/end of point sequence, in respect to their distances. Parameters points (list) – List of point coordinates ((x, y) tuples/lists) Returns Extrapolated points at start and end: (point_before_start, point_after_end) Return type tuple grid_extrap_frame(points, width, height) Extrapolate frame for rectangular grid, width and height needed, order must be row-major Parameters • points (list) – List of point coordinates ((x, y) tuples/lists) • width (int) – Number of columns • height (int) – Number of rows Returns Return frame points Return type list classmethod grid_reorder(points, width, height, kind=’column2row’) Resort grid points, either column-major to row-major or vice-versa. Parameters • points (list) – List of point coordinates ((x, y) tuples/lists) • width (int) – Number of columns • height (int) – Number of rows • kind (str) – Kind of reordering “column2row” or “row2column” Returns Reordered list of points Return type list grid_warp(image, src_points, dest_points, area, extrap=None, grid_shape=None, grid_order=None) Warp full image following grid points. If extrapolation is needed, arguments grid_shape and grid_order must be provided, which then are used to extrapolate a point frame around source and destination grids. Default grid order is row-major, thus column-major will be reordered.

13.13. tta.units.imageprocessing.warping 129 TTA Documentation, Release 1.15.2

Parameters • image (numpy.ndarray) – CV2 image as numpy array • src_points (list) – List of point coordinates ((x, y) tuples/lists): unwarped points • dest_points (list) – List of point coordinates ((x, y) tuples/lists): warped points • area (list) – List/tuple of area to warp (e. g. image size (width, height)) • extrap (bool) – If True, add extrapolated frame to grid point definitions • grid_shape (tuple) – Shape of grid (number of points in x, number of points in y) • grid_order (str) – Either “column”(column-major order) or “row”(row-major order) Returns Warped image (CV2 format) Return type numpy.ndarray

13.14 tta.units.isotp.isotp

ISO-TP Unit (ISO 15765-2) class tta.units.isotp.isotp.ISOTP(device_id=’192.168.0.233’, channel=0, src_addr=247, ident_base=1536, addressing=1, padding=None, vir- tual=False) ISO-TP Unit (ISO 15765-2) Send and receive messages via CAN according to ISO transport protocol. Parameters • device_id (str) – Identifier of device, can be IP-address, serial number or None • channel (int) – CAN channel • src_addr (int) – ECU address used for sender • padding (int) – Byte value for padding up to full 8 byte frame • addressing (int) – Address mode (ADDR_BASE=0x00, ADDR_EXTENDED=0x01, ADDR_IDENT=0x02) • padding – Byte value for padding up to full 8 byte frame • _virtual (bool) – If True, Unit starts in virtual mode (no driver attached, developer only) request(dst_addr, msg, suppr_pos_response=False) Handle diagnosis request and collect reply data Parameters • dst_addr (int) – ECU address of destination(target) device • msg (list) – List of int(bytes) to send Returns List of int(bytes) containing reply data Return type list

130 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.15 tta.units.multimeter

This module provides a TTA interface to various multimeters. It contains driver classes, which implement functionality for different multimeter types. A multimeter typically provides multiple functions, such as measuring voltage, current, resistance, frequency, temperature etc. Some multimeters can communicate with a computer, using a serial or a USB interface. The basic function of the multimeter unit interface is to receive measurement data, convert to a decimal format and display it to the user. Some multimeters can also be controlled remotely. The multimeter unit can later be expanded to include such capabilities. This version of the unit supports the Voltcraft VC-820 and VC-830 multimeter. class tta.units.multimeter.Multimeter(dmmtype=None, port=None) Class created to access data from and send commands to a multimeter. Initializes the multimeter unit. Parameters • dmmtype (str) – Selects a specific multimeter. • port (str) – Selects the COM port for the serial connection. get_display() Get the current display readout. get_status() Get the current measurement modes, range, etc- set_mode(dmm_mode=’V’, ac_dc=’DC’) Set the measurement mode (Multimeter dependent - Will be implemented when required) Parameters • dmm_mode (str) – Select the measurement mode (V, A, Ohm, Hz) • ac_dc (str) – Select AC or DC. set_range(dmm_range=’AUTO’) Set the measurement range (Multimeter dependent - Will be implemented when required) Parameters range (int) – Measurement range of the multimeter.

13.15.1 Initializing the unit

To access data from a multimeter, an object of the Multimeter class is created and initialized with the driver and name of the COM Port as parameters. Example An object of the Multimeter class is created with the Voltcraft VC820 connected at port COM1: dmm= Multimeter(Multimeter.VC820,"COM1")

13.15.2 Physical Quantities

The pint package for physical quantities has been integrated with the multimeter unit. This is used to return measured values with a physical unit. Unit register contain various physical units such as ampere, volt, farad, Hz, etc. It also contains built-in exceptions for those cases, when arithmetic operations are performed on quantities with different units.

13.15. tta.units.multimeter 131 TTA Documentation, Release 1.15.2

Example A unit registry is created during initialization of a multimeter unit. :: ureg = pint.UnitRegistry() Example A physical quantity is created with the measured value and the unit :: volts = value * ureg.V amps = value * ureg.A

13.15.3 Reading data

Reading and displaying data is done with the read function. Bytes are read from the serial port and stored in a buffer. This is a private function of the VC820 class.

13.15.4 Displaying data

The get_display data is used to display the measured data. The function returns a quantity object Example: while 1: logger.info(dmm.get_display())

13.15.5 Setting measurement mode

Some multimeters allow remote control of their measurement settings. This functionality is enabled with set_mode. The function and corresponding examples will be written as a later expansion.

13.16 tta.units.ocr.ocr

13.16.1 OCR Unit

The OCR (optical character recognition) unit provides an interface to interact with different OCR back ends. Currently supported are tesseract and OneNote. • tesseract To use the full functionality of tesseract additional packages might be needed, such as language packages or custom configurations. • OneNote This uses OneNote® from Microsoft Office®. The latter has to be installed to use it. Take care to download needed language packs (Microsoft Office® setup) also. Otherwise those languages will not be available. We recommend to use image preprocessing if the characters are not correctly recognized on an image.

13.16.2 Initializing the unit

The unit can be initialized with the chosen language, this needs a corresponding language package which can be found here for tesseract: https://github.com/tesseract-ocr/tesseract/wiki/Data-Files. For OneNote® refer to the Microsoft Office® setup and install packages which are offered there.

132 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

If you have installed tesseract on your system already, you can use it by setting the path to your installation in the TTA Settings (parameter “install_dir”). Regarding the language parameter, notice that the values will be different for each back end. For tesseract use the short name of the language pack: this is the prefix before “.traineddata” (e. g. “eng” or “deu” or “chi_sim” (simplified chinese)). Whereas for OneNote you have to refer to a ISO 639-1 code like “en_US” or “de_DE” (you can find allowed codes in the dict windows_locale in the Python package locale). Example:

# Init OCR for tesseract back end from tta.units.ocr import OCR ocr= OCR(language="deu") # Default is eng, driver default is "DriverTesseract"/OCR.

˓→Tesseract

# Init OCR for OneNote back end from tta.units.ocr import OCR ocr= OCR(driver=OCR.OneNote, language="de_DE"

If you are unsure of which tesseract version you are currently running, or rather which one is used by TTA you can use the following function. This will return the version of the back end generally: ocr.get_version()

Note: The OneNote back end uses the COM interface. Intialization of this interface is done in respect to the Windows registry. Often there is a wrong key saved for OneNote, which will lead to an exception on intializing this interface. The driver will try to delete the wrong key, but if you do not have the appropriate permissions it will fail. In this case you should get those permissions or delete the key manually: HKEY_CLASSES_ROOT\TypeLib\{0EA692EE- BB50-4E3C-AEF0-356D91732725}\1.0

13.16.3 Recognize Functionality

To recognize text the recognize() function can be used as follows: ocr.recognize(image) # This will return the text found in image

This function can also be parameterized to get more sophisticated output (example for tesseract, for the OneNote driver there are no additional parameters supported yet): ocr.recognize(image, mode=3, output="hocr", config={"tosp_min_sane_kn_sp":4})

For example here we are getting a full HOCR (xml based) representation instead of just text. Through the config parameter as well as the mode (for further details see tesseract segmentation modes below) used we are able to adjust the way that tesseract works and recognizes the text. If your previous results are not desirable you might want to look into these possibilities. If you want a list of notable tesseract parameters you can simply call the following function which will print out all available parameters that can be used inside the config: ocr.get_parameters()

13.16.4 Bounding Boxes and Color Representation with tesseract

To use bounding boxes you first need to get the HOCR representation as shown in the previous step. This will give you a HOCR class object that can access the bounding boxes. To do this simply use the function get_bounding_box()

13.16. tta.units.ocr.ocr 133 TTA Documentation, Release 1.15.2

and you get a dictionary with all detected words alongside their bounding boxes. Once you received the bounding boxes you can then call get_colors() on the HOCR object, this takes the picture and crops it according to all previously found bounding boxes to assess the colors used within them and returns them in the same dict you received before. Example:

hocr= ocr.recognize(image, output="hocr", config={"tosp_min_sane_kn_sp":4}) hocr.get_bounding_box() colors= hocr.get_colors()

If you only want to received the most common colorcodes you can do that by calling get_colors(filter=3) to filter for the top three results for each bounding box.

13.16.5 Tesseract segmentation modes

Page segmentation modes

0 Orientation and script detection (OSD) only. 1 Automatic page segmentation with OSD. 2 Automatic page segmentation, but no OSD, or OCR. 3 Fully automatic page segmentation, but no OSD. (Default) 4 Assume a single column of text of variable sizes. 5 Assume a single uniform block of vertically aligned text. 6 Assume a single uniform block of text. 7 Treat the image as a single text line. 8 Treat the image as a single word. 9 Treat the image as a single word in a circle. 10 Treat the image as a single character. 11 Sparse text. Find as much text as possible in no particular order. 12 Sparse text with OSD. 13 Raw line. Treat the image as a single text line, bypassing hacks that are tesseract-specific.

13.16.6 Optional Config Options for tesseract

https://github.com/tesseract-ocr/tesseract/tree/master/tessdata

13.16.7 Unit Reference

OCR Unit for basic OCR functionality class tta.units.ocr.ocr.OCR(driver=’DriverTesseract’, language=None, install_dir=None, tesserdir=None) The OCR unit can use Tesseract (https://github.com/tesseract-ocr) or OneNote (Microsoft Office) to recognize text on images. (Installation of third party software may be needed.) Parameters • language (str) – Language definition (see language codes for back end, e. g. “eng”, “deu” for tesseract “en_US”, “de_DE” for OneNote) • install_dir (str) – If not None, path to back end installation • tesserdir (str) – Deprecated, use install_dir instead

134 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

get_parameters() Returns a list of config parameters get_tesseract_parameters() Deprecated: use get_parameters get_tesseract_version() Deprecated: use get_version get_version() Returns the backend version Returns Version Return type str recognize(image, mode=3, output=’text’, **kwargs) Recognize text (from PIL Image or from file) Parameters • image (PIL.Image) – Image to recognize text from or path (str) to image • mode (int) – Int Specifies which mode is used by back end • output (str) – String that specifies the output type either “text” or “hocr” • kwargs (dict) – Path or config as dict, e. g. {“path”: “C:/my_path”} or {“config”: {“tosp_min_sane_kn_sp”: 4}} Returns List of recognized lines Return type list

13.17 tta.units.odx

The ODX (Open Diagnostic Data Exchange) unit provides functions, to access PDX-containers and its ODX-F defi- nition files. Those containers and files can be used to access necessary information about the flash process for a given software container and the flash data itself. As the unit is intended to be used for extraction of flash information, this module provides read-only methods, for both PDX and ODX classes. It is not possible to create PDX containers, or even fully ISO compliant ODX files.

13.17.1 PDX - PDX unit

The main purpose of the PDX unit is to provide a method, to extract the contained ODX-F file(s) and the corresponding binary data files, necessary for a flash process. When retrieving an ODX object from a PDX container, the archived file is parsed and an instance of the ODX Class is returned. The file itself remains archived in the container, it is not locally extracted. The PDX class is a subclass of the Zip-file class in the Python module zip-file and hence, all available methods for zip file inspection and local extraction can be used. Example: Create an instance of the PDX class, by providing a path to a pdx container, get odx files and an instance of the odx class, then extract files from the container:

13.17. tta.units.odx 135 TTA Documentation, Release 1.15.2

# create an instance pdx= PDX("pdx_container_path")

# get a list of contained odx file names, containing a desired substring lodxfiles= pdx.get_odx_files("-f","HW1")

# get an odx object by file name lodxfiles= pdx.get_odx_files("HW1_compressed.odx-f")

# get the only available .odx-f file in the PDX container oodx= pdx.get_odx_files() # CAUTION: Returns None if 0 or more than 1 .odx-f

˓→available

# extract a file by name to current working directory pdx.extract("odxfile.odx-f")

class tta.units.odx.PDX(pdxfile) Class for PDX containers Initialize the PDX object Parameters pdxfile (str) – full os path of the pdx container get_odx(sfilename=”) Get an odx file content as ODX object. If no file name is given, the single available odx-f file is returned. Parameters sfilename (str) – name of the odx file Returns ODX Return type ODX get_odx_files(odxtype=’-f’, contains_name=”) Get a list of odx-file names Parameters • odxtype (str) – Type of the odx file (e.g. ‘-f’) • contains_name (str) – Substring to be contained in the searched odx files Returns ODX Return type ODX

13.17.2 ODX - ODX unit

This unit provides easy access to the XML data in ODX files. The XML elements are stored in an ODX object, maintaining the structure of the XML tree in a Python name space.

13.17.2.1 Attribute access

XML attributes and texts are stored as attributes of the corresponding Python objects. The type of those attributes remains unchanged, compared to their analogies in XML, meaning those attributes will always be of type ‘string’, regardless of what type its value actually represents (e. g. integer, bytes, etc. . . ). Text content can be accessed via the attribute ‘content’ of an ODX object, or by applying the string operator str() to it. Each Python object additionally stores the XML tree of its content as an lxml etree.Element attribute called ‘xml’.

136 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

For reasons of clarity, the object and attribute names are identical to the ones used in the XML tree, except that they are all in lower case and that dashes/hyphens are replaced by underscores. Example: Access objects, attributes and texts of the XML tree in an ODX file: ODX example:

FL FLASH

Python access: from lxml import etree # just for printing

# access odx model version smodel= odx.model_version

# access the short name of flash sname= odx.flash.short_name.content # using the 'content' attribute print(odx.flash.short_name) # applying the string operator

# print the lxml etree element object as string print(etree.tostring(odx.xml))

ODX objects which may have several instances of a type in the same name space are stored as a list attribute (main- taining the order of occurrence in the XML tree). The list attribute’s name is identical to the one of the sole attribute, but with a plural ‘s’ at the end (compliant with the naming convention in ODX). ODX example:

FL FLASH EM ECUMEM SES SESS

Python access:

13.17. tta.units.odx 137 TTA Documentation, Release 1.15.2

# access session id session_id= odx.flash.ecu_mems[0].mem.sessions[0].id

13.17.2.2 ODX Links

In case that an ODX element has internal reference(s) to other ODX elements, those link elements are stored in a list attribute called ‘odxlinks’. ODX links, within the same document, can be directly accessed, by calling the get() method of the corresponding object. The returned object is the referenced element of that link. Some ODX objects, which are expected to have those odx links, additionally come with a convenience method, to directly access those referenced elements. ODX example:

FL FLASH EM ECUMEM SES SESS DB DBLOCK FD FDATA

138 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Python access:

# list of odxlinks in session llinks= odx.flash.ecu_mems[0].mem.sessions[0].odxlinks

# get first session link by get() method first_datablock= llinks[0].get()

# get referenced data blocks by convenience method dblocks= odx.flash.ecu_mems[0].mem.sessions[0].get_datablocks()

# get flash data for given data block by convenience method for datablock in dblocks: print(datablock.get_flashdata().short_name)

13.17.2.3 Flash order and access

For flash processes as a whole, according to ISO/PRE-FDIS 22901-1:2008(E), it is recommended to start with selecting a session description by name (and the part’s number if desired), which in turn references a session with necessary flash details, from ECU-MEM-CONNECTORS. The order of the data to be flashed is then given by the order of the referenced data blocks in the given session. For the first steps, there are some more convenient methods, which could be used for that purpose. Example flash data access:

# get session descriptions in ecu-mem-connectors lsess_descs= odx.flash.get_session_descs() # choose your session then from this list session= lsess_descs[0] # if you want the first listed session, otherwise check

˓→(short) names

# if you are sure that your odx files will only have one session session= odx.flash.get_single_session() # raises an AttributeError if 0 or more

˓→than 1 session description available

# get datablocks in correct flash order for dblock in session.get_datablocks(): fdata= dblock.get_flashdata()

13.17.2.4 ODX flash objects

This package contains ODX and PDX units. class tta.units.odx.DiagLayerContainer(xmlnode, ancestors=None) A diagnose layer container This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.ComParamSpec(xmlnode, ancestors=None) Communication parameter specification This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object

13.17. tta.units.odx 139 TTA Documentation, Release 1.15.2 class tta.units.odx.ComParamSubset(xmlnode, ancestors=None) Communication parameter subset This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.MultipleEcuJobSpec(xmlnode, ancestors=None) Multiple ECU job specification This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.VehicleInfoSpec(xmlnode, ancestors=None) Vehicle information specification This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.EcuConfig(xmlnode, ancestors=None) ECU configuration This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.FunctionDictionary(xmlnode, ancestors=None) Function dictionary This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Flash(xmlnode, ancestors=None) Flash object This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object get_session_descs() Get a list of all available session descs Returns list of SessionDesc objects Return type list get_single_session() Get the single session which is referenced by the single session desc available Returns Session object Return type Session Raises AttributeError – if number of available session descs is not one class tta.units.odx.CompanyData(xmlnode, ancestors=None) Contains company data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.AdminData(xmlnode, ancestors=None) Contains admin data

140 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.SDG(xmlnode, ancestors=None) Contains special data group info This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.SDGCaption(xmlnode, ancestors=None) Contains special data group caption info This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Desc(xmlnode, ancestors=None) Contains some description This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.ODXLink(xmlnode, ancestors=None) base class for odx links This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object get() Get the object which is referenced by this link Returns ODX Return type ODX Raises TypeError – if the referenced odx type in unknown class tta.units.odx.EcuMem(xmlnode, ancestors=None) Contains company data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.EcuMemConnector(xmlnode, ancestors=None) Contains company data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Session(xmlnode, ancestors=None) This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object get_datablock(index) Get the datablock with index i for this session in listed order Returns DataBlock objects Return type DataBlock

13.17. tta.units.odx 141 TTA Documentation, Release 1.15.2

get_datablocks() Get all referenced datablocks for this session in listed order Returns list of all referenced DataBlock objects Return type list class tta.units.odx.DataBlock(xmlnode, ancestors=None) Data blocks This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object get_flashdata() Get the flash data (object) referenced in this data block Returns referenced FlashData object Return type FlashData class tta.units.odx.FlashData(xmlnode, ancestors=None) Flash data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Checksum(xmlnode, ancestors=None) This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.ExpectedIdent(xmlnode, ancestors=None) Expected Ident This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Security(xmlnode, ancestors=None) This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.FlashClass(xmlnode, ancestors=None) Flash class information This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.SessionDesc(xmlnode, ancestors=None) Contains session information This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object get_session() Get the session referenced by this session desc Returns referenced Session object Return type Session

142 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

class tta.units.odx.IdentDesc(xmlnode, ancestors=None) Contains identifier information This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.PhysMem(xmlnode, ancestors=None) Contains physical memory data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Mem(xmlnode, ancestors=None) Contains memory data This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.TargetAddrOffset(xmlnode, ancestors=None) Target address Offset This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.OwnIdent(xmlnode, ancestors=None) Own ident This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Segment(xmlnode, ancestors=None) This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.Filter(xmlnode, ancestors=None) This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object class tta.units.odx.ChecksumResult(xmlnode, ancestors=None) Checksum result This object is instantiated when the corresponding element is found while parsing an ODX file NOTE: Please do not manually create this object

13.18 tta.units.pcap.pcap

Created on 03.07.2017 class tta.units.pcap.pcap.Capture(cap_handle, fcallback, ilimit=-1, user_def=None, unit_log=None) threaded capture object run() Start a capture with given handle and callback

13.18. tta.units.pcap.pcap 143 TTA Documentation, Release 1.15.2 class tta.units.pcap.pcap.PacketCapture(capture_handle, ilimit=-1, cus- tom_callback=None, custom_param=None, eth_unit=None) Capture Unit. NOTE: Direct usage is not intended. Unit instances are returned by the start_capture method of NetworkAdapter instances in the ethernet unit. capture() Start a capture with given handle. Captured packets are forwarded to the unit’s event queue capture_result Get the capture result is_capturing() Check if this capture is already/still running join_capture(timeout=None) Join the capture thread (pcap loop)

13.19 tta.units.powersupply.powersupply

Module for PowerSupply unit and related functions class tta.units.powersupply.powersupply.PowerSupply(driver=None, port=None) The PowerSupply unit provides functions for accessing (programmable) power supply devices. Parameters • driver (str) – Specifies the power supply device driver to use • port (str) – Serial com port to connect to get_actual_current() Get actual (measured) current Returns Actual current in ampere Rtyoe float get_actual_power() Get actual (measured) power Returns Actual power in watt Return type float get_actual_voltage() Get actual (measured) voltage Returns Actual voltage in volt Return type float get_current() Get target current set Returns Current in ampere Return type float get_max_current() Get maximal current value measured Returns Maximal current value measured in ampere

144 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Return type float get_max_voltage() Get maximal voltage value measured Returns Maximal voltage value measured in volt Return type float get_min_current() Get minimal current value measured Returns Minimum current value measured in ampere Return type float get_min_voltage() Get minimal voltage value measured Returns Minimum voltage value measured in volt Return type float get_output() Get output state Returns True, if output is “on”, False otherwise Return type bool get_power() Get target power set Returns Power in watt Return type float get_voltage() Get target voltage set Returns Voltage in ampere Return type float load_sequence(path) Load voltage waveform sequence from file Parameters path (str) – Path to CSV file with definition set_current(value) Set target current value Parameters value (float) – Target current value in ampere set_output(state) Set ouptut to on or off Parameters state (bool) – If True, output will set to “on”, else to “off” set_power(value) Set target power value Parameters value (float) – Target power value in watt set_voltage(value) Set target voltage value Parameters value (float) – Target voltage value in volt

13.19. tta.units.powersupply.powersupply 145 TTA Documentation, Release 1.15.2

start_sequence(repetitions=1) Start loaded sequence and repeat it (if desired) Parameters repetitions (int) – Number of repetitions stop_sequence() Stop running sequence

13.20 tta.units.ptc

This module provides a PTC Integrity unit interface. To use the PTC units the user needs to install ptc and fill in the credentials, like the password, the hostname, the port and the username. The user doesn’t need to open the GUI it is only necessary that he enters the credentials. To use the full functionality the user must build a valid connection with the connect method.

13.20.1 PTC Verdicts

The parameter tc_result includes the result of a test case, which is called verdict in PTC. In PTC there are several result types like “Passed”, “Failed” and “Skipped”. To edit a result of a test case the user must enter one of the following result types (see table below). These types are the TTA testcase result types and will be matched to the PTC verdict result types:

Result(TTA) Verdict(PTC) Passed Passed Incomplete Skipped Failed Failed Blocked Skipped Canceled Failed

13.20.2 PTC - PTC unit

The PTC unit is the interface to PTC Integrity. You can start a unit by providing the user name and the host name of the server the PTC client should connect to. Example: from tta.units.ptc import PTC ptc= PTC("my.ptc.host","my_user")

class tta.units.ptc.ptc.PTC(hostname, username) Unit class to interface PTC command line client Initialize PTC Unit with connection data Parameters • hostname (str) – URL of the PTC host • username (str) – Username for PTC connection add_session_report(session_id, tc_id, tc_result) Create a report in a test session

146 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters • session_id (int) – Identifier of the TestSession • tc_id (int) – Identifier of the TestCase • tc_result (str) – Result of the TestCase connect() Connect the initialized user to PTC create_testcase(parent_id, location, text) Create a new TestCase within a TestSuite Parameters • parent_id (int) – Identifier of the TestSuite • location (str) – Location of the TestCase within the TestSuite. Possible values are: first, last, before & after • text (str) – Description of the TestCase create_testobjective(project, summary) Create a new TestObjective within a project Parameters • project (int) – Name of the PTC project • summary (str) – Decscription of the TestObjective create_testsession(project=None, summary=None, objective_id=None) Create a new Test Session within a project linking to a TestObjective Parameters • project (str) – Name of the PTC project • summary (str) – Description of the TestSession • objective_id (int) – Identifier of the linked TestObjective create_testsuite(project, short_title) Create a new TestSuite within a project Parameters • project (str) – Name of the PTC project • short_title (str) – Title of the TestSuite delete_session_report(session_id, tc_id) Delete the report of a test case in a test session Parameters • session_id (int) – Identifier of the TestSession • tc_id (int) – Identifier of the TestCase disconnect() Disconnect the initialized user from PTC edit_session_report(session_id, tc_id, tc_result) Edit the report of a test case in a test session Parameters

13.20. tta.units.ptc 147 TTA Documentation, Release 1.15.2

• session_id (int) – Identifier of the TestSession • tc_id (int) – Identifier of the TestCase • tc_result (str) – Result of the TestCase export_session_attachment(session_id) Export Test Cases from Test Session Parameters • session_id (int) – Identifier of the test session • filter (dict) – list of types to filter (“case” and/or “session”) & string result to filter the exported test cases Returns List of all requirement files in TTA folder (MITE) Return type list export_suite_tc(suite_id, mapping=None, project_id=None, category=None) Export all testcases from PTC TestSuite get_all_fields() Return all available fields and their matching Backend-Names for Displaynames Returns Dictionary with all fields by Displayname and their names Return type Dict get_session_tc(session_id, tc_info=None, tc_filter=None) Returns the TestCases of a TestSession Parameters • session_id (int) – Identifier of the TestSession • tc_info (list) – List of all fields the returned TestCases should have • tc_filter (str) – TTA result filter that applies to returned TestCases Returns List of all TestCase information that are in the TestSession Return type list get_tcs_from_suite(suite_id, project=None, category=None) Parameters • ts_id (int) – ID of TestSuite to search in • project (str) – Project to match to • category (str) – Testcase category to filter for for example “System Test” load_testcase(tc_id, mapping) Return a detailed description for the current testcase as JSON Parameters • tc_id (int) – Id of the testcase to get description for • fields (list) – List of items in order [description, precondition, steps, expected, post- condition] Returns JSON representation of PTC testcase Return type dict

148 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.21 tta.units.pwm

This is a brief introduction to the PWM unit. The PWM module controls PWM generator signals. Features: • Read current duty cycle from PWM generator • Read current frequency from PWM generator • Change value of duty cycle • Change value of frequency

13.21.1 PWM Unit

As mentioned before, the PWM unit controls PWM generator signals. You can easily read and change values of duty cycle and frequency. The unit can be called with standard parameters, or with individual values. In order to support multiple devices, the driver has to be set up individually. The drivers can be exchanged without changing the way the PWM unit behaves. Thus, no code, using the PWM unit, has to be modified, if another driver is used. At the moment the following drivers are implemented for the PWM unit: DRIVER_PWMSERIAL (default). • Limitations: – max 1.000 Hz – duty cycle can only be set in 1% steps (50,5% -> 50%) • Driver Name: “PWMGeneratorTMArduino” Examples: Read current duty cycle and frequency from PWM generator (saved as a tuple) Change values of duty cycle in percent (1% = 0.01) or frequency in Hz.:

# start using parameters from config pwm_unit= PWMGenerator()

# start using custom parameters pwm_unit= PWMGenerator(self, duty_cycle= 0.4, frequency=100, driver="your driver name

˓→") current_dc= pwm_unit.get_duty_cycle() current_fq= pwm_unit.get_frequency() pwm_unit.set_duty_cycle(0.6) pwm_unit.set_frequency(400)

class tta.units.pwm.pwm.PWM(device=None, duty_cycle=0.2, frequency=10, driver=’PWMGeneratorTMArduino’) PWM generator unit to simulate pwm signals Parameters • device (dict) – Dictionary containing the device connection information (depends on driver) • duty_cycle (float) – duty cycle in percent (e. g. 0.01 = 1%, 0.5 = 50%)

13.21. tta.units.pwm 149 TTA Documentation, Release 1.15.2

• frequency (int) – frequency in Hz (e. g. 1 = 1Hz, 50 = 50Hz) • driver (int) – PWM driver, that will be used get_duty_cycle() Get duty cycle from pwm generator Returns duty cycle as float read from pwm generator Return type float get_frequency() Get frequency from pwm generator Returns frequency in hz read from pwm generator Return type float set_duty_cycle(duty_cycle) Set duty cycle to a float between 0.00 and 1.00 with just 2 decimal places Parameters duty_cycle (float) – duty cycle in percent (e. g. 0.01 = 1%, 0.5 = 50%) set_frequency(frequency) set frequency to an integer in Hz Parameters frequency (float) – frequency in Hz

13.21.2 Custom Drivers

Custom driver can be added, by inheriting from the PWM driver base class and implementing the methods. In order to make the driver accessible by the PWM Unit, the driver class has to be imported, within the pwm module and appended to the DRIVER_CLASSES list. class tta.units.pwm.pwm_driver_base.PWMDriverBase(unit_instance, device, duty_cycle, frequency) Base class for PWM generator drivers Parameters • device (dict) – Dictionary containing the device connection information • unit_instance (PWMGenerator) – PWMGenerator Unit instance using this driver • duty_cycle (float) – duty cycle in percent (e. g. 0.01 = 1%, 0.5 = 50%) • frequency (int) – frequency in Hz (min. 1, max. 1000) get_duty_cycle() Read duty cycle from pwm generator Returns duty cycle as float read from pwm generator Return type float get_frequency() Read frequency from pwm generator Returns frequency in hz read from pwm generator Return type float

150 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

set_duty_cycle(duty_cycle) Set pwm generator’s duty cycle. Parameter value must be in the range of 0.0 to 1.0. Parameters duty_cycle (float) – duty cycle in percent (e. g. 0.01 = 1%, 0.5 = 50%) set_frequency(frequency) Set pwm generator’s frequency Parameters frequency (float) – frequency in Hz (min. 1)

13.22 tta.units.qpst

This is a brief introduction to the QPST unit. The QPST module is used to access the QPST Automation Server from Qualcomm. Features: • Access the phone’s file system via EFS Explorer • Connect a phone and read phone information (status, ESN, etc.) • Restart the phone

13.22.1 QPST Unit

The QPST Unit can be used to access the phone’s file system, using the ‘efs_*()’ methods. class tta.units.qpst.qpst.QPST(com_port=None, label=None) The QPST Unit provides access to the COM interface of the QPST Automation server from Qualcomm. Parameters • com_port (str) – COM port of the phone. E.g. COM5. (optional) • label (str) – QPST label of an added phone. (optional) build_id str: The build information of the phone. efs_copy_file(path_src, path_dest) Copy a file within EFS. Parameters • path_src (str) – Source path on the phone. E.g. /tmp/test.txt • path_dest (str) – Destination path on the phone. E.g. /tmp/sub/test2.txt efs_copy_pc_to_phone(path_pc, path_efs) Copy a file from the PC to EFS. Parameters • path_pc (str) – Source path on the PC. E.g. c:temptest.txt • path_efs (str) – Destination path on the phone. E.g. /tmp/test.txt efs_copy_phone_to_pc(path_efs, path_pc) Copy a file from EFS to PC. Parameters

13.22. tta.units.qpst 151 TTA Documentation, Release 1.15.2

• path_efs (str) – Source path on the phone. E.g. /tmp/test.txt • path_pc (str) – Destination path on the PC. E.g. c:temptest.txt efs_create_link(src_efs_path, lnk_efs_path) Create a link to a file. Parameters • src_efs_path (str) – Path to existing file. • lnk_efs_path (str) – Path of the link. efs_delete(path_efs) Delete a file or a link. Use ‘efs_rm_dir’ or ‘efs_remove_tree’ to remove directories. Parameters path_efs (str) – Path of file or link to delete. efs_dir_list(efs_path, recursive=False) Get the contents of an EFS directory. The contents will be returned as dictionary. The following contents are listed: • Name of the specific directory items as keys of the returned dict object. • type: Type of the item as integer. File(0), Subdirectory(1), Link(2) • for the other parameters see the documentation of the ‘efs_stat_file’ method If the contents are returned recursively, the path will be added to the name (key of dict). Otherwise only the filename will be used as key. Note that returning the root ‘/’ recursively can cause permission errors. Parameters • efs_path (str) – Path to the directory. • recursive (bool) – Get the contents of the directory and its subdirectories. Returns Dictionary containing the folder contents. Return type dict efs_max_dir_entries int: Maximum number of directory entries. efs_max_file_size int: Maximum file size. efs_max_link_depth int: Maximum link depth. efs_max_mounts int: Maximum mounts. efs_max_name int: Maximum length of EFS names. efs_max_path int: Maximum length of EFS paths. efs_mk_dir(new_efs_path) Creates a new directory. Parameters new_efs_path (str) – Directory path to be created. efs_read_link(path_efs) Translate a link to the path it represents.

152 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters path_efs (str) – Path of directory to delete. Returns Translated path. Return type str efs_remove_tree(path_efs, allow_root_delete=False) Remove directory and its subdirectories. Parameters • path_efs (str) – Path of directory to delete. • allow_root_delete (bool) – Allow deleting the ‘/’ directory if True. False by de- fault. efs_rename(old_efs_path, new_efs_path) Rename a file. Parameters • old_efs_path (str) – Path to existing file. • new_efs_path (str) – Path to renamed file. efs_rm_dir(path_efs) Removes an empty directory. Parameters path_efs (str) – Path of directory to delete. efs_stat_file(path_efs) Return file properties as dictionary. The following properties are available: • mode: Contains a combination of file protections • size: Size in bytes. • nlink: Number of links to the file. • acctime: Last access time. Format ‘YYYY/MM/DD HH:MM:SS’ • modtime: Modification time. Format ‘YYYY/MM/DD HH:MM:SS’ • chgtime: Status change time. Format ‘YYYY/MM/DD HH:MM:SS’

Parameters path_efs (str) – Path on the phone. E.g. /tmp/test.txt

efs_stat_fs(path_efs=’/’) Return file system parameters as dictionary: • fs_id: File system ID. • fs_type: File system type. • blk_size: Blocksize of the file system. • tot_blks: Total blocks on file system. • avail_blks: Available blocks on file system. • free_blks: Free blocks on file system. • max_size: Maximum file size. • n_files: Number of file on the file system. • max_n_files: Maximum number of files on the file system.

13.22. tta.units.qpst 153 TTA Documentation, Release 1.15.2

Parameters path_efs (str) – Path to the mounted file system. E.g. ‘/’

efs_stat_link(path_efs) Return link properties as dictionary. The following properties are available: • mode: Contains a combination of file protections • acctime: Last access time. Format ‘YYYY/MM/DD HH:MM:SS’ • modtime: Modification time. Format ‘YYYY/MM/DD HH:MM:SS’ • chgtime: Status change time. Format ‘YYYY/MM/DD HH:MM:SS’

Parameters path_efs (str) – Path on the phone. E.g. /tmp/test_link

efs_version int: EFS protocol version. esn int: The ESN of the phone. imei str: The IMEI of the phone. is_usb int: 0 if the port is serial, 1 if the port is USB lock_phone() Lock the phone to prevent actions from the QPST GUI or another automation session to be executed. meid str: The MEID of the phone. model_number int: The mobile model number of the phone. phone_mode int: Mode of the phone detected by QPST. Possible values: • 0: No phone detected • 2: Phone in Download mode • 3: Phone in Diagnostic mode • 4: Phone offline and in Diagnostic mode • 6: Phone in streaming Download mode phone_status int: 0 if no phone is detected, 5 if the phone is ready port_label str: Label of the QPST port. port_name str: Name of the COM port. reset_phone() Send a reset command to the phone.

154 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

send_spc(spc_value) Send a Service Provisioning unlock code. Sending the wrong code will cause the phone to disconnect from QPST for 1 minute. Parameters spc_value (str) – Six-digit string containing the Service Provisioning code. set_offline() Send a command to the phone to change it to offline mode. Use the ‘reset_phone()’ method to restart the phone and return it to online mode. unlock_phone() Unlock the phone to enable actions from the QPST GUI or another automation session to be executed. Phone has to be locked before.

13.22.2 QPST Automation Server

The QPST Unit uses the QPST Automation Server’s COM Interface for automation. The Automation Server is ac- cessed, using the QPSTAutomationServer Unit. It is recommended not to use this Unit directly. Use the QPST Unit instead. class tta.units.qpst.qpst_automation_server.QPSTAutomationServer The QPST Unit provides access to the COM interface of the QPST Automation server from Qualcomm. Initializes the COM interfaces. call_efs_function(device, efs_function, *args) Call an EFS function on a specific device. Parameters • device (COMObject) – COM handle of the connected device. • efs_function (str) – Name of the called COM function. call_efs_function_with_variants(device, efs_function, *args) Call an EFS function on a specific device. Use this functions if Variants have to be passed as parameters (e.g. VT_BYREF). Parameters • device (COMObject) – COM handle of the connected device. • efs_function (str) – Name of the called COM function. connect_target(com_port=None, label=None, timeout=10.0) Connects a target(phone) to QPST. The required phone can be specified by devices COM port or by its QPST label. If COM port is given, the label will be ignored. If not parameters are given, an already added device will be connected. Note that CAM ports, that are not added to QPST yet will be added automatically. In this case the QPST label of the device will be set to the value of the ‘label’ parameter. If not ‘label’ parameter is present, the label will be named ‘Serial Port ’. Parameters • com_port (str) – COM port of the phone. E.g. COM5. • label (str) – QPST label of an added phone. • timeout (float) – Timeout in seconds that will be waited for the device to be ready. If the timeout is exceeded, the handle of the device will be returned event though it is not ready.

13.22. tta.units.qpst 155 TTA Documentation, Release 1.15.2

Returns COM handle of the connected device Return type COMObject get_efs_dir_list(device, efs_path, recursive=False) Get the contents of an EFS directory. The contents will be returned as dictionary. Parameters • device (COMObject) – COM handle of the connected device. • efs_path (str) – Path to the directory. • recursive (bool) – Get the contents of the directory and its subdirectories. Returns Dictionary containing the folder contents. Return type dict get_efs_property(device, efs_property) Get an EFS property of a specific device. Parameters • device (COMObject) – COM handle of the connected device. • efs_property (str) – Name of the property. get_phone_information(device, phone_information) Get a specific information from the connected device. Parameters • device (COMObject) – COM handle of the connected device • phone_information (str) – Name of the COM property. lock_phone(device) Lock the phone to prevent actions from the QPST GUI or another automation session to be executed. Parameters device (COMObject) – COM handle of the connected device quit_application() Shutdown the QPSTAtmnServer.Application COM interface and close the QPST Automation server, if no other client is connected to it. reset_phone(device) Reset the phone/target. Parameters device (COMObject) – COM handle of the connected device send_spc(device, spc_value) Send a Service Provisioning unlock code. Sending the wrong code will cause the phone to disconnect from QPST for 1 minute. Params str spc_value Six-digit string containing the Service Provisioning code. Parameters device (COMObject) – COM handle of the connected device set_offline(device) Send a command to the phone to change it to offline mode. Use the ‘reset_phone()’ method to restart the phone and return it to online mode. Parameters device (COMObject) – COM handle of the connected device

156 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

unlock_phone(device) Unlock the phone to enable actions from the QPST GUI or another automation session to be executed. Phone has to be locked before. Parameters device (COMObject) – COM handle of the connected device

13.23 tta.units.qxdm.qxdm

The QXDM Unit can be used to access the Qualcomm eXtensible Diagnostic Monitor (QXDM). QXDM is accessed using it’s integrated COM automation interface. The unit can be used to read traced items or send commands to the target. The Unit requires a valid QXDM installation with an active license. Supported Versions: 3.x, 4.x class tta.units.qxdm.qxdm.QXDM(com_port=0, gps_port=None, path_config=None, poll_interval=0.025, poll_max_size=1000, driver=’QXDM_v3.x’) The QXDM Unit provides access to the COM interface of QXDM from Qualcomm. Parameters • com_port (int) – COM port of the target. E.g. 5 for COM5. Set to 0 in order to disconnect. • gps_port (int) – Number of the serial COM port of an optional external GPS receiver. E.g. 6 for COM6 • path_config (str) – Path to the a QXDM .dmc configuration file. • poll_interval (float) – Interval for polling new messages while an Eventsource is attached. • poll_max_size (int) – Maximum number of Items read at once while an Eventsource is attached. Reading more Items at once decreases overhead but increases latency. • driver (str) – QXDM driver, that will be used. Available: QXDM_v3.x connect_gps(gps_port) Connects an external GPS receiver to QXDM. Parameters gps_port (int) – COM port of the GPS receiver. Set to 0 in order to disconnect. connect_target(com_port) Connects a target(phone) to QXDM. The COM port can be looked up using QPST. Parameters com_port (int) – COM port of the target. E.g. 5 for COM5. Set to 0 in order to disconnect. export_view_text(view_name, output_file) Exports all items of a view to a text file. Parameters • view_name (str) – Name of the view to be exported. • output_file (str) – Path to the output file. load_config(path_config) The function loads a configuration file (.DMC). Parameters path_config (str) – Path to the a QXDM .dmc configuration file.

13.23. tta.units.qxdm.qxdm 157 TTA Documentation, Release 1.15.2

load_item_store(input_file) Load an existing item store (.isf) file. All items in this file can then be read using Eventsources or the read_item() / read_items() function. NOTE: A connected target will be disconnect by calling this method. Parameters output_file (str) – Path to the output file. quit_application() Shutdown the QXDM.Application COM interface. The QXDM application will be shut down as well. read_item(timeout=None) Read the next unread item from the trace. The function will wait, if no unread items are available. Parameters timeout (float) – Wait timeout in seconds. None for unlimited timeout. Returns QXDM Item or None in case of a timeout Return type Item read_items(count=None, timeout=None) Read multiple items. Limits can be set on the number of items that will be read (count) and the maximum time that the reading process can take (timeout). The parameter can be set to None: 1) Only count set to None: All unread items that are received till timeout will be returned 2) Only timeout set to None: The method will wait (forever) till all items specified by count are received 3) Timeout and count are set to None: All unread items will be returned immediately

Parameters • count (int) – Timeout in seconds. Default: None • timeout (float) – Timeout in seconds. The functions stops after the timeout and returns all available items. Default: None Returns List of QXDM Items. May be empty. Return type Item

reset_phone() Reset the phone/target. save_item_store(output_file) Save the actual item store to a .isf file. Parameters output_file (str) – Path to the output file. class tta.units.qxdm.qxdm.QXDMFilter(item_type=None, key=None, name=None, sum- mary=None, use_regex=False) Event filter for QXDM items, filtering for type, key, name and summary. Wild card is “None” and matches any value, so if e. g. scope is “None”, any scope will be accepted by the filter. Parameters • item_type (int) – Number of the type • key (str) – Key of the item • name (str) – String that occurs in the name • summary (str) – String that occurs in the summary • use_regex (bool) – Use regular expressions to evaluate name and summary. False by default.

158 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation class tta.units.qxdm.qxdm.QXDMHelper Helper class providing functions to work on the QXDM trace. classmethod check_trace_summary_for_pattern(qxdm_unit, pattern, close_after, time- out) Search for the given pattern in the current QXDM trace Param string pattern: The pattern to search for in the trace Returns True, if the pattern could be found Return type bool

13.24 tta.units.relay:

The relay module provides an interface to interact with relay boards. It has been developed with a driver concept, which means that the module can be easily expanded to support new boards, by writing classes for each new board type.

13.24.1 Relay Unit

The relay unit provides functions to operate relays on a relay board. It can set relays, get the switching status (ON or OFF) of the relays, toggle and reset them. The boards can be connected, using various interfaces depending on the board. class tta.units.relay.Relay(board=’Conrad8RelayBoard’, address=0, port=’COM1’) Class to control a relay board Initializes the relay unit. :param board :param address :param port get() Returns the state of the relays on the relay board Returns Switching state of relays Return type int is_active() Returns the status of the board. Returns True if active, false otherwise. Return type bool

13.24. tta.units.relay: 159 TTA Documentation, Release 1.15.2

reset() Switches off all relays set(on=None, off=None) Switches on the relays in relaylist. Parameters • relaylist (list) – List of relays to be switched on • state (int) – Desired state of the relays: 0 (OFF) or 1(ON) • preserve (int) – Preserves the state of the other relays, if set to 1. toggle(relaylist) Toggles the state of the relays in relaylist Parameters relaylist (list) – Relays to be toggled

13.24.2 Conrad8RelayBoard-Driver

This class provides the interface to operate a Conrad 8 Channel Relay Board. The board is operated over a serial port interface. The cascaded operation of multiple Conrad boards is also supported. The functions available are set, get, toggle and reset. The execution of a function involves the generation of a command, sending the command over the serial port and reading the response from the relay controller. The functions calculate the addresses of the boards and therefore, no address is required as a function parameter, except while initializing the unit. class tta.units.relay.conrad8relay.Conrad8RelayBoard(unit_instance, address, port, baudrate=19200, timeout=1) Class to control a Conrad 8 Channel relay board. Model number: 197730 Initializes the relay board Parameters • address (int) – Address of the relay board • port (str) – Device name, e.g. COM1 • boardcount – Number of relay boards to be controlled • baudrate (int) – Baud rate (set to 19200 if omitted) • timeout (int) – Timeout of the serial port get() Returns the switching states of the relays. Parameters address (int) – Address of the relay board. Returns Switching state of relays Return type dict is_active() Returns the status of the relay board. Returns Status of the board. True: Active, False: Inactive Rytpe bool reset() Switch off all relays.

160 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

set(on=None, off=None) Set relay states. Parameters • on (list) – List of relays to be switched on. • off (list) – List of relays to be switched off. Returns status code: 1 if successful, -1 if failed Return type int toggle(relaylist) Toggles the relays. Parameters relaylist (list) – Relays to be toggled. Returns status code: 1 if successful, -1 if failed Return type int

13.24.3 Initializing the unit

The unit can be initialized, by giving “Conrad8RelayBoard” as the board parameter and the address and COM port as other parameters. The constructor function reads the responses and automatically determines the count of boards. Consequently, it determines the number of available relays. Example:

address=0 port="COM8" conrad1= Relay("Conrad8RelayBoard", address, port)

If the initializing process of the relay is failed the user will be received an error. An error could be that the relay board is not correctly connected with another board or that a single relay board can‘t get a signal.

13.24.4 Setting Relays

Relays are switched, by using the set function with an “on” list and “off” list as parameters. The states of the relays, which are not in the list, remain unchanged. The function checks, if the inputs are within the range of available relays. If not, an error is raised. Example: Scenario 1: One board is connected. Eight relays are available. Switching on relays 2,4 and 8 is done as follows:

conrad1.set(on=[2,4,8])

Example: Relay 8 is switched off without affecting other relays:

conrad1.set(on=[], off=[8])

Example: Now an attempt to set relay 19 is made. However, the user will receive an error, because only 8 relays are available:

conrad1.set(on=[19]) ERROR: Can't operate more than 8 relays!

13.24. tta.units.relay: 161 TTA Documentation, Release 1.15.2

Example: Scenario 2: Three boards are connected. 24 relays are available. Switching on the relays 2, 6, 9, 21. The addresses for the boards are calculated internally, by the set function: conrad1.set(on=[2,6,9,21])

Scenario 3: Switch on all relays: conrad1.set(on=[conrad1.ALL_RELAYS])

13.24.5 Getting relay states

Relay states are obtained, by using the get function, which then returns a list of all relays, that are switched on. This works, by sending a broadcast “get” command to all boards and then appending those relays to a list, which are switched on. Example: conrad1.set(on=[2,4]) conrad1.get() [2,4]

13.24.6 Toggle relays

With this command, the state of the relays will be inverted, i.e. if the relay was previously ON, it will be switched OFF and vice versa. Example: Scenario: Set relays 2 and 6. Toggle relay 6: conrad1.set(on=[2,6]) conrad1.get() [2,6] conrad1.toggle([6]) conrad1.get() [2]

Example: Scenario: Toggle all relays: conrad1.toggle(ALL_RELAYS)

13.24.6.1 Reset

This function switches off all the available relays. This is also done during deregistration of the relay unit. Example: conrad1.set[2,6,7] conrad1.get() [2,6,7] conrad1.reset() conrad1.get() []

162 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.25 tta.units.serial

This is a brief introduction to the Serial unit. The serial module encapsulates the access to the serial ports. For a detailed documentation, see the tta_tutorials_serial Features: • Synchronous and asynchronous read and write functions. • Uniform interface for accessing different serial ports (e.g. via pySerial). • Virtual serial port for testing purposes. • Single ports can be used simultaneously, by several units/test cases. • Integration of TTA concepts such as EventSources, Logging, etc.

13.25.1 Serial Unit

A Serial Unit object depends on a specific serial port and the driver that provides the serial port. By default, the Serial unit uses pySerial(serial) as driver, to access every serial port known to the operating system. For a list of implemented drivers, see Implemented Drivers. Additionally, the baud rate and timeout interval (in seconds) should be defined, when creating the unit. To use the serial port, the unit must be started explicitly after its creation, by calling the start_up() method. Examples: Open a Serial unit, using pySerial on port “COM1” with a specific timeout and baudrate and on port “COM2” with default values (timeout=1 and baudrate=19200): serial_unit= Serial(port="COM1", baudrate=9600, timeout=1) serial_unit.start_up() serial_unit= Serial("COM2") # timeout and baudrate will be set to default values, if

˓→they are omitted serial_unit.start_up()

Note: A Serial unit can simultaneously be used, by several other units/test cases. This may cause unexpected behavior, if the same port was opened unintentionally.

class tta.units.serial.Serial(port=’COM1’, baudrate=19200, timeout=1, driver=’pySerial’, max_shutdown_time=20, **kwargs) Serial Unit to get access to a serial interface. Additional keyword parameters can be added. See the pySerial (serial) documentation for further informa- tion about the available parameters. The following parameters are always used: Parameters • driver (int) – Serial driver, that will be used. By possible values: DRIVER_PYSERIAL (default), DRIVER_VIRTUAL • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 19200 if omitted) • timeout (float) – Read and write timeout in seconds

13.25. tta.units.serial 163 TTA Documentation, Release 1.15.2

• max_shudown_time (float) – The max time in seconds, for which the unit will wait before interrupting an active read when shutting down start_up() Open the Port.

13.25.2 Sending data

Data can be sent, using the write() method. All byte data types (bytes, bytearray, bytes sequences) or ascii strings can be sent:

serial_unit= Serial("COM1") serial_unit.start_up()

serial_unit.write("ascii strings are allowed") serial_unit.write(b'bytes sequences are preferred') serial_unit.write(bytes([100,23,44]))

The write() method will return the number of bytes sent.

13.25.3 Reading data

There are two ways to read data: 1. Synchronous reads 2. Asynchronous reads using EventSources

Note: Synchronous and asynchronous reading can not be combined. Synchronous reads, while an EventSource is attached, lead to unexpected results and vice versa.

13.25.3.1 Synchronous reading:

Reading data from the serial port will return byte sequences. Data can be read directly from the buffer, using read() or readline():

serial_unit= Serial("COM1") serial_unit.start_up()

serial_unit.read(10) # read 10 bytes serial_unit.read() # read everything in the buffer or until timeout serial_unit.readline() # read till '\n' occurs

13.25.3.2 Asynchronous reading:

Data can also be read, using EventSources. As soon as an EventSource is added to the unit, all data, send to the unit, will be stored byte by byte in the EventSource(s). Each Event contains one byte in its “value” attribute. After the last EventSource has been removed from the unit, the data will be stored in the buffer again.

Note: Bytes that are already in the serial ports buffer, when the first EventSource is attached, will directly be pushed to the EventSource.

164 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Examples:

serial_unit= Serial("COM1") serial_unit.start_up()

src= EventSource(serial_unit) time.sleep(2.0) # wait for data to be send src.close()

for event in src: one_byte= event.value print(one_byte)

For convenience, an EventSource can be read, similar to synchronous reading, using event_read() or event_readline():

data= serial_unit.event_read(src, 20) # read 20 bytes from EventSource src data= serial_unit.event_readline(src) # read from EventSource src until '\n' occurs

13.25.3.3 Timeouts

Every timeout, during synchronous or asynchronous reading, will raise a SerialReadTimeoutError. The data read till timeout can be accessed in the args[1] attribute of the timeout:

try: data= serial_unit.readline() except SerialReadTimeoutError as exception: data= exception.args[1]

13.25.4 Implemented Drivers

The Serial unit can use one of several drivers, in order to provide access to different serial ports. The drivers can be exchanged, without changing the way the Serial unit behaves. Thus, no code using the Serial unit has to be modified, if another driver is used. At the moment, the following drivers are implemented for the Serial unit: pySerial (default): Uses the pySerial module for Python and is the default driver for the Serial unit. Use this driver, if you want to access a serial port that is known to the operating system (e.g. a COM port listed in the Windows Device Manager). Virtual Driver: Creates an virtual serial port in the Serial unit. Data written to this unit/port can be read from it afterwards. This driver should only be used for testing purposes.

Example: Create a Serial unit on “COM1” and “COM2” using pySerial as driver and a Serial unit on “COM15”, using the virtual driver:

from tta.units.serial import Serial

# import the driver identifiers from tta.units.serial.serial import DRIVER_PYSERIAL from tta.units.serial.serial import DRIVER_VIRTUAL (continues on next page)

13.25. tta.units.serial 165 TTA Documentation, Release 1.15.2

(continued from previous page)

serial_pyserial_1= Serial("COM1") # Serial unit using

˓→default driver (pySerial) an port COM1 serial_pyserial_2= Serial("COM2", driver=DRIVER_PYSERIAL) # Driver explicitly set

˓→to pySerial

serial_virtual= Serial("COM15", driver=DRIVER_VIRTUAL) # Serial unit using

˓→virtual driver on port COM15

13.26 tta.units.template.template

Definition of a template for new Units class tta.units.template.template.Template(arg1=’default1’) TODO: add description of the whole unit here: TODO: add description of the parameters of the unit here (including types): Parameters arg1 (str) – a example parameter without meaning not_wrapped_method(i_param, i_param_with_default=42) TODO: add description for every method in the unit, including parameters and return value: This function adds two parameters and returns the value. Parameters • i_param (int) – First parameter • i_param_with_default (int) – Second parameter. This parameter is optional and replaces with 42, if omitted Returns Sum of two parameters Return type int wrapped_method(i_param, i_param_with_default=42) TODO: add description for every method in the unit, including parameters and return value: This function adds two parameters and returns the value. Parameters • i_param (int) – First parameter • i_param_with_default (int) – Second parameter. This parameter is optional and replaces with 42, if omitted Returns Sum of two parameters Return type int

13.27 tta.units.term.term

Module for Term unit and related functions class tta.units.term.term.Term(driver=None, host=None, user=None, passw=None, port=23) The FTP unit provides file transfer functions. It supports FTP, FTPS(FTP via SSL) and SFTP(FTP via SSH).

166 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Parameters • host (str) – Host name or IP address to connect to • user (str) – User name • passw (str) – Password • port (int) – TCP port to connect to execute(command) Execute command string on remote host Parameters command (bytes) – Command string to execute Returns Command result Return type bytes

13.28 tta.units.timer.event_source

This module provides a set of event sources which can be used to implement timer functionality, e.g. timouts. class tta.units.timer.event_source.CyclicSource(cycle_time, max_events=1, unit=None, filter_=None) EventSource that delivers cyclic events with cycle time in sec Parameters • cycle_time (float) – Cycle time (base is seconds, e. g. 0.120 means “120 ms”) • max_events (int) – Number of triggered events • unit (UnitBase) – Unit to be attached to • filter (EventFilter) – Event filter to be applied close(reason=None) Close cyclic source run() Trigger timed events class tta.units.timer.event_source.TimerEvent(value, timestamp=None, source=None, timestamp_device=None) Timer event. Parameters • value – The value of the event. • timestamp (datetime) – Event’s timestamp. If None, current timestamp will be used. • source (EventSource) – EventSource that created this Event

13.29 tta.units.timer.timer

This module provides a TimerUnit which can be used to implement timer functionality, e.g. timeouts. class tta.units.timer.timer.Timer The timer unit provides a set of event sources which can be used to implement timer functionality, e.g. timeouts.

13.28. tta.units.timer.event_source 167 TTA Documentation, Release 1.15.2

13.30 tta.units.uds

This module provides a TTA unit interface to Unified Diagnostic Services (UDS). The UDS Unit contains functions for all specified UDS Services and a class, defining all the constant parameters from the UDS protocol, in a way that the tester does not have to use the raw/hexadecimal values of the parameters.

13.30.1 UDS - UDS unit

A UDS unit is associated to a CAN channel. In order to be able to send and receive UDS services, it is necessary to define the device_id, the channel, the src_addr, the ident_base, the addressing and the padding. The device_id might be an IP address (for a bluePiraT or other Telemotive hardware for example), a device serial number (as string) or None (for Vector hardware). The channel defines, which channel from the hardware to use (if it has more than one address). The src_addr defines the address of the ECU, with which you want to communicate on the CAN-bus. The ident_base is the base address of the CAN-Bus, while addressing is the addressing type of the CAN bus and the padding defines with which padding you want to complete your CAN Messages, in the case they are smaller than 8 bytes. A function sending a UDS Service has the same name as the UDS Service its sends (as defined in ISO). A function takes the ecu_address and eventually other UDS constants or values as parameters. The functions from the UDS Unit return the answer received from the ECU as a byte array, in case of a positive answer received. In case of a negative answer, a TTAUDSError will be raised. You can catch and then analyze those exceptions with a try/except block. The reason for the negative answer is stored in the attribute .error_code of the TTAUDSError. Another type of error can be raised, by the UDS Unit : the TTAISOTPTimeoutError. This error is raised in two different cases : 1), when an ISOTP-Timeout occurs, which means that the ECU did not answer in the next second after receiving the UDS Service, or 2), in case the ECU returns a UDS Response Pending and does not send a second answer in the next 5 seconds. Example: • Open a UDS Unit with different parameters:

# Open UDS unit for the device "192.168.0.233", on 2nd channel, with padding and

˓→addressing extended uds= UDS("192.168.0.233", channel=1, src_addr=0x7E, ident_base=0x700,

˓→addressing=ISOTP.ADDR_EXTENDED, padding=0xaa) # Open UDS unit without padding with default addressing (which is also extended) uds= UDS("192.168.0.233", channel=1, src_addr=0x7E, ident_base=0x700) # Open UDS unit for Vector hardware on channel 2 uds= UDS( None, channel=1)

• Send a UDS Service with a parameter: testerPresent

uds.testerPresent(0x00) # Send testerPresent in broadcast

• Send a UDS Service with a UDS constant parameter: diagnosticSessionControl - ProgrammingSession

uds.diagnosticSessionControl(0x14, UDSType.Session.ECUProgramming)

• Send a UDS Service with UDS constant and Parameters : securityAccess sendKey:

list_key=[0x12, 0x34, 0x56, 0x78] uds.securityAccess(0x14, UDSType.Security.SendKeyFlash, list_key)

168 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• Send a UDS Service with multiple UDS constants : communicationControl EnableNonDiagnosticCommunica- tion:

uds.communicationControl(0x00, UDSType.Communication.EnableRxAndTx, UDSType.

˓→CommunicationNet1.Normal| (UDSType.CommunicationNet2.AllNetworks <<4))

• Catch a negative answer to a UDS Service : example of a ServiceNotSupportedInActiveSession for a Write- DataByIdentifier:

try: uds.writeDataByIdentifier(0x14, 0x0102,[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) except TTAUDSError as exception: if TTAUDSError.error_code == UDSType.Error.ServiceNotSupportedInActiveSession: print("Expected error received")

class tta.units.uds.UDS(device_id=’192.168.0.233’, channel=0, src_addr=247, ident_base=1536, addressing=1, padding=None) UDS Unit (Unified Diagnose Service) Handle UDS requests Parameters • device_id (str) – Identifier of device, can be IP-address, serial number or None • channel (int) – CAN channel • src_addr (int) – ECU address used for sender • ident_base (int) – Identifier base for ECU addressing • addressing (int) – Address mode (ISOTP.ADDR_BASE=0x00, ISOTP.ADDR_EXTENDED=0x01, ISOTP.ADDR_IDENT=0x02) • padding (int) – Byte value for padding up to full 8 byte frame accessTimingParameters(ecu_addr, code) Access Timing Parameters (NOT YET IMPLEMENTED) Parameters ecu_addr (int) – ECU address of destination(target) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError clearDiagnosticInformation(ecu_addr, group) Clear Diagnostic Information Parameters • ecu_addr (int) – ECU address of destination(target) • group (UDSType.DTCClear) – Group of DTCs Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError communicationControl(ecu_addr, control, network, node=None) Communication Control

13.30. tta.units.uds 169 TTA Documentation, Release 1.15.2

Parameters • control (UDSType.Communication) – Control type • network (UDSType.CommunicationNet1) – 4 highest bits of network for the com- munication, 4 lowet bits for the network type • node (int) – Node identification number Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError controlDTCSettings(ecu_addr, control, option) Control DTC Settings Parameters • control (UDSType.DTCSetting) – DTC setting type • option (UDSType.DTCSettingOption) – DTC setting control option Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError diagnosticSessionControl(ecu_addr, session) Diagnostic Session Control Parameters session (UDSType.Session) – Session type Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError dynamicallyDefineIdentifier(ecu_addr, identifier, data) Dynamically Define Identifier (NOT YET IMPLEMENTED) Parameters • ecu_addr (int) – ECU address of destination(target) • identifier (int) – Identifier value (range is 0..65535) • data (list) – List of int(bytes) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError ecuReset(ecu_addr, reset, sleep_time=None) ECU reset Parameters • reset (UDSType.Reset) – Reset type • sleeptime (int) – Time to power down (only for 0x04 reset type EnableRapidPower- ShutDownSequence) Returns Result as list of int(bytes)

170 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError inputOutputControlByIdentifier(ecu_addr, identifier, parameter, states) Input Output Control By Identifier Parameters • ecu_addr (int) – ECU address of destination(target) • identifier (int) – InputOutput Identifier value (range is 0..65535) • parameter (UDSType.InputOutputPar) – InputOutput Parameter value • states (list) – List of int(bytes) containing Control States #1 to n Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError linkControl(ecu_addr, control, mode) Link Control Parameters • control (UDSType.Link) – Link control type • mode (UDSType.LinkMode) – Link control mode identifier Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError readDTCInformation(ecu_addr, info_type, status_mask) Read DTC Information (INCOMPLETE) Parameters • ecu_addr (int) – ECU address of destination(target) • info_type (UDSType.DTCRead) – Information type • int status_mask (UDSType.DTCReadStat) – Status mask Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError readDataByIdentifier(ecu_addr, identifier) Read Data By Identifier Parameters • ecu_addr (int) – ECU address of destination(target) • identifier (int) – Identifier value (range is 0..65535) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError

13.30. tta.units.uds 171 TTA Documentation, Release 1.15.2

readDataByPeriodicIdentifier(ecu_addr, identifier) Read Data By Periodic Identifier (NOT YET IMPLEMENTED) Parameters • ecu_addr (int) – ECU address of destination(target) • identifier (int) – Identifier value (range is 0..65535) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError readMemoryByAddress(ecu_addr, format_len, mem_addr, mem_size) Read Memory By Address Parameters • ecu_addr (int) – ECU address of destination(target) • format_len (int) – Address and lenght format identifier • mem_addr (list) – Memory address • mem_size (list) – Memory size Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError requestDownload(ecu_addr, format_data, format_len, mem_addr, mem_size) Request Download Parameters • ecu_addr (int) – ECU address of destination(target) • format_data (int) – Data format identifier • format_len (int) – Address and lenght format identifier • mem_addr (list) – Memory address • mem_size (list) – Memory size Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError requestTransferExit(ecu_addr) Request Transfer Exit Parameters ecu_addr (int) – ECU address of destination(target) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError requestUpload(ecu_addr, format_data, format_len, mem_addr, mem_size) Request Upload Parameters

172 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• ecu_addr (int) – ECU address of destination(target) • format_data (int) – Data format identifier • format_len (int) – Address and length format identifier • mem_addr (list) – Memory address • mem_size (list) – Memory size Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError responseOnEventService(ecu_addr, code) Response On Event Service (NOT YET IMPLEMENTED) Parameters code (int) – Control code Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError routineControl(ecu_addr, operation, identifier, data=None) Routine Control Parameters • ecu_addr (int) – ECU address of destination(target) • operation (UDSType.Routine) – Operation to do (UDSRou- tine.Start/Stop/Request) • identifier (int) – Identifier value (range is 0..65535) • data (list) – List of int(bytes) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError runner_tester_present() Thread to continuously send “Tester Present” securityAccess(ecu_addr, access, data=None) Security Access Parameters • access (UDSType.Security) – Access type • data (list) – List of int(bytes) to transfer Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError testerPresent(ecu_addr, control=128) Tester Present Parameters • control (int) – Control code • repeat (bool) – If True, start thread to send continuously

13.30. tta.units.uds 173 TTA Documentation, Release 1.15.2

Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError testerPresentDisable() Tester Present disable (stop sending continuously) testerPresentEnable() Tester Present enable (start sending continuously) transferData(ecu_addr, blocknum, data) Transfer Data Parameters • ecu_addr (int) – ECU address of destination(target) • blocknum (int) – Sequence number of block to transfer • data (list) – List of int(bytes) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError writeDataByIdentifier(ecu_addr, identifier, data) Write Data By Identifier Parameters • ecu_addr (int) – ECU address of destination(target) • identifier (int) – Identifier value (range is 0..65535) • data (list) – List of int(bytes) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError writeMemoryByAddress(ecu_addr, format_len, mem_addr, mem_size, data) Write Memory By Address Parameters • ecu_addr (int) – ECU address of destination(target) • format_len (int) – Address and lenght format identifier • mem_addr (list) – Memory address • mem_size (list) – Memory size • data (list) – List of int(bytes) Returns Result as list of int(bytes) Return type list Raise tta.core.exception TTAUDSError, TTAISOTPTimeoutError

174 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.30.2 UDSType

The UDSType class describes several UDS constants. Those constants are grouped, by the UDS Service they refer to.

13.30.2.1 UDSType.Error

The UDSType.Error are used, in order to define the reason of a negative answer from the ECU. They are used as attributes from the TTAUDSError exception. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Error Class for enums of UDS error codes BusyPending = 120 Busy – Response pending BusyRepeat = 33 Busy – Repeat request ConditionsNotCorrect = 34 Conditions not correct ExceedAttempts = 54 Exceed attempts FailurePreventsExecution = 38 Failure prevents execution of requested action GeneralProgrammingFailure = 114 General programming failure GeneralReject = 16 General Reject InvalidKey = 53 Invalid key MsgFormatIncorrect = 19 Message length or format incorrect NoResponseFromSubnetComponent = 37 No response from subnet component OutOfRange = 49 Out of range RequestSequenceError = 36 Request sequence error RequiredTimeDelayNotExpired = 55 Required time delay not expired ResponseTooLong = 20 Response too long SecurityAccessDenied = 51 Security access denied or needed

13.30. tta.units.uds 175 TTA Documentation, Release 1.15.2

ServiceNotSupported = 17 Service not supported ServiceNotSupportedInActiveSession = 127 Service not supported in active diagnostic session SubFunctionNotSupportedInActiveSession = 126 Subfunction not supported in active diagnostic session SubFunctionNotSupported_x12 = 18 Subfunction not supported TransferDataSuspended = 113 Transfer data suspended UploadDownloadNotAccepted = 112 Upload/download not accepted WrongBlockSequenceCounter = 115 Wrong block sequence counter

13.30.2.2 UDSType.Session

The UDSType.Session is used as parameter in the UDS diagnosticSessionControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Session Class for enums of diagnostic session control session types Default = 1 Default session Development = 79 Development session ECUProgramming = 2 ECU programming session ExtendedDiagnostic = 3 Extended diagnostic session IOTest = 65 Input output testing

13.30.2.3 UDSType.Security

The UDSType.Security is used as parameter in the UDS securityAccess. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Security Class for enums of security access types RequestSeed = 3 Request seed

176 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

RequestSeedFlash = 17 Request seed for flash RequestSeedKWFS = 9 Request seed for K-/WFS RequestSeedSpecial1 = 33 Request seed for special activation #1 RequestSeedSpecial10 = 51 Request seed for special activation #10 RequestSeedSpecial11 = 53 Request seed for special activation #11 RequestSeedSpecial12 = 55 Request seed for special activation #12 RequestSeedSpecial13 = 57 Request seed for special activation #13 RequestSeedSpecial14 = 59 Request seed for special activation #14 RequestSeedSpecial15 = 61 Request seed for special activation #15 RequestSeedSpecial16 = 63 Request seed for special activation #16 RequestSeedSpecial2 = 35 Request seed for special activation #2 RequestSeedSpecial3 = 37 Request seed for special activation #3 RequestSeedSpecial4 = 39 Request seed for special activation #4 RequestSeedSpecial5 = 41 Request seed for special activation #5 RequestSeedSpecial6 = 43 Request seed for special activation #6 RequestSeedSpecial7 = 45 Request seed for special activation #7 RequestSeedSpecial8 = 47 Request seed for special activation #8 RequestSeedSpecial9 = 49 Request seed for special activation #9 SendKey = 4 Send key SendKeyFlash = 18 Send key for flash SendKeyKWFS = 10 Send key for K-/WFS

13.30. tta.units.uds 177 TTA Documentation, Release 1.15.2

SendKeySpecial1 = 34 Send key for special activation #1 SendKeySpecial10 = 52 Send key for special activation #10 SendKeySpecial11 = 54 Send key for special activation #11 SendKeySpecial12 = 56 Send key for special activation #12 SendKeySpecial13 = 58 Send key for special activation #13 SendKeySpecial14 = 60 Send key for special activation #14 SendKeySpecial15 = 62 Send key for special activation #15 SendKeySpecial16 = 64 Send key for special activation #16 SendKeySpecial2 = 36 Send key for special activation #2 SendKeySpecial3 = 38 Send key for special activation #3 SendKeySpecial4 = 40 Send key for special activation #4 SendKeySpecial5 = 42 Send key for special activation #5 SendKeySpecial6 = 44 Send key for special activation #6 SendKeySpecial7 = 46 Send key for special activation #7 SendKeySpecial8 = 48 Send key for special activation #8 SendKeySpecial9 = 50 Send key for special activation #9

13.30.2.4 UDSType.Reset

The UDSType.Reset is used as parameter in the UDS ecuReset. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Reset Class for enums of ecu reset types DisableRapidPowerShutDownSequence = 5 Disable rapid power shutdown sequence

178 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

EnableRapidPowerShutDownSequence = 4 Enable rapid power shutdown sequence Hard = 1 Hard reset KeyOffOn = 2 Key off on reset Soft = 3 Soft reset

13.30.2.5 UDSType.Communication

The UDSType.Communication is used as parameter in the UDS communicationControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Communication Class for enums of communication control types DisableRxAndEnableTx = 2 Disable rx and enable tx DisableRxAndTx = 3 Disable rx and tx EnableRxAndDisableTx = 1 Enable rx and disable tx EnableRxAndDisableTxWithEnhAddr = 4 Enable rx and disable tx with enhanced address information EnableRxAndTx = 0 Enable rx and tx EnableRxAndTxWithEnhAddr = 5 Enable rx and tx with enhanced address information GateWayVehicleWakeup = 64 Gateway vehicle wakeup

13.30.2.6 UDSType.CommunicationNet1

The UDSType.CommunicationNet1 is used as parameter in the UDS communicationControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class CommunicationNet1 Class for enums of communication control types, network, (lower nibble of CommunicationAndNetwork- Type) NetworkManagement = 2 Network management communication messages

13.30. tta.units.uds 179 TTA Documentation, Release 1.15.2

Normal = 1 Normal communication messages NormalAndNetworkManagement = 3 Normal and network management communication messages

13.30.2.7 UDSType.CommunicationNet2

The UDSType.CommunicationNet2 is used as parameter in the UDS communicationControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class CommunicationNet2 Class for enums of communication control types, network, (higher nibble of CommunicationAndNetwork- Type) AllNetworks = 0 Applies to all networks MainNetwork = 15 Main network SubNetwork1 = 1 Sub network #1 SubNetwork10 = 10 Sub network #10 SubNetwork11 = 11 Sub network #11 SubNetwork12 = 12 Sub network #12 SubNetwork13 = 13 Sub network #13 SubNetwork14 = 14 Sub network #14 SubNetwork2 = 2 Sub network #2 SubNetwork3 = 3 Sub network #3 SubNetwork4 = 4 Sub network #4 SubNetwork5 = 5 Sub network #5 SubNetwork6 = 6 Sub network #6 SubNetwork7 = 7 Sub network #7 SubNetwork8 = 8 Sub network #8

180 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

SubNetwork9 = 9 Sub network #9

13.30.2.8 UDSType.DTCSetting

The UDSType.DTCSetting is used as parameter in the UDS controlDTCSettings. class tta.units.uds.UDSType Class for all enums and constants of UDS services class DTCSetting Class for enums of control DTC setting types Off = 2 Activate persistent saving of DTCs On = 1 Deactivate persistent saving of DTCs

13.30.2.9 UDSType.DTCSettingOption

The UDSType.DTCSettingOption is used as parameter in the UDS controlDTCSettings. class tta.units.uds.UDSType Class for all enums and constants of UDS services class DTCSettingOption Class for enums of control DTC setting option types AllDTCs = 16777215 All supported and recognized DTCs

13.30.2.10 UDSType.Link

The UDSType.Link is used as parameter in the UDS linkControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Link Class for enums of link control types TransitionMode = 3 Transition mode VerifyMode = 1 Verify mode transition with fixed parameter

13.30. tta.units.uds 181 TTA Documentation, Release 1.15.2

13.30.2.11 UDSType.LinkMode

The UDSType.LinkMode is used as parameter in the UDS linkControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class LinkMode Class for enums of link control mode types CAN1MBaud = 20 CAN 1Mbit baud CAN500kBaud = 18 CAN 500k baud Programming = 32 Programming setup

13.30.2.12 UDSType.DTCClear

The UDSType.DTCClear is used as parameter in the UDS clearDiagnosticInformation. class tta.units.uds.UDSType Class for all enums and constants of UDS services class DTCClear Class for enums of clear diagnostic information

13.30.2.13 UDSType.DTCRead

The UDSType.DTCRead is used as parameter in the UDS readDTCInformation. class tta.units.uds.UDSType Class for all enums and constants of UDS services class DTCRead Class for enums of read diagnostic information DTCByStatusMask = 2 Report DTC by status mask DTCExtDataRecordByDTCNumber = 6 Report DTC extended data record by DTC number DTCSnapshotRecordByDTCNumber = 4 Report DTC snapshot record by DTC number MostRecentConfirmedDTC = 14 Report most recent confirmed DTC NumberOfDTCByStatusMask = 1 Report number of DTC by status mask

182 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

13.30.2.14 UDSType.DTCReadStat

The UDSType.DTCReadStat is used as parameter in the UDS readDTCInformation. class tta.units.uds.UDSType Class for all enums and constants of UDS services class DTCReadStat Class for enums of read diagnostic information status mask Confirmed = 8 Confirmed DTC Pending = 4 Pending DTC TestFailed = 1 Test failed (active/passive) TestFailedSinceLastClear = 32 Test failed since last clear TestFailedThisOpCycle = 2 Test failed this operation cycle TestNotComplete = 16 Test not complete since last clear TestNotCompleteThisOpCycle = 64 Test not completed this operation cycle WarnIndicatorRequested = 128 Warning indicator requested

13.30.2.15 UDSType.InputOutputPar

The UDSType.InputOutputPar is used as parameter in the UDS inputOutputControlByIdentifier. class tta.units.uds.UDSType Class for all enums and constants of UDS services class InputOutputPar Class for enums of input output control parameter types FreezeCurrentState = 2 Freeze current state ResetToDefaultOrInitValues = 1 Reset to default or init values ReturnControlToECU = 0 Return control to ECU ShortTermAdjustment = 3 Short term adjustment

13.30. tta.units.uds 183 TTA Documentation, Release 1.15.2

13.30.2.16 UDSType.InputOutputState

The UDSType.InputOutputState is used as parameter in the UDS inputOutputControlByIdentifier. class tta.units.uds.UDSType Class for all enums and constants of UDS services class InputOutputState Class for enums of input output control state types (first byte) InfiniteTiming = 255 Infinite timing, means permanent control NoTest = 0 Don’t start test

13.30.2.17 UDSType.Routine

The UDSType.Routine is used as parameter in the UDS routineControl. class tta.units.uds.UDSType Class for all enums and constants of UDS services class Routine Class for enums of routine control operation types Request = 3 Request routine (results) Start = 1 Start routine Stop = 2 Stop routine

13.30.2.18 UDSType.DataFormat

class tta.units.uds.UDSType Class for all enums and constants of UDS services class DataFormat Class for enums of data format types (for request download/upload) Compression1 = 16 Compression method 1 (OEM dependend) Compression2 = 32 Compression method 2 (OEM dependend) Compression3 = 48 Compression method 3 (OEM dependend) Compression4 = 64 Compression method 4 (OEM dependend)

184 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Compression5 = 80 Compression method 5 (OEM dependend) Compression6 = 96 Compression method 6 (OEM dependend) Compression7 = 112 Compression method 7 (OEM dependend) Encryption1 = 1 Encryption method 1 (OEM dependent) Encryption2 = 2 Encryption method 2 (OEM dependent) Encryption3 = 3 Encryption method 3 (OEM dependent) Encryption4 = 4 Encryption method 4 (OEM dependent) Encryption5 = 5 Encryption method 5 (OEM dependent) Encryption6 = 6 Encryption method 6 (OEM dependent) Encryption7 = 7 Encryption method 7 (OEM dependent) UnCompressed = 0 No compression of data UnEncrypted = 0 No encryption of data

13.31 tta.units.vector.canoe

This module provides a TTA unit, to access to the CAN Tool CANoe by Vector Informatik.

13.31.1 CANoe unit

The CANoe unit can be used, to control most of the functions provided, by CANoe via the COM automation interface. Currently supported CANoe versions: • 7.2 or newer • 8.x • 9.x • 10.x Newer versions may work as well, but have not been tested yet.

13.31. tta.units.vector.canoe 185 TTA Documentation, Release 1.15.2 class tta.units.vector.canoe.CANoe(config_file_canoe=None, canoe_path=None, close_canoe_on_shutdown=False, stop_measurement_on_shutdown=True) The CANoe Unit provides access to the COM interface of CANoe from Vector. The CANoe configuration and the used CANoe version can be set, when creating the CANOE Unit. The CANoe Version will be registered at the Windows COM Server. Note that administrative rights are required for this. If no canoe_path parameter is set, the CANoe version will be used, that is registered at the COM Server at the moment. Parameters • config_file_canoe (str) – Path to the a CANoe .cfg file to configure CANoe. The last configuration of CANoe will be used if the parameter is omitted. • canoe_path (str) – Path to CANoe executable of the CANoe installation that should be used. The executable is usually located in “Exec32CANoe32.exe” or “Exec64CANoe64.exe”. • close_canoe_on_shutdown (bool) – Close the CANoe application on shutdown (True) or not (False). False by default. call_capl_function(function_name, *args) Call a CAPL function. In order to call the function, the measurement has to be started and the function must have been registered at the CANoe Unit using the “register_capl_function(. . . )” method, before the Measurement was started. Params str function_name Name of the CAPL function. Params obj args Up to 10 positional parameters. Returns Returncode of the function. Return type int close_canoe_on_shutdown(close_on_shutdown) The CANoe application can be closed, when the Unit is shut down. For performance reasons the applica- tion should not be closed. Parameters close_canoe_on_shutdown (bool) – Close the CANoe application on Unit shutdown (True) or not (False) compile_capl() Compiles all CAPL, XML and .NET nodes. exec_com_function(root, attr_list, *args, **kwargs) Do not use this function directly! Execute a COM function using the Unit thread. Parameters • root (COMObject) – Root COM interface/object. If omitted, the CANoe application handle will be used. • attr_list (list) – List of strings representing the attribute sequence that is called starting at root. E.g. [“ObjA”, “Subobj”, “Method”] is generates the call “.ObjA.Subobj.Method(*args, **kwargs)” Returns Return value of the called function. Return type Depends on called function. execute_all_test_modules(test_environment, test_folder_list=None) Execute all activated test modules within the test environment or subfolder consecutively. Note that the

186 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

methods ends immediately. To check the actual execution state, the executed TestModules have to be instantiated directly. Parameters • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional. Returns Report of the test execution. Return type TestReport get_com_obj(root, attr_list) Do not use this function directly! Get a COM sub object/interface using the Unit thread. Parameters • root (COMObject) – Root COM interface/object . If omitted, the CANoe application handle will be used. • attr_list (list) – List of strings representing the attribute sequence that is called starting at root. E.g. [“ObjA”, “Subobj”, “Value”] is generates the call “.ObjA.Subobj.Value” Returns Handle of the COM interface/object. Return type COMObject get_configuration() Returns the actual loaded configuration. Returns Path to the loaded CANoe .cfg file Return type str get_diag(network, device) Return a handle for the specific diagnostic layer of the ECU. Parameters • network (str) – Network to send diagnostic messages on E.g. “CAN” • device (str) – Name of the ECU get_environment_var(env_var_name) Return a handle for a specific environment variable. Values can be accessed using the the handle’s “Value” attribute. Parameters env_var_name (str) – Name of the environment variable. Returns Handle for an environment variable. Return type EnvVariable get_node(node_name) Return a handle for a specific node. Values can be accessed using the the handle’s “Value” attribute. Examples node_object = canoe_unit.get_node(“Motor”) Parameters str – Name of the Node

13.31. tta.units.vector.canoe 187 TTA Documentation, Release 1.15.2

get_responses(request) Returns a list of all responses related to a given request object. Parameters CANoeRequest – Diagnostic Request get_signal(bus, channel, msg_name, signal_name) Return a handle for a specific signal. Values can be accessed using the the handle’s “Value” attribute. Note that most signals are read only. Examples signal_object = canoe_unit.get_signal(“CAN”, 2, “MyCANMsgName”, “MySignalName”) signal_object = canoe_unit.get_signal(“FlexRay”, 1, “MyFRMsgName”, “MyFRSignalName”) Parameters • bus (str) – Name of the bus. E.g. “CAN”, “Lin”, “FlexRay” • channel (int) – Number of the channel. Starting at 1. • msg_name (str) – Name of the message (see Database files for details) • signal_name (str) – Name of the signal within the message (see Database files for details) Returns Handle for the signal. Return type CANoeSignal get_system_var(sys_namespaces, sys_var_name) Return a handle for a specific system variable. Values can be accessed using the the handle’s “Value” attribute. The variables can only be accessed, if they belong to a namespace. Parameters • sys_namespaces (str) – Name of the namespace containing the variable (e.g. “Gen- eral”) or list of stings if there are several nested namespaces (e.g. [“_Statistics”, “CAN1”]) • sys_var_name (str) – Name of the system variable. Returns Handle for a system variable. Return type SysVariable get_test_module(test_environment, test_folder_list, test_module) Return a handle for a specific test module. Parameters • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional. • test_module (str) – Name or index (int) of the test module. Returns Test module handle. Return type TestModule get_test_report(test_environment, test_folder_list=None) Returns the test report object of a node within the test setup (test_environment and/or subfolder). To access the test report of an TestModule, use the “Report” property of the TestModule object instead. Parameters

188 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

• test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional. Returns TestReport of the test environment or folder Return type TestReport get_test_setup_node_state(test_environment, test_folder_list=None, test_module=None) Get the activation state of a node (TesEnvironment, Folder or TestModule) within a Test Setup. Parameters • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional. • test_module (str) – Name or index (int) of the test module. Parameter is optional. Returns True if active, otherwise False Return type bool measurement_running() Is the measurement running. Returns True, if measurement is running. Otherwise False Return type bool open_configuration(config_file_canoe) Open a CANoe configuration. Parameters config_file_canoe (str) – Path to the a CANoe .cfg file to configure CA- Noe. register_capl_function(function_name) Registers an existing CAPL function, so that this function can be called using the CANoe Unit while the Measurement is started. The Measurement has to stopped to register the function, as the function handle has to created on Measurement start. Parameters function_name (str) – Name of the CAPL function to be registered. register_event_callback(com_object, callback_class) Register a class at a COM object supporting callbacks. The class has to implement the methods that are called by the COM server (e.g. “OnChange(self, value)” for CANoe Variable objects). See the manufac- turers COM reference for further details. Parameters • com_object (COMObject) – COM Object that triggers the callback • callback_class (classobj) – Class implementing the required callback method(s). Returns EventProxy representing the created callback_class instance. Return type win32com.client.EventsProxy set_com_property(root, attr_list, new_value) Do not use this function directly! Set a COM Property in Unit thread. Use get_com_obj() the read the property.

13.31. tta.units.vector.canoe 189 TTA Documentation, Release 1.15.2

Parameters • root (COMObject) – Root COM interface/object. If omitted, the CANoe application handle will be used. • attr_list (list) – List of strings representing the attribute sequence that is called starting at root. E.g. [“ObjA”, “Subobj”, “PropA”] is generates the call “.ObjA.Subobj.PropA = new_value” • new_value (obj) – Value that should be assigned to the property. The type depends on the property. set_test_setup_node_state(active, test_environment, test_folder_list=None, test_module=None) Set the activation state of a node (TesEnvironment, Folder or TestModule) within a Test Setup. Parameters • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional. • test_module (str) – Name or index (int) of the test module. Parameter is optional. • active (bool) – True to activate activate, False to deactivate start_measurement(timeout=90.0) Start the measurement or simulation. Parameters timeout (float) – Timeout in seconds the unit will wait till the measurement is started. (Default 90.0) Raises TimeoutError stop_measurement(timeout=90) Stop the measurement or simulation. Parameters timeout (float) – Timeout in seconds the unit will wait till the measurement is stopped. (Default 90.0) Raises TimeoutError stop_measurement_on_shutdown(stop_measurement_on_shutdown) The CANoe application can be closed, when the Unit is shut down. For performance reasons the applica- tion should not be closed. Parameters close_canoe_on_shutdown (bool) – Close the CANoe application on Unit shutdown (True) or not (False) stop_sequence(test_environment, test_folder_list=None) Stop all running test modules within the test environment or subfolder. Note that the methods ends imme- diately. To check the actual execution state, the executed TestModules have to be instantiated directly. Parameters • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup) • test_folder_list (str) – Name or index (int) of the subfolder. Paths are repre- sented by lists of names and indices. Parameter is optional.

190 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

unregister_capl_function(function_name) Unregisters an existing CAPL function, so that no handle is created for this function on Measurement start anymore. Parameters function_name (str) – Name of the CAPL function to be unregistered.

13.31.2 Executing CAPL Functions

To run a CAPL function from TTA you need to configure your simulation first. Here you need to click on a node of your choice and enter the CAPL Browser. Alternatively you can also create a new one dedicated to the communication with TTA and write your wrappers in there. After that we now have to define wrapper functions we can later access from out TTA environment.

Now that we have created a wrapper that we can access from the COM interface it is time to register this CAPL function so we can later call it, this is done through the method register_capl_function(“set_klemme”). After starting the simulation via start_measurement() we are now able to run the previously registered function with the command call_capl_function(“set_klemme”) this will call the wrapper function seen in the picture above and switch on the environmental variable for clamp 15 to 1.

13.31.3 CANoeNode - Using Nodes

Nodes can be activated or deactivated by setting the .Active property to True/False Example usage:

from tta.units.vector import canoe

c= canoe.CANoe() node=c.get_node("Motor") # Get handle for node object node.Active= False # Turn off node

13.31. tta.units.vector.canoe 191 TTA Documentation, Release 1.15.2

class tta.units.vector.canoe.CANoeNode(canoe_unit, node_name) Helper class for accessing Nodes. The objects behave like the Node COM interface. Parameters bus (str) – Name of the node. E.g. “Motor”, “Diagnose”, “Klemmenstatus” Active Determines the status of the CAPL node. Returns Current state of the node Return type bool DriftJitter Sets the min/max value of the drift/jitter (even distribution) in %. DriftJitterActive State of the drift/jitter of the current node. Returns State of DriftJitter Return type bool FullName Sets or determines the complete path of the object. For most objects, this property is read-only. Returns Full Name of the node Return type str Name The name of the CAPL node; it may differ from the file name. Returns Node Name Return type str StartDelay Returns a value for the start delay. Returns Current start delay in ms Return type int StartDelayActive Returns state of the start delay. Returns Start Delay State Return type bool

13.31.4 CANoeDiagnostic - Using the Diagnostic Module

The CANoe Unit can also be used to access the DiagnosticConsole and send DiagnosticRequests through CANoe. Access Diagnostics and send Request:

from tta.units.vector import canoe

c= canoe.CANoe() diag=c.get_diag("CAN","BV_HeadUpDisplUDS") # Get Diagnostic Handle diag.TesterPresentStatus= True # Turn on cyclic sending of TesterPresent req= diag.create_request("DiagnServi_DiagnSessiContrDefaultSessi") # Create Request diag.send_request(req) # Send Request

192 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Furthermore you can adjust the request parameters, herefore you will need the qualifier associated with your parameter and the value you want to set. The qualifier can be found in the DiagnosticConsole of CANoe, if it isnt displayed by default you can go to Properties and add Parameter Qualifier to the displayed columns. As seen in the screenshot below.

Parameters can be set as following: diag.change_parameter(req,"Knockout_Counter_ECUKnockOutCtr",2) # Change Parameter

˓→ECUKnockOutCtr diag.send_request(req) # Send Request

class tta.units.vector.canoe.CANoeDiagnostic(canoe_unit, network, device) Helper class for accessing the diagnostic Layer. The objects behave like the Node COM interface. param str network Network to send diagnostic messages on E.g. “CAN” param str device Name of the ECU E.g. “BV_HeadUpDisplUDS” TesterPresentStatus Status if TesterPresent gets sent Returns TesterPresent on/off Return type bool change_parameter(request, qual, value) Change Parameter of DiagnosticRequest Parameters • request (COMRequestObject) – Previously created RequestObject (returnvalue of create_request()) • qual (str) – Qualifier of the Parameter

13.31. tta.units.vector.canoe 193 TTA Documentation, Release 1.15.2

• value – New Paramter Value create_request(value) Creates a request object Parameters value (str) – Name of the diagnostic message E.g. “Di- agnServi_DiagnSessiContrDefaultSessi” send_request(req) Sends a request object Parameters CreateRequest> req (

13.31.5 CANoeSignal - Using Signals

Bus signals can be read, using CANoeSignal objects. Use the get_signal() method of the CANoe Unit, to create CANoeSignal objects.

class tta.units.vector.canoe.CANoeSignal(canoe_unit, bus, channel, msg_name, sig- nal_name) Helper class for accessing Signals. The objects behave like the Signal COM interface. Use the CANoe Unit method “get_signal(. . . )” to avoid creating unnecessary objects. Parameters • canoe_unit (CANoe) – CANoe unit, which should be used to access the Environment- Variable • bus (str) – Name of the bus. E.g. “CAN”, “Lin”, “FlexRay” • channel (int) – Number of the channel • msg_name (str) – Name of the message (see Database files for details) • signal_name (str) – Name of the signal within the message (see Database files for details) FullName The fully qualified name of a signal or a message. Format :::: Returns The name of the variable. Return type str IsOnline Signal received during running measurement. Returns True, if the measurement is running and the signal has been received. False, if not. Return type bool RawValue Returns the raw value of the signal. State Returns the state of the signal. Returns (0) Default value.

194 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

(1) Measurement not running and value set by application. (2) Measurement not running and value has state of the last measurement. (3) Current value from running measurement. Return type int Value The value of the Signal. In order to set the value of a signal an “interaction layer” has to be set in the Simulation Setup. See the CANoe manual for details.

13.31.6 EnvVariable - Accessing Environment Variables

Reading and writing Environment Variables are provided, by the EnvVariable objects. Use the get_environment_var() method of the CANoe Unit, to create EnvVariable objects. class tta.units.vector.canoe.EnvVariable(canoe_unit, var_name) Helper class for accessing Environment Variables. The objects behave like the EnvironmentVariable COM interface. Use the CANoe Unit method “get_environment_var(. . . )” to avoid creating unnecessary objects. Parameters • canoe_unit (CANoe) – CANoe unit, which should be used to access the Environment- Variable • var_name (str) – Name of the EvnironmentVariable NotificationType The notification type of the EnvironmentVariable object Returns cValue(0), cValueAndTime(1), cValueAndTimeU(2) Return type int Type The type of the EnvironmentVariable object Returns Integer(0), Float(1), String(2), Data(3) Return type int Value The value of the EnvironmentVariable object. trigger_event_on_change(create_event=True) Trigger an Event in the CANoe Unit if the variable changes. The new value and a reference to this object can be accessed as dictionary via the Events “value” attribute. Example new_value = event.value[“new_value”] variable_object = event.value[“var_obj”] Parameters create_event (bool) – True, if Events should be triggered. False, if not.

13.31. tta.units.vector.canoe 195 TTA Documentation, Release 1.15.2

13.31.7 SysVariable - Accessing System Variables

Reading and writing System Variables are provided, by the SysVariable objects. Use the get_system_var() method of the CANoe Unit, to create SysVariable objects. class tta.units.vector.canoe.SysVariable(canoe_unit, sys_namespaces, var_name) Helper class for accessing System Variables. The objects behave like the Variable COM interface. Use the CANoe Unit method “get_system_var(. . . )” to avoid creating unnecessary objects. Parameters • canoe_unit (CANoe) – CANoe unit, which should be used to access the Environment- Variable • sys_namespaces (str) – Name of the namespace containing the variable (e.g. “Gen- eral”) or list of stings if there are several nested namespaces (e.g. [“_Statistics”, “CAN1”]) • var_name (str) – Name of the EvnironmentVariable AnalysisOnly The variable shall be used only for analysis purposes. Returns True - variable shall be used only for analysis purposes. Otherwise False. Return type bool Comment The comment for the variable. GetMemberPhysValue(member_name) The current physical value of the member. GetMemberValue(member_name) The current value of the member. GetSymbolicValueName(member_name) The symbolic name for the value, if there is one defined. Else an empty string. Returns The symbolic name for the value, if there is one defined. Else an empty string. Return type str MaxValue The maximum value of the variable. MinValue The minimum value of the variable. Name The name of the variable. Returns The name of the variable. Return type str NotificationType The notification type of the Variable object Returns cValue(0), cValueAndTime(1), cValueAndTimeU(2) Return type int

196 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

ReadOnly Check, if variable is read only. Returns If the object is write protected True is returned. Otherwise False is returned. Return type bool SetMemberPhysValue(member_name, value) Set the current physical value of the member. SetMemberValue(member_name, value) set the current value of the member. SetSymbolicValueName(member_name, new_name) Set the symbolic name for the value. Parameters new_name (str) – New symbolic value name. Type The type of the Variable object. Returns Type as number. 65535 if invalid. Return type int Value The value of the Variable object. trigger_event_on_change(create_event=True) Trigger an Event in the CANoe Unit if the variable changes. The new value and a reference to this object can be accessed as dictionary via the Events “value” attribute. Example new_value = event.value[“new_value”] variable_object = event.value[“var_obj”] Parameters create_event (bool) – True, if Events should be triggered. False, if not.

13.31.8 TestModule, TestReport - Running CANoe Test Cases

The CANoe Unit can run CANoe test cases. Use the get_test_module() method of the CANoe Unit, to create TestModule objects. The reports of executed test cases are represented by TestReport objects. These can be accessed, via the “Report” property of the TestModule objects. If several Test Modules of a CANoe Test Setup should be executed, use the CANoe Unit methods execute_all_test_modules() to start and stop_sequence() to the execution of a specific Test Envi- ronment (or of a sub folder within the Test Environment). The get_test_report() method can be used, to retrieve the report of the execution. class tta.units.vector.canoe.TestModule(canoe_unit, test_environment, test_folder_list, test_module) Helper class for accessing Test Modules. The object provides a subset of the corresponding COM objects functions. Use the CANoe Unit method “get_test_module(. . . )” to avoid creating unnecessary objects. Parameters • canoe_unit (CANoe) – CANoe unit, which should be used to access the TestModule • test_environment (str) – Name or index (int) of the test environment (top level node of Test Setup)

13.31. tta.units.vector.canoe 197 TTA Documentation, Release 1.15.2

• test_folder_list (list) – str or list of str containing the path to the test module • test_module (str) – Name or index (int) of the test module FullName Full path to the CAPL program or the XML test module, that is used by the test module. Name Name of the TSTestModule CANoe object. Pause() Pauses the test execution. Reload() Reloads the XML test specification. Only for XML test modules. Report TestReport object. Resume() Resumes the paused test module execution. Start(wait_till_finished=True) Executes the test module. Note that the measurement has to be started first, in order to execute a test. Params bool wait_till_finished Wait till the test module execution finished. Default True. Oth- erwise the actual state of the test module has to be check manually by calling the get_state() method. Returns Result of the TestModule execution. If ‘wait_till_finished’ parameter is set to False, ‘None’ will be returned. Possible results are: 0 - Testmodule executed completely 1 - User abortion 2 - General Error (e.g. measurement stop) Return type int or None Stop() Stops a running test module execution. TestVariant Name of the currently active variant. Only valid for XML test modules. VerdictImpact Behavior of a test module when a test case or test pattern fails. get_child_state(path_to_child) Check, if a child obejct (TestSequence or TestCase) of the TestModule is activated. Params list path_to_child List containing the name or index (int) of the child. Returns Is child enabled Return type bool get_state() Returns the actual state of the test module. For details see the STATE_* constants of the TestModule class. Returns Acutal state. Possible values: STATE_IDLE, STATE_RUNNING, STATE_PAUSED Return type int get_testcase_verdict(path_to_testcase) Returns the result of the execution of a TestCase within the TestModule. The TestModule must be executed before calling this function. Use the TestModule VERDICT_* constants to check the result. Params list path_to_child List containing the name or index (int) of the TestCase.

198 Chapter 13. TTA Units Reference TTA Documentation, Release 1.15.2

Returns Verdict of the TestCase. Return type int set_child_state(path_to_child, enabled) Check, if a child obejct (TestSequence or TestCase) of the TestModule is activated. Params list path_to_child List containing the name or index (int) of the child. Params bool enabled True to enable, False to disable. class tta.units.vector.canoe.TestReport(canoe_unit, report_com_obj) Helper class for accessing TestReports. The objects behave like the TestReport COM interface. Use the CANoe Unit method “get_test_report(. . . )” for test environments or folders or the TestModules “Report” property to avoid creating unnecessary objects. Instantiating directly may cause errors. Parameters • canoe_unit (CANoe) – CANoe unit, which should be used to access the TestReport • report_com_obj (COMObject) – Handle of the TestReport COM object. FullName The complete path of the test report. GenerateReport(wait_till_finished=True) Generates the report. If the report is generated asynchronously, use the “report_generated()” oder “wait_for_generation()” method to check, if the generation finished. Params bool wait_till_finished The method will wait, till the report has been generated if True. LastWrittenFullName The complete path of the alst wirtten test report. Name The file name of the test report. Without path and file name extension. get_last_generation_status() Returns the status of the last generation as dictionary. The following keys are available: • success: True if the HTML report has been generated successfully. • sourceFullName: Absolute path to the XML report. • generatedFullName: Absolute path to the HTML report.

Returns Dictionary containing the status of the last report generation. None if no report has been generated yet. Return type dict

report_generated() Is report already generated. Returns Yes (true) or no (False) Return type bool wait_for_generation() Waits till report is generated. Will return immediately, if the report has already been generated.

13.31. tta.units.vector.canoe 199 CHAPTER FOURTEEN

HOW TO CREATE A TTA UNIT?

If a test developer needs to adapt new hardware, special software interfaces or applications it might be necessary to have access to deeper levels of TTA. The most functionality of those levels can be used from within units.

14.1 Unit capabilities

The Unit is the basic software component in TTA for integrating respectively interfacing hardware devices and soft- ware services. It offers already some functionalities which are useful for a software developer: • Configuration management • Logging management • Thread-safety for methods • Event dispatching Apart from that, the unit manager tries to handle units as singletons (variant: mono-state) whenever possible. This means that if you instantiate a unit with the same parameter configuration (arguments), you will get a new reference to the same unit object. This is useful if accessing hardware or services based on single network connections, for example. Additionally, as the methods of the unit can be defined to be thread-safe, the same object can be shared among different threads without having to care about concurrency issues. All this is done by the unit manager in background automatically, the user does not have to care about configuring this. For a developer there are mostly API functions to have easy access to the unit capabilities.

14.1.1 Unit usage

Units are handled automatically by the unit manager. On instantiation the unit invokes the unit manager and registers itself. If you want to shut down/close a unit call the unregister method. This signals the unit manager that you do not need your unit anymore. If a unit is not needed by anyone anymore, the unit manager will shut down it completely (shutting down the instance behind the singleton). Example: my_unit= MyUnit() # Instatiate unit, unit manager will handle it my_unit.unregister() # Unregister unit, unit manager will unregister or/and shut

˓→down if last instance

200 TTA Documentation, Release 1.15.2

14.1.2 Unit configuration

You can save any argument configuration of your unit into the appropriate config YAML files (like default_config.yaml etc.). If you instantiate your unit, missing arguments will be filled from this configuration. Example: Given a unit named “MyFirstUnit” with arguments “foo” and “bar” you can enter the default values under the section “Units”:

Units: MyFirstUnit: default: foo: 102 bar:"Hello World"

Instantiation: myunit1= MyFirstUnit() # equivalent to: MyFirstUnit(foo=102, bar="Hello

˓→World") myunit2= MyFirstUnit(foo=250) # equivalent to: MyFirstUnit(foo=250, bar="Hello

˓→World") myunit3= MyFirstUnit(bar="test") # equivalent to: MyFirstUnit(foo=102, bar="test)

Note: Every unit configuration needs a “default” section (mandatory).

14.1.3 Unit logging

Every unit gets a dedicated logger when an instance is created. It can be accessed by the self._logger attribute. Logs will be duplicated into a separate log file named like the unit. Example: val= 23 self._logger.debug("value(raw) = %s, value(calc.) = %s", val, val * 100+ 80)

14.1.4 Thread-safe access to unit methods: async_func decorator

Usually it is recommended that a unit method is decorated with the “async_func” decorator. This will ensure that any call of the method from different threads will be handled thread-safe. You can omit the decorator, if you are sure that your method is implemented in a way where thread-safety is not needed (e. g. isolated static method). If you are in doubt whether your method might cause unwanted side effects in a multi-threading context, you should always use async_func. Example: The following example will show a unit definition for a step motor class. Here, incr_step() can be accessed from any thread. It will be ensured that the method execution won’t be intercepted from other calls to methods decorated with “async_func”. Thus, in this example, there will be no call between increasing the step_counter and moving the step motor: from tta.core.unit_base import UnitBase, async_func

(continues on next page)

14.1. Unit capabilities 201 TTA Documentation, Release 1.15.2

(continued from previous page) def StepMotor(UnitBase): def __init__(self, init_val): self.step_counter= init_val self._init_step_motor()

@async_func def incr_step(self, step): # invocation of this method is thread-safe self.step_counter+= step self._move_step_motor(step) ...

14.1.5 Making the unit dispatch events

If a developer wants to continuously dispatch events coming from a device or interface, he can do so by calling self._trigger_event(). The unit base class already provides functions for adding and removing EventSource objects. Therefore, calling self._trigger_event() with an Event object as argument, the underlying event management will automatically dispatch those events to the currently added event sources. Example: In this example the developer wants a unit to wait for some trace data coming from e. g. a DLL and wants to dispatch it to all added event sources. The unit just initializes the DLL and converts the data from the callback into a TraceMessage object defined before. The TraceMessage object converts some fields like timestamp and content: import datetime from tta.core.unit_base import UnitBase def TraceMessage(): def __init__(self, number, timestamp, content): self.number= number self.timestamp= datetime.datetime.fromtimestamp(timestamp) # seconds since

˓→1970 self.content= content.decode("latin-1") # decode from latin-1 def TraceSerial(UnitBase): def __init__(self): UnitBase.__init__(self) self.dll= self._init_dll_interface() self.dll._register_callback(self._receive_trace_messages)

def _receive_trace_messages(number, timestamp, content): message= TraceMessage(number, timestamp, content) self._trigger_event(Event(message)) ...

14.2 Implementing a complete unit

When implementing a unit, the developer can make use of the aforementioned capabilities. Apart from that there are some things to consider.

202 Chapter 14. How to create a TTA unit? TTA Documentation, Release 1.15.2

14.2.1 Define, initialize, shut down and add methods

Every unit has to inherit the UnitBase class. On initialization it has to init the UnitBase parent first. A unit also is responsible to offer a _shutdown method the unit manager can call if the unit should be closed. In _shutdown any components used should be shut down/closed if it is necessary or useful. After clean up the _shutdown of UnitBase parent should be called. Regarding the methods of your unit, think about if you need thread-safety and generally use the async_func decorator if you are in doubt (see Thread-safe access to unit methods: async_func decorator). Example: Typical unit implementation example: from tta.core.unit_base import UnitBase, async_func def MyUnit(UnitBase): def __init__(self, foo, bar): UnitBase.__init__(self) # Init UnitBase first(!) self.foo= foo self.bar= bar self.connection= ServerConnect(("127.0.0.1", 4000), foo)

@async_func def set_bar(self, new_bar): bar= self.connection.get_bar() if new_bar != bar: self.connection.put_bar(new_bar) self.bar= new_bar ... def _shutdown(self): self.connection.close() UnitBase._shutdown(self) # Shut down UnitBase last(!)

Note: On initialization UnitBase.__init__(self) has to be the first and on shutdown UnitBase._shutdown(self) has to be the last statement. The _shutdown method must be always defined.

14.2.2 Use other units in your unit

You can use other units in your unit as components, e. g. assign them to attributes. Usage is like in regular test cases or python scripts. So just instantiate them in the __init__ method and unregister them in the _shutdown method. Just think about that if instantiation fails, you might want to unregister other units already successfully instantiated. This is useful if you want to restart your unit in case of errors (e. g. unreliable hardware or services related to the device under test). On the other hand, if you want any exception in the test case to abort it immediately and you do not intend to catch unit initialization exceptions, you do not need to clean up. At the end of every test case script all units will be shut down. Example: Here is an example of handling used units if you want to recover unit functionality by restarting it several times due to unreliable conditions. Then it is recommended to catch exceptions during initialization and shutdown. This would avoid having orphaned and unused units around.

14.2. Implementing a complete unit 203 TTA Documentation, Release 1.15.2

from traceback import print_exc from tta.core.exception import TTAUnitInitError from tta.core.unit_base import UnitBase def MyUnit(UnitBase): def __init__(self, foo): UnitBase.__init__(self) # Init UnitBase first(!) self.foo= foo self.other_unit1= None self.other_unit2= None init_success= True try: self.other_unit1= MyOtherUnit1() self.other_unit2= MyOtherUnit2() except (TTAUnitInitError, TypeError) as exc: # We got problem -> clean up init_success= False if not init_success: self._shutdown_units() raise exc ... def _shutdown_units(): # This method is useful during init and shutdown for unit_used in [self.other_unit1, self.other_unit2]: try: if unit_used and unit_used.is_alive(): unit_used.unregister() except BaseException: print_exc()

def _shutdown(self): self._shutdown_units() UnitBase._shutdown(self) # Shut down UnitBase last(!)

Note: If using other units in your unit you should take care about cleaning up the units yourself.

204 Chapter 14. How to create a TTA unit? CHAPTER FIFTEEN

TTA CORE REFERENCE

The TTA Core reference describes TTA’s core components.

15.1 tta.core.config_manager

This module contains the implementation of TTA’s config manager class. Copyright (C) MAGNA Telemotive GmbH exception tta.core.config_manager.ConfigEntryMissingError This error will be raised when the requested config entry is missing. exception tta.core.config_manager.ConfigEntryTypeError This error will be raised when a sub value of a config entry which is not a dictionary is requested. exception tta.core.config_manager.ConfigInvalidError This error will be raised when the configuration is invalid. class tta.core.config_manager.ConfigManager Central Configuration object for reading and merging config files and access to this config information. _ConfigManager__get_unit_config_set(unit_name) return the name of the unit config :param unit_name: requested unit :type unit_name: str static _recursive_dict_merge(base_data, new_data) Merge data from one dictionary into another. This method merges the data from one dictionary into another. The original dictionaries will be unaffected. A new result dictionary will be created and returned. If both dictionaries contain data for the same key, the data from new_data is used. Parameters • base_data (dict) – Dictionary containing data to which new_data will be merged. • new_data (dict) – Dictionary containing the data that will be merged into base_data Returns A new dictionary containing the merged data. Return type dict _set_config(new_data) Sets config dictionary . Not for official use! For testing purposes only! Parameters new_data (dict) – config dict to be set _set_unit_config(unit_name, unit_config, config_set_key=’default’) Sets config dictionary for specified TTA Unit. Not for official use! For testing purposes only!

205 TTA Documentation, Release 1.15.2

Parameters • unit_name (str) – Name of TTA Unit to get config for. • unit_config (dict) – Config dictionary to set add_config_dict(dict_new, description=’’) Add data from a dictionary to this config Parameters • dict_new (dict) – config data dict • description (str) – optional description of ths config change add_config_file(str_filename) Add data from a yaml file to this config. This method loads the specified yaml file and adds the containing config data to the current configuration. Parameters str_filename (str) – YAML filename to read and add. Raises ConfigInvalidError – If file content violates YAML format static get_config_folder() Get the folder for config files. Returns Path to config folder Return type str get_config_sources() get a list of all contributors to the current config data set Returns config sources Return type list get_entry(*args) Returns a config value. This method returns the config value specified with the arguments. E.g.:

get_entry("units","CAN","bitrate")

Parameters args – List of entry keys to the entry you want to get Returns Requested value Raises • ConfigEntryMissingError – If current config has no entry • ConfigEntryTypeError – If config entry is not of type dict

get_unit_config(unit_name, config_set_name=None) Returns config dictionary for specified TTA Unit. Parameters unit_name (str) – Name of TTA Unit to get config for. Returns Dictionary containing Unit configuration Return type dict static get_workspace_folder() Return workspace folder

206 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

Returns Path to workspace folder Return type str reset_config() bring the ConfigManager back to the initial state set_locked(bool_state) set lock state of the ConfigManager and prevent further add_config_XYZ() actions Parameters bool_state (bool) – new lock state to_yaml() debug function: return config data as yaml string Returns config data Return type str validate() check config settings Raises ConfigEntryMissingError: if root elements “Units”, “config_sets” , . . . are missing Raises ConfigEntryTypeError: if root elements are not a dict Raises SelectedConfigSetsInvalidError: if multiple/ no valid ConfigSets are selected Raises ConfigInvalidError: if invalid Unittnames/ ConfigNames are used exception tta.core.config_manager.ConfigManagerLockedError This error will be raised when editing a already locked ConfigManager exception tta.core.config_manager.SelectedConfigSetsInvalidError This error will be raised when entries in the “config_sets_selected:” tree are invalid. tta.core.config_manager._get_config_folder() Get config folder tta.core.config_manager._get_workspace_folder() Get workspace folder tta.core.config_manager.get_current_config_manager() Get config manager object and start if it doesn’t exist yet Returns Globally set config manager Return type ConfigManager

15.2 tta.core.config_units.generate

This module contains the generator code for creating code-completion-compatible entry point for configured units Copyright (C) MAGNA Telemotive GmbH class tta.core.config_units.generate.Generator(config_manager, output_folder=None) generate Python code from existing Units and Config settings Parameters • config_manager (config_manager.ConfigManager) – config manager with config settings • output_folder (str) – root folder for new generated code

15.2. tta.core.config_units.generate 207 TTA Documentation, Release 1.15.2

generate(units_list=None) generate a py file with config set entries from config_manager for code completion :param filename: :type filename: :param config_manager: :type config_manager: static make_empty_init(folder) create a folder and a empty __init__ file at folder :param folder: folder :type folder: str

15.3 tta.core.context

This module contains TTA’s Context class which provides a complete execution context handling TTA’s lifecycle. Copyright (C) MAGNA Telemotive GmbH class tta.core.context.Context(name=None) TTA’s execution context handles the whole lifecycle for configuration, logging, units. Parameters name (str) – Context name. Omit for default name. end_lifecycle() End the current TTA lifecycle. Raises TTAContextError – When there is no active lifecycle get_name() Get context name. Returns Context name Return type str get_seq_number() Get context sequence number within a test sequence. Returns Context sequence number Return type int get_start_time() Context’s start time. Returns Current start time Return type datetime is_active() Check if there is an active lifecycle in the context. Returns True if there is an active lifecycle Return type bool set_name(name=None) Change the context’s name. This new name will be applied to the logger configuration on the new lifecycle. Parameters name (str) – New context name. Omit for default name. set_next_lifecycle_name(lifecycle_name=None) Set the name for the next lifecycle that will be started using ‘with context:’. The logger will be configured accordingly. context = Context() context.set_next_lifecycle_name(“my_lifecycle”) with context:

208 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

equals context = Context() context.start_lifecycle(“my_lifecycle”) context.end_lifecycle() Parameters lifecycle_name (str) – Lifecycle’s name. If specified, the logger will use this name to determine the output path. If not specified, main module name will be used instead. set_seq_number(num) Set context sequence number within a test sequence. Parameters name (int) – New sequence number. set_start_time(start_time) Change the context’s start time. This new start time will be applied to the logger configuration on the new lifecycle. Parameters start_time (datetime) – New context start time. Omit for default time (date- time.now()) start_lifecycle(lifecycle_name=None, runtype=None) Start a TTA lifecycle and configure the logger accordingly. Parameters lifecycle_name (str) – Lifecycle’s name. If specified, the logger will use this name to determine the output path. If not specified, main module name will be used instead. Raises TTAContextError – When there’s already an active lifecycle with_name(lifecycle_name=None) Same as context.set_next_lifecycle_name(lifecycle_name). Additionally returns context object itself. By calling the context object, the with-statement-usage can be enriched by providing a name for the lifecycle: context = Context() with context.with_name(“my_lifecycle”): equals context = Context() context.set_next_lifecycle_name(“my_lifecycle”) with context:

Parameters lifecycle_name (str) – Lifecycle’s name. If specified, the logger will use this name to determine the output path. If not specified, main module name will be used instead. Returns Context object itself Return type Context class tta.core.context.RunType Type of test runnable TestCase = 0 TestCase type: single testcase run TestSuite = 1 TestSuite type: multiple runs with multiple testcases TestSuiteSimple = 2 TestSuiteShort type: multiple runs with same testcase

15.3. tta.core.context 209 TTA Documentation, Release 1.15.2

15.4 tta.core.event.event

This module contains the base Event class of TTA’s event system. Copyright (C) MAGNA Telemotive GmbH class tta.core.event.event.Event(value, timestamp=None, source=None, times- tamp_device=None) Base class for all events in TTA Parameters • value – The value of the event. • timestamp (datetime) – Event’s timestamp. If None, current timestamp will be used. • source (EventSource) – EventSource that created this Event class tta.core.event.event.SourceIsClosed(value, timestamp=None, source=None, times- tamp_device=None) Internal Event used when an EventSource is being closed. Parameters • value – The value of the event. • timestamp (datetime) – Event’s timestamp. If None, current timestamp will be used. • source (EventSource) – EventSource that created this Event

15.5 tta.core.event.filter

This module contains the base EventFilter class of TTA’s event system. Copyright (C) MAGNA Telemotive GmbH class tta.core.event.filter.CombinedEventFilter(*args) Abstract class. Can combine any amount of EventFilter instances. This is a common base class for all the implementations of different combined filters. In order to be accepted an event must be accepted by all filters being combined. I.e. a CombinedEventFilter combines single filters with logical AND. CombinedEventFilter’s constructor accepts any amount of EventFilter instances to be combined. Parameters args (list) – One or more Eventfilters Raises TypeError – If one of args is not of type EventFilter accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool

210 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation class tta.core.event.filter.CombinedEventFilterAnd(*args) Can combine any amount of EventFilter instances with logical AND. In order to be accepted an event must be accepted by all filters being combined. CombinedEventFilter’s constructor accepts any amount of EventFilter instances to be combined. Parameters args (list) – One or more Eventfilters Raises TypeError – If one of args is not of type EventFilter accept(event) Decides whether to accept or decline an event. Only accepts an event if all combined event filters accept it. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool class tta.core.event.filter.CombinedEventFilterOr(*args) Can combine any amount of EventFilter instances with logical OR. In order to be accepted an event must be accepted by at least one of the filters being combined. CombinedEventFilter’s constructor accepts any amount of EventFilter instances to be combined. Parameters args (list) – One or more Eventfilters Raises TypeError – If one of args is not of type EventFilter accept(event) Decides whether to accept or decline an event. Accepts an event if at least one of the combined event filters accepts it. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool class tta.core.event.filter.CombinedEventFilterXor(filter_a, filter_b) Can combine two EventFilter instances with logical XOR. In order to be accepted an event must be accepted by at exactly one of the filters being combined. Parameters • filter_a (EventFilter) – First filter to combine • filter_b (EventFilter) – Second filter to combine accept(event) Decides whether to accept or decline an event. Accepts an event if at least one of the combined event filters accepts it. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool

15.5. tta.core.event.filter 211 TTA Documentation, Release 1.15.2 class tta.core.event.filter.EventFilter Abstract class. Base class defining the interface for event filters. TTA Units can provide different event filter implementations. accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation class tta.core.event.filter.InvertedFilter(filter_) Inverts an EventFilter. Inverts the accept() decision of an EventFilter. Parameters filter (EventFilter) – EventFilter instance to be inverted Raises TypeError – If filter is not of type EventFilter accept(event) Decides whether to accept or decline an event. Accepts an event if the event filter declines it. Parameters event (Event) – Event to be checked by the filter Returns True if the event is declined Return type bool class tta.core.event.filter.TypeFilter(inst_type=None) Event filter for object types Parameters inst_type (obj) – Type to match (see syntax of isinstance), can be tuple/list to match multiple types accept(event) Decides whether to accept or decline an event. This function is called for every incoming event. EventFilter implementations must override this function and evaluate if the event is accepted by the filter (i.e. if the event passes the filter). If the event is accepted, the function must return True, if not, the function must return False. Parameters event (Event) – Event to be checked by the filter Returns True if the event is accepted Return type bool Raises NotImplementedError – If accept method is not overloaded by EventFilter imple- mentation

212 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

15.6 tta.core.event.source

This module contains the implementation of the EventSource class of TTA’s event system. Copyright (C) MAGNA Telemotive GmbH class tta.core.event.source.CombinedEventSource(event_sources, filter_=None) This class implements an EventSource which combines any amount of EventSources. Parameters • event_sources (EventSource) – List of EventSource objects to combine. • filter (EventFilter) – Filter to be applied to this EventSource Raises TypeError – if one element of event_sources is not of type EventSource close(reason=’EventSource.close() was called explicitly.’) Closes the EventSource After calling close, no Events will be emitted by this instance of EventSource. on_eventsource_closed(event) Invoked once when the observed EventSource is closed Parameters event (Event) – received event on_message(event) Invoked every time a normal Event is put into the source EventSoures Parameters event (Event) – Received event class tta.core.event.source.CounterEventSource(event_source, max_events) This class implements an EventSource which will close itself after receiving a specified amount of events from its base EventSource. Parameters • event_source (EventSource) – CounterEventSource instance will relay event_source’s events until max_events has been reached. • max_events (int) – Amount of events to be relayed until this source closes itself. on_eventsource_closed(event) Invoked once when the observed EventSource is closed Parameters event (Event) – received event on_message(event) Invoked every time a normal Event is put into the observed EventSoure Parameters event (Event) – Received event class tta.core.event.source.EventObserverInterface Abstract class, implementing all methods an Event Observer must implement on_eventsource_closed(event) Invoked once when the observed EventSource is closed Parameters event (Event) – Received event on_message(event) Invoked every time a normal Event is put into the observed EventSoure Parameters event (Event) – Received event

15.6. tta.core.event.source 213 TTA Documentation, Release 1.15.2 class tta.core.event.source.EventSource(unit=None, filter_=None) This class implements EventSource which receives events from a Unit to a queue. Parameters • unit (UnitBase) – Unit instance to receive events from • filter (EventFilter) – Filter to be applied to this EventSource close(reason=None) Closes the EventSource After calling close, no Events will be emitted by this instance of EventSource. copy() Returns a list containing the current content of the EventSource queue Returns List of events Return type Event get(block=True, timeout=None) Get event from source Parameters • block (bool) – If False, get will not block on empty source • timeout (float) – Timeout after which get will return if there is no element in source Returns Event from source Return type Event Raises TTAEventSourceClosedError – If EventSource already closed get_close_reason() Returns the reason why this EventSource has been closed. Returns None when the EventSource has not yet been closed. :rtype: str is_closed() Returns True if this EventSource instance has been closed. :rtype: bool put(event, block=True, timeout=None) Put event into source Parameters • event (Event) – Received event • block (bool) – If False, put will not block on full source • timeout (float) – Timeout after which put will return if the source is full Raises • TTAEventSourceClosedError – If EventSource already closed • TTAEventSourceDispatchError – If error occurres while dispatching event to ob- servers register_observer(observer) Adds an observer to the EventSource Every time the EventSource receives an Event which passes the Filter, all Observer.on_message meth- ods will be called. The method must accept exactly one argument ‘event’. Only Events received after register_observer will invoke the callback methods.

214 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

Parameters observer (EventObserverInterface) – the object to be notified Raises TTAEventSourceClosedError – If EventSource already closed unregister_observer(observer) Removes an observer After unregister_observer, the specified observer method will not be invoked anymore upon new Events. Parameters observer (EventObserverInterface) – Observer to remove class tta.core.event.source.TimeoutEventSource(event_source, time- out_between_events=None, close_after=None, auto_start=True, inherit_events=False) This class implements an EventSource which will close itself after a defined timeout. Parameters • event_source (EventSource) – TimeoutEventSource instance will relay event_source’s events. • timeout_between_events – Maximum timeout in seconds between events. When no event has been received for this amount of time, this EventSource will be closed. None = no timeout :type timeout_between_events: float :param close_after: Maximum lifetime in seconds of this EventSource. After this time, this EventSource will be closed. None = no timeout :type close_after: float :param auto_start: If True, specified timeouts start to count down immediately. If False, EventSource.start() has to be called explicitly. :param bool inherit_events: If True, inherit events from provided EventSource and check timeout with regard to timestamp of last event inherited :type auto_start: bool class Timer(interval, src) Timer implementation for this EventSource. Based on threading.Timer. cancel(update=False) Stop the timer if it has not finished yet. run() Method representing the thread’s activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword argu- ments taken from the args and kwargs arguments, respectively. set_last_timestamp(timestamp) Inform Timer of latest event’s timestamp close(reason=None) Closes the EventSource After calling close, no Events will be emitted by this instance of EventSource. get_timeout_between_events() Return current timeout_between_event interval on_eventsource_closed(event) Invoked once when the observed EventSource is closed Parameters event (Event) – received event on_message(event) Invoked every time a normal Event is put into the observed EventSoure Parameters event (Event) – Received event

15.6. tta.core.event.source 215 TTA Documentation, Release 1.15.2

set_timeout_between_events(timeout_between_events=None) Set/change timeout between events on started running TimeoutEventSource start() Starts counting down specified timeouts.

15.7 tta.core.exception

This module contains the base class for all TTA Units. Copyright (C) MAGNA Telemotive GmbH exception tta.core.exception.HintError Hints for exceptions, should help the user to figure out what he could do to solve the situation. Usage: Raise a HintError with a supplying message text from the original exception. exception tta.core.exception.MissingDocumentationError Raised when a test case implementation is missing the required docstring content. exception tta.core.exception.TTAContextError Error will be raised when trying to start a context’s lifecycle while it is already running and when ending the lifecycle of a context with no active lifecycle. exception tta.core.exception.TTADLLError Raised when the DLL can not compute the key exception tta.core.exception.TTAError Base class for all TTA related errors. exception tta.core.exception.TTAEventSourceClosedError Error will be raised when an inappropriate action is performed on a closed EventSource. exception tta.core.exception.TTAEventSourceDispatchError(exceptions) Error will be raised when Error(s) occurred during dispatching of Events to the EventSource’s observers. Mem- ber variable exceptions will hold a list of all errors that occurred. Parameters exceptions (list of Exception) – Exceptions that occurred exception tta.core.exception.TTAFlashError(flash_step) Raised when an error occurs in the flash-cycle exception tta.core.exception.TTAISOTPSequenceError Raised when the sequence number between ISO-TP consecutive frames is wrong exception tta.core.exception.TTAISOTPTimeoutError Raised when the timeout between ISO-TP messages is hit exception tta.core.exception.TTAIllegalDriverError Raised when an illegal driver is specified for a unit exception tta.core.exception.TTAImageGrabberError(error_code) Raised when the call of a driver dll function returns an error code exception tta.core.exception.TTAImageGrabberNoImageError Raised when the image grabber can’t get an image exception tta.core.exception.TTALicenseError Error will be raised if license did expire exception tta.core.exception.TTAModifiedError Error will be raised if code manipulation has been detected

216 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

exception tta.core.exception.TTAODXError Raise when the ODX file does not contains all the requires data for a flash cycle exception tta.core.exception.TTAUDSError(error_code) Raised when a negative response to a UDS service is received exception tta.core.exception.TTAUDSTransmissionError Raised when reply can not be matched to any known UDS service exception tta.core.exception.TTAUnitInitError Error will be raised when an exception during TTA Unit init occurs. exception tta.core.exception.TTAUnitManagerContextError Error will be raised on entering a with-block if UnitManager is not empty exception tta.core.exception.TTAUnitShutdownError Error will be raised when an exception during TTA Unit shutdown occurs.

15.8 tta.core.logger

This module contains the implementation of the common logger module of TTA (derived from Python logging mod- ule). Copyright (C) MAGNA Telemotive GmbH class tta.core.logger.LoggerManager Central management instance for all log functions. There should be only one (and always the same) Logger- Manager in the lifetime of a Python program Constructor add_data(data_provider) Integrate logger configuration from this data provider and integrate it with current settings. Update all existing TTA Loggers and all new created. Parameters data_provider (dict) – data provider Returns previous data provider for restore_data() operations Return type data provider get_data_provider() return the current log data provider Returns log data provider Return type dict get_logger(name, logtype=’TestCase’) return a TTALogger instance with given name. Parameters name (str) – logger name get_logger_path(logtype=’TestCase’) return path where log files are created Parameters logtype (str) – Logger type ( “TestCase” or “TestSequence”) Returns absolute path to log folder Return type str

15.8. tta.core.logger 217 TTA Documentation, Release 1.15.2

restore_data(data_provider) Set logger configuration from to this data provider. Update all existing TTA Loggers and all new created. Parameters data_provider (dict) – data provider update_config(config, logger_type=’TestCase’) change logger configuration of all existing TTA Loggers and all new created. Parameters config (dict) – config dictionary Return type dict Returns last used config dictionary class tta.core.logger.TTAFileHandler(name, path, logtype=’TestCase’) TTA specific implementation of a python Logger file handler object update_path(new_path) switch this logger handler to a new file in a different folder with the same file name Parameters new_path (str) – new folder location class tta.core.logger.TTALogger(name) TTA specific implementation of a python Logger object Constructor Parameters name (str) – name of the logger (without prefix “tta.”) handle(record) Handle all incoming mapRecods. Method is only overwritten to fix the logger name from “tta.something” to “something” Parameters record (dict) – record of all info of a logger message log_exception(exc_info, indent=4) Logs an exception. :param exc_info: Exception info to log (sys.exc_info()) :type exc_info: Exception :param include_traceback: If True, traceback will be logged as well :type include_traceback: bool :param indent: Indentation of log content :type indent: int class tta.core.logger.TTALoggerData(filename, sequence_name=’single_runs’, tta_root=None, date=None, time=None, parent=None, path=None, **kwargs) dict-like data provider to fill placeholders in the PATH configuration of the LoggerManager Parameters • tta_root (str) – path to the “tta_code” folder • filename – • sequence_name – • date – • time – class tta.core.logger.TTALoggerDataBase(parent) base class of all dict-like data provider

15.9 tta.core.unit_base

This module contains the base class for all TTA Units.

218 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

Copyright (C) MAGNA Telemotive GmbH class tta.core.unit_base.MethodWrapper(func_to_wrap) Wrapper for Unit methods decorated with async_func Parameters func_to_wrap (function) – Method to be wrapped __get__(instance, owner) Wrap with __get__ to obtain Unit instance of caller Parameters • instance (UnitBase) – Unit instance of which method call is invoked • owner (UnitBase) – Unit class which has decorated method Returns Function instance_wrapper(*args, **kwargs) (returning result of forwarded call) for decorator Return type function __init__(func_to_wrap) Parameters func_to_wrap (function) – Method to be wrapped __weakref__ list of weak references to the object (if defined) class tta.core.unit_base.UnitBase Base class of all units Raises • TypeError – If constructor call got multiple values for argument or got no value for argu- ment and neither got config or got too many positional arguments or got unknown keyword arguments • TTAUnitInitError – If exception occurred during Unit initialization (exception chained) __init__() Raises • TypeError – If constructor call got multiple values for argument or got no value for argument and neither got config or got too many positional arguments or got unknown keyword arguments • TTAUnitInitError – If exception occurred during Unit initialization (exception chained) _add_source(event_source) Add EventSource to Unit Parameters event_source (EventSource) – EventSource to be added Raises • UnitIsDownError – If Unit already closed • TypeError – If event_source is not of type EventSource • ValueError – If event_source was already added _call_in_unit_thread(function, args, kwargs) Calls the specified function. If calling thread is Unit’s worker thread, function will be called directly. If

15.9. tta.core.unit_base 219 TTA Documentation, Release 1.15.2

not, function call will be put to Unit’s event queue and this method waits for the async call to finish and returns the result. Parameters • function (function) – Method of unit to be executed in Unit’s thread • args (list) – Arguments • kwargs (dict) – Keyword arguments Returns Result of forwarded function call Raises • UnitIsDownError – If Unit was already closed • BaseException – If exception occurred during call execution in thread, it will be for- warded _get_logger_instance() Get logger instance, can be overridden if other log format and type desired _remove_all_sources(close=False, reason=’EventSource.close() was called explicitly.’) Remove all EventSources from Unit Parameters • bool (close) – If True, then the EventSource objects will be closed • str (reason) – EventSource.REASON_* indicating why source was closed _remove_source(event_source) Remove EventSource from Unit Parameters event_source (EventSource) – EventSource to be removed _shutdown() Unit base shutdown method: stop thread and shutdown interfaces. This method is only called if this Unit is the last instance and the Unit should REALLY be closed. _trigger_event(event) Dispatch event to all registered EventSources Parameters event (Event) – Event to be triggered add_watchdog(watchdog) Add watchdog to unit Parameters UnitWatchDog (watchdog) – Watchdog object to add to unit recover(res, test, unit_incidents) Recover a broken unit if selftest failed :param res: :param test: :param unit_incidents: remove_watchdog(watchdog) Remove watchdog from unit Parameters UnitWatchDog (watchdog) – Watchdog object to remove from unit run() Unit’s main function. Processes event queue. selftest(test, unit_incidents) Perform a unit internal self test and report problems to the unit manager. This function is only called if a UnitWatchDog was added to this unit Parameters

220 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

• test (UnitSelfTest.Test) – type of self test to be performed • unit_incidents – unregister() Unregister current Unit at unit manager (and shut Unit down if this is the last instance) Raises • UnitIsDownError – If Unit already closed • TTAUnitShutdownError – If exception occurred during shutdown (exception chained) or UnitBase._shutdown wasn’t called in overloaded method class tta.core.unit_base.UnitMetaClass This meta class defines singleton behavior of all Unit classes. __call__(*args, **kwargs) Called when a Unit instance is requested via UnitName(*args, **kwargs). Must return appropriate in- stance. Parameters • cls (UnitBase) – Class of the Unit • args (list) – Arguments • kwargs (dict) – Keyword arguments Returns Unit instance Return type UnitBase Raises • TypeError – If constructor call got multiple values for argument or got no value for argument and neither got config or got too many positional arguments or got unknown keyword arguments • TTAUnitInitError – If exception occurred during Unit initialization (exception chained) tta.core.unit_base.async_func(func_to_wrap) Decorator for async callable Unit functions. Parameters func_to_wrap (function) – Method to be wrapped Raises BaseException – If exception occurred during call execution in thread, it will be for- warded class tta.core.unit_base.tta_value_from_configfile dummy parameter for generated unit classes __weakref__ list of weak references to the object (if defined)

15.10 tta.core.unit_driver_base

This module contains the base class for all TTA Unit drivers. Unit drivers can be used for units which depending on the test environment’s setup can interact with different HW or SW interfaces to provide the same functionality. Copyright (C) MAGNA Telemotive GmbH

15.10. tta.core.unit_driver_base 221 TTA Documentation, Release 1.15.2

class tta.core.unit_driver_base.UnitDriverBase(unit_instance) Base class for all TTA Unit drivers. Unit drivers can be used for units which depending on the test environment’s setup can interact with different HW or SW interfaces to provide the same functionality. This class defines the minimum interface which must be implemented by such a unit driver. For actual functionality, additional functions can be implemented as well. The base constructor stores the unit instance and creates the driver’s own logger object. Derived class’s constructor must initialize the actual HW/SW interface. When something goes wrong, an ex- ception should be raised. Parameters unit_instance (UnitBase) – TTA Unit instance using this driver DRIVER_NAME = None Driver implementation must provide a static member denoting its name. classmethod get_instance(driver, driver_classes, unit_instance, *args, **kwargs) Find the matching driver class and return a new instance of it. This method checks if driver_classes contains a class who’s DRIVER_NAME attribute equals driver. If driver is a class itself which is a subtype of the class on which get_instance is being called, a new instance of this class will be returned. Behind unit_instance any amount of arguments can be added which will be passed to the driver’s constructor. Parameters • driver (str) – Desired driver name or driver class • driver_classes (list) – List of supported driver classes • unit_instance (BaseUnit) – Instance of unit requesting the driver instance shutdown() Closes the actual HW/SW interface. This method will be called at the end of the hosting unit’s lifecycle and should shut down the actual HW or SW interface (e.g. release all resources, close connections etc.). When something goes wrong, an exception should be raised.

15.11 tta.core.unit_exception

This module contains the base class for all TTA Units. Copyright (C) MAGNA Telemotive GmbH exception tta.core.unit_exception.TTAUnitError(*args) Base class for self defined exceptions raised by TTA Units. Will report the error to the lifecycle manager. Parameters *args (tuple) – Arguments __init__(*args) Initialize self. See help(type(self)) for accurate signature.

15.12 tta.core.unit_manager

This module contains the implementation of TTA’s unit manager class. Copyright (C) MAGNA Telemotive GmbH

222 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2 exception tta.core.unit_manager.InvalidUnitClassError This error is raised when the user tries to perform an action on an unknown Unit class. exception tta.core.unit_manager.InvalidUnitInstanceError This error is raised when the user tries to perform an action on an unknown Unit instance. class tta.core.unit_manager.UnitContext(args, kwargs, instances, shared, errors=None) Unit context, used by unit manager to handle Unit properties Properties: args, kwargs, list of instances, monostate shared object, set of errors Parameters • args (tuple) – Arguments • kwargs (dict) – Keyword arguments • instances (list) – Object ids of Unit instances from this Unit • shared (dict) – Monostate shared object (reference to ‘__dict__’ of the Unit object) • errors (list) – TTAUnitErrors which have been raised by the Unit exception tta.core.unit_manager.UnitIsDownError This error is raised when a call to an already shut down unit is made. class tta.core.unit_manager.UnitManager UnitManager: manages Unit monostate objects (derived from UnitBase) Initiates config manager automatically on initialization. _UnitManager__watchdog() Watchdog thread: Do unit self tests for all units static _fix_unit_name(str_unitname) Returns name of unit Parameters str_unitname (str) – Name of Unit (e. g. CANUnit) Returns Name of Unit normalized (e. g. for CANUnit this is CAN) Return type str _reset() Reset unit registry completely, used if unregister fails or is deemed unstable _unregister_all(bool_clear_exceptions=False) Unregister all managed UnitBase instances Parameters bool_clear_exceptions (bool) – If True all error lists will be emptied get_active_instances(unit_class, args, kwargs) Return the active instances of the specified unit_class with the specified arguments Parameters • unit_class (UnitBase) – Class of Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit Returns List of Unit instances Return type list get_active_shared(unit_class, args, kwargs) Return the monostate shared __dict__ object

15.12. tta.core.unit_manager 223 TTA Documentation, Release 1.15.2

Parameters • unit_class (UnitBase) – Class of Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit Returns Unit monostate shared object Return type dict get_context(unit_class, args, kwargs) Return the unit context of the specified unit_class with the specified arguments Parameters • unit_class (UnitBase) – Class of Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit Returns Context entry from registry Return type UnitContext get_context_by_instance(unit_instance) Return the unit context for a unit instance Parameters unit_instance (UnitBase) – Unit Returns Context entry from registry Return type UnitContext get_incidents() Return dict containing Unit classes and reported error incidents Returns Dictionary containing error incidents for every Unit Return type dict get_unit_parameters(str_unitname, config_set_name=None) Return unit parameters for unit name from ConfigManager Parameters str_unitname (str) – Name of Unit Returns Parameter configuration of Unit Return type dict has_active_instances(unit_class, args, kwargs) Return True if there is an active instance of the specified unit_class with the specified arguments Parameters • unit_class (UnitBase) – Class of Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit Returns True if registry has active instance Return type bool has_context(unit_class, args, kwargs) Return True if there is a unit context of the specified unit_class with the specified arguments

224 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2

Parameters • unit_class (UnitBase) – Class of Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit Returns True if registry has context entry Return type bool is_empty() Check if unit registry is empty Returns True if registry is empty Return type bool register_instance(unit_instance, args, kwargs, dict_shared=None) Register UnitBase as monostate object Parameters • unit_instance (UnitBase) – Unit • args (tuple) – Arguments for Unit • kwargs (dict) – Keyword arguments for Unit • dict_shared (dict) – Unit monostate shared object Raises TTAUnitInitError – If UnitManager is in shutdown or if Unit is created outside strict with-context report_exception(unit_instance, error) Report TTAUnitError for Unit Parameters • unit_instance (UnitBase) – Unit • error (TTAUnitError) – TTAUnitError object shutdown() Shutdown and shutdown all managed units shutdown_watchdog() Shutdown watchdog startup() Activate unit manager startup_watchdog() Activate watchdog unregister_instance(unit_instance) Unregister an instance of a Unit. Check if this is the last usage of this Unit and return True if the Unit should shut down. Parameters unit_instance (UnitBase) – Unit to be removed Returns True if Unit was the last registered instance in context entry Return type bool Raises InvalidUnitInstanceError – If Unit is not found in registry

15.12. tta.core.unit_manager 225 TTA Documentation, Release 1.15.2

unregister_unit(unit_instance) Unregister all instance of a Unit (Watchdog handling). Check if this is the last usage of this Unit and return True if the Unit should shut down. Parameters unit_instance (UnitBase) – Unit to be removed Returns True if Unit was the last registered instance in context entry Return type bool Raises InvalidUnitInstanceError – If Unit is not found in registry unregister_unit_instances(unit, all_contexts=True) Unregister all instances of a Unit Parameters • unit (UnitBase) – Unit to be removed, either instance or class • all_contexts (bool) – True if all instances from all contexts will be unregistered (default) Raises InvalidUnitInstanceError – If Unit is not found in registry update_watchdogs(whitelist=None, counter=0) Watchdog update: Do unit self tests for all units or for whitelist only, now Parameters • whitelist (list) – List/tuple of unit instances for which the watchdog should be called • counter (int) – Seconds counter, reserved internally, do not use on external call class tta.core.unit_manager.UnitSelfTest Class for unit self testing class Result Result enum Error = 1 Error, test did fail Lost = 3 Lost, lost contact to unit OK = 0 OK, test was successfull Unknown = 4 Unknown, undefined problem Warning = 2 Warning, test did not fail but condition suspicious class Test Test enum Long = 1 Long test Short = 0 Short test class tta.core.unit_manager.UnitWatchDog(selftest, recover=None, tests=None) Class for unit watchdog

226 Chapter 15. TTA Core Reference TTA Documentation, Release 1.15.2 tta.core.unit_manager.get_current_unit_manager() Get unit manager object and start if it does not exist yet Returns Globally set unit manager Return type UnitManager

15.13 tta.core.util

This module contains some utility functions to be used all over the core package. Copyright (C) MAGNA Telemotive GmbH tta.core.util.from_unc(path) Convert UNC path to path, if not UNC path just return Parameters path (str) – UNC path tta.core.util.get_init_arguments(klass) Returns arguments of klass’s constructor method. Self not included. Parameters klass (object) – Class to be inspected Returns Tuple of elements (see below) Return type tuple This method inspects the specified class klass and returns information about this class’s constructor method. It returns a tuple containing 4 elements: 1. tuple containing names of all arguments in order (with/without default values, ‘self’ and */** arguments excluded) 2. dictionary containing arguments with default values (key) and default values (value) 3. name of the *args argument if used, else None 4. name of the **kwargs argument if used, else None tta.core.util.import_module_from_file(filename) Import module from given filepath and return its object, works for .py, .pyc and .pyd Parameters filename (str) – Path to file to import Returns Module object Return type module tta.core.util.import_module_from_file_34_35(filename) Import module from given filepath and return its object, works for .py, .pyc and .pyd, Python 3.4/3.5 Parameters filename (str) – Path to file to import Returns Module object Return type module tta.core.util.import_module_from_file_36(filename) Import module from given filepath and return its object, works for .py, .pyc and .pyd, Python 3.6 Parameters filename (str) – Path to file to import Returns Module object Return type module

15.13. tta.core.util 227 TTA Documentation, Release 1.15.2 tta.core.util.mod_init() Module init tta.core.util.setup_windows_console(quickedit) Change quickedit mode of windows console tta.core.util.timeout(func, args=(), kwargs=None, duration=1.0, default=None) Call function with timeout, return default if timeout hit Parameters • func (function) – Function to call • args (tuple) – Arguments for function call • kwargs (dict) – Keyword arguments for function call • duration (float) – Timeout in seconds • default (object) – Default result Returns Result of function call: result, exception, is_alive Return type types.SimpleNamespace tta.core.util.to_unc(path) Cast a filename/path to a UNC path which is safe to access paths with more than 255 characters in Windows Parameters path (str) – Path to convert to UNC path

228 Chapter 15. TTA Core Reference CHAPTER SIXTEEN

TUTORIAL TTA CONFIGURATION

Before you can test something with TTA, you need to set the configuration of your computer. Those variables are defining your setup : “address” of the device you want to control (IP Address of a Telemotive HW, COM port of a relay card, Port to use from a Vector HW, IP Address to use for your computer in case of Ethernet Tests etc. . . Those settings are defined in your TTA config file “default_config.yaml”. It be located at: 1. (if environment variable is defined) 2. C:UsersDocumentstta_workspacetta_config 3. C:Libsite-libttaconfig The different locations will be checked in this search order. If a file is found at one location, all other locations are ignored. This default_config.yaml looks like this:

Units: CAN:// Configuration of the CAN-HW, in this case a Vector CANCaseXL default: device_id:"" channel:0 baudrate: 500000 ISOTP: default: device_id:"" src_addr: 0x7E ident_base: 0x700 addressing: 0x00 padding: 0xAA UDS: default: device_id:"" src_addr: 0x7E ident_base: 0x700 addressing: 0x00 padding: 0xAA FlashECU:// Configuration of the Flash Unit default: device_id:"" channel:1// Channel from the CAN-HW to use for flash src_addr: 0x7E ident_base: 0x700 addressing: 0x00 ecu_addr: 0x14 padding: 0xAA (continues on next page)

229 TTA Documentation, Release 1.15.2

(continued from previous page) Relay: default: board: Conrad8RelayBoard address:0 port: \\.\COM6// COMPort to which the relay card is connected

Those variables define the default value for the configuration of all the Units of TTA. You can always define other value in the call of the constructor of each Unit by overloading the constructor.

230 Chapter 16. Tutorial TTA Configuration CHAPTER SEVENTEEN

TUTORIAL ANDROID UNIT (TTA.UNITS.ANDROID)

The Android Unit enables TTA to simulate user inputs on any Android device. This tutorial explains the basic possi- bilities and usage of that unit.

17.1 Getting started:

First, we need to setup up the developer environment for Android: 1. Install the driver for the Android developer site: https://developer.android.com/studio/index.html 2. Install the ADB Driver for the desired Android device form the Vendor homepage. 3. Activate the Developer Settings on the Android device: Enter Settings and open Device Information. Scroll down to the Buildnumber and tap the build number 7 times. A popup appears showing that the developer mode is activated, now leave this menu, to the previous menu, a new entry is shown “Developer Options”. 4. Enter the developer options and enable the USB debugging option. 5. Now the ADB driver should install as the computer recognizes a new device, the adb device. 6. Depending on the Android version used on the device, a popup may appears on the device asking to trust the computer. Note: Depending on the Android version or the Android device, there might be other ways to activate the Developer Setting. Information for each device are usually found on the internet.

17.2 Operation

Any Android device comes with a list of services available via the Android debug bridge. A Number of these services are available via the AndroidBase and the AndroidIO class in the Android Unit. Additionally to the AndroidBase and Android IO class, there is the Logcat class. This class provides the internal traces of the device. It is also possible to export the monitor functionality of the Logcat class to another thread and create an event, in case a special trace marker appears. The Android Unit provides the following services: • Input methods: swipe, tap (single touch), text, key event(e.g. Hardkeys such as the power button) • Capture methods: xml_dump, screenshot, find icon • Read serial number from the shell, if more than one device is connected • Get the output from the adb shell • Collect commands and execute a command sequence

231 TTA Documentation, Release 1.15.2

• Handle several devices • Using the Logcat Unit, one can record Logcat traces

17.3 Initialize the AndroidBase Unit

First, one needs to initialize the Android Unit by initializing the ADB class and the AndroidBase class. To open the connection to the android device, use the adb class’ device method. Example:

from tta.units.android.android import AndroidBase from tta.units.android.android import ADB from tta.units.android.android import AndroidIO

android= AndroidBase() adb= ADB() adb.devices()

Note: The method adb.devices() returns a list of connected devices. If several devices are connected, you have to choose the desired one using list commands.

17.4 Send a Command to the Device

After the initialization of the Unit and connecting the device, you can send commands to the connected devices. The commands are the adb shell commands. Below are some important examples. The console automatically reads the output. Example::

command="input tap 200 200" command="input swipe 200 200 400 400" command="input text helloWorld"

process_output= android.execute_single_command(command, serials[0], android_

˓→shell=True)

for line in process_output: print("output:"+ str(line))

Note: The method execute_single_command() checks, if the command was successfully transmitted to the device and returns the output of the console.

17.5 Send a sequence of Commands to the Device

It is also possible to collect commands and build a command sequence. See the example below how to add commands to a sequence and how to execute this command sequence. Example::

232 Chapter 17. Tutorial Android unit (tta.units.android) TTA Documentation, Release 1.15.2

# collect the commands in a list commands=[] commands.append("input tap 200 200") commands.append("input swipe 200 200 400 400") commands.append("input tap 500 230") commands.append("input text helloWorld")

#adding the commands a the sequence for command in commands: android.add_command_to_sequence(command)

# returns boolean in case every command is executed correctly success= android.execute_command_sequence(serials[0], android_shell= True)

Note: The command sequence is automatically deleted after the execution.

17.6 Logcat Unit

The Logcat Unit Object has the following features: • Get Logcat logs from the device • Search in logfiles or in the live log for specific log line • Create events for log lines • Use Logcat filter The Logcat Unit is based on the android base class. For detailed information, please look into the logcat unit’s documentation tta_units_android_logcat.

17.7 Basic Logcat usage

This section explains the basic usage of the logcat unit, like getting the serial numbers from the connected devices or how to set Logcat filters. For more details on the functionality of Logcat, please visit the developer page: https: //developer.android.com/studio/command-line/logcat.html. To start, initialize the Logcat Unit similar to the Android Unit. The initialization opens a screening for connected devices and clears the log buffer of every connected device. Example:: from tta.units.android.logcat import Logcat logcat= Logcat() serials= logcat.get_serials()

There are two ways to get logs from the device: - Use the methods logcat.get_logs()() from the Logcat Unit - Use events (described in ADVANCED LOGCAT USEAGE see down below) The example below shows how you can record logs from the Logcat. Example: 1. Set the filter for the desired device. 2. Wait some time so that the logs can be written (remember: the buffer was cleared before). 3. Get the Logs from the device and print these in the console.

17.6. Logcat Unit 233 TTA Documentation, Release 1.15.2

4. Find a defined line in the logs. Here it is possible to send already recorded logs or record new logs.

# 1. logcat.set_filter(serials[0], logformat="time", level="W") # 2. time.sleep(10) # 3. logs= logcat.get_logs(serials[0]) if logs: for ele in logs: print("\t\t Logs:"+ str(ele)) # 4. res= logcat.find_log_line(serials[0],"DCD ON") print("------new recorded ------" print(res) print("------new recorded ------") res= logcat.find_log_line(serials[0],"DCD ON", logs) print("------old recorded ------") print(res) print("------old recorded ------")

Note: the method find_log_line() returns the desired logline

17.8 Advanced Logcat usage

Now the second way to get logs from the device: In this example events will be used. This can be used to set a listener for a certain logline. This listener runs in a independent thread, each device has its own listener thread. To activate events with Logcat there a several steps necessary. Example: 1. Add one or more events to the event list. In this example the keywords “DCD” and “Battery” will trigger an event. 2. Create the listener thread for the specified device. 3. Create the EventSource to receive the Events. 4. Start the listener thread so the events can be triggered. 5. Collect the data from the event source and the thread queue. 6. Stop the listener thread. This shuts down the unit automatically.

# imports from tta.units.android.logcat import Logcat

logcat= Logcat() serials= logcat.get_serials()

# 1. logcat.add_event_string("DCD") logcat.add_event_string("Battery")

# 2. Note: currently there is also a queue returned which is a direct link

˓→to the listener # the found log lines are also in this queue thread_queue= logcat.create_new_thread(serials[0]) (continues on next page)

234 Chapter 17. Tutorial Android unit (tta.units.android) TTA Documentation, Release 1.15.2

(continued from previous page)

# 3. src= EventSource(logcat)

# 4. logcat.start_thread(serials[0])

# 5. in this demo there is a waiting time and during this time the events

˓→are logged # you can do your stuff instead for i in range(0, 10): time.sleep(1) print("waiting:"+ str(i)) print("##################### EVENTSOURCE ########################") while src.qsize() !=0: print("------src.get(): ------") print(src.get()) print("------\r\n") while thread_queue.qsize() !=0: print("------thread_queue.get():------") print(thread_queue.get()) print("------\r\n") print("##################### EVENTSOURCE ########################")

# 6. logcat.stop_thread(serials[0])

Note: Please make sure to stop thread if it is not needed any more.

17.9 AndroidIO incl. AndroidDeviceManager

The AndroidIO and the AndroidDeviceManager are two classes within the AndroidUnit to make life more comfortable. The AndroidDeviceManager keeps track of any initialized devices and provides copies of the instance at any time. The AndroidIO class provides access to several functions similar to the AndroidBase class but shorter and easier. It also extracts information from the device. The example below shows how to handle these classes. Example: 1. Import the AndroidDeviceManager and the AndroidIO. 2. Initialize the AndroidDeviceManager. 3. Some example commands show how the AndroidIO class handles adb commands. 4. Now get the detected Serial Numbers from the Devicemanager and register a new device. In return you will get an instance of the device. 5. Get a xml_dump of the current screen and print it. 6. Search the xml_dump for a specific icon. 7. Get a screenshot from the device.

from tta.units.android.androiddevicemanager import AndroidDeviceManager from tta.units.android import AndroidIO

(continues on next page)

17.9. AndroidIO incl. AndroidDeviceManager 235 TTA Documentation, Release 1.15.2

(continued from previous page) """ note new functionality in the androidIO class in combination with the

˓→Android Device Manager """

adm= AndroidDeviceManager() androidio= AndroidIO()

# some example commands androidio.swipe((200 200 400 400)) androidio.tap((200 200)) androidio.text(("helloWorld"))

# receive the serials of all connected devices devices= adm.get_connected_devices()

# now create a new Android device class note3= adm.register_new_device("note3", serials[0])

# try some fancy stuff with the note 3 # get the XML Dump xml_dump= note3.get_xml_dump() print(xml_dump)

# Find an icon an get the coordinates of this icon coords_icon= note3.find_icon("Netflix") print("Icon:"+ str(coords_icon))

# get a screenshot of the current screen img= note3.get_screenshot() img.show() if img: print("a screenshot is here")

17.10 Testcase example

Below you find a full testcase example using the above presented solutions. Note: This example only explains the android unit’s functions in the context of TTA- testcase. It is not a full testcase! Example:: from tta.runner import Runner from tta.testcase.testcase_base import AdvancedTestCaseBase from tta.units.android import AndroidBase from tta.units.android import ADB from tta.units.android import AndroidIO class Android_testcase_example(AdvancedTestCaseBase): """ This is a simple example of an android testcase """ def __init__(self, parameter_values=None): AdvancedTestCaseBase.__init__(self, parameter_values) (continues on next page)

236 Chapter 17. Tutorial Android unit (tta.units.android) TTA Documentation, Release 1.15.2

(continued from previous page) self.android= AndroidBase() self.androidio= AndroidIO() self.adb= ADB() def precondition_001_check_adb_connection(self): """ A mobile device or tablet with android has to be used and connected to the

˓→computer. Identify the device to connect to. """

# open a new shell connection self.android.open_shell_connection() print("New shell opened.") self.current_step_result.add_text("Shell","Shell was successfully opened.")

# show a list with detected devices if not self.adb.devices(): if not self.android.is_shell_alive() == True: self.logger.info("Shell isn't alive anymore. Going to close and start

˓→a new one.") # close the shell and start a new one self.android.close_shell_connection() self.android.open_shell_connection() self.adb.devices() self.current_step_result.add_text("Shell","Shell wasn't alive

˓→anymore, a new was started.") else: self.logger("Shell is alive.") self.adb.devices() self.current_step_result.add_text("Shell","Shell is alive and

˓→devices are shown.")

def step_001_go_somewhere_on_the_device(self): """ use tap and swipe to navigate """ self.androidio.swipe((500, 1500, 500, 500, 1500)) self.androidio.tap((400, 1000))

# get image img= androidio.get_screenshot() self.current_step_result.add_image("image", img) def run_testcase(): """ Run testcase """ runner= Runner() runner.run_test_case(Demo_BMW_Connected_App) if __name__ =="__main__": run_testcases()

17.10. Testcase example 237 CHAPTER EIGHTEEN

TUTORIAL RELAY UNIT (TTA.UNITS.RELAY)

The relay unit makes it possible to control relay boards. This is useful when devices have to be switched on/off at precise times in a test environment. The current version of the relay unit supports the Conrad 8 channel relay board. —–

18.1 Getting started:

1. Install the driver for the Conrad relay board. The driver and datasheet can be found at: https: //www.conrad.de/de/relaiskarte-baustein-197720-12-vdc-24-vdc-197720.html Driver: Sourcecode_8FACH_RELAISKARTE_24V7A_4_0 Datasheet: 8FACH_RELAISKARTE_24V_7A_de_en_fr_nl 2. Connect the relay board to a lab power supply. Set the voltage to 12V, current limit of 500 mA and switch on. The green LED indicates power ON. Red LEDs indicate the state of the relays (ON/OFF). When the board is first connected to power or if the power is cycled, all relays are switched off. 3. Connect the relay board to the test computer. Click on: Control Panel -> Device Manager. Check the COM port number for the “Silicon Labs CP210x USB to UART Bridge.” This is the serial to USB adapter on the board. Some boards do not come with such an adapter. In such a case, you will have to provide the adapter and check the COM port number. The COM port number is necessary when writing scripts for automation of the relay board.

18.2 Operation

The relay board has a microcontroller which receives commands from its serial interface as an input and then activates the relays based on the commands. The unit has been developed with a driver concept. That means that the function- ality for a specific type of board is implemented with a driver for that board. However, the user interface remains the same regardless of which board type is selected and the user can use the same functions and syntax for all variants of relay boards. With the selection of the Conrad 8 Board driver, the relay unit uses the serial unit in the TTA package to send commands over the serial port. The following functions are available to the user for the operation of relay boards. set - Use this to switch relays on or off. The function takes lists of relays to be switched on/off as a parameter, generates the corresponding command(s) and sends them to the relay board. Relays which are not in the list are left undisturbed. Example 1 board is connected. 8 relays are available Switching on relays 2,4 and 8 is done as follows: conrad1.set(on=[2,4,8])

238 TTA Documentation, Release 1.15.2 get - Use this function to get the status of the relays. It sends a broadcast command to all boards that are connected and returns a list of all relays that are switched on. Example First, the relays 2 and 4 are set. Then a get is called to check the status of the relays: conrad1.set(on=[2,4]) conrad1.get() Response: [2,4] reset - Use this function to switch off all relays. Example: conrad1.set[2,6,7] conrad1.get() Response: [2,6,7] conrad1.reset() conrad1.get() Response: [] toggle - Invert the state of the relays. Use a list of relays that need to be toggled. If a relay was previously ON, it will be switched OFF and vice versa. Other relays remain undisturbed. Example Scenario: Set relays 2 and 6. Toggle relay 6: conrad1.set(on=[2,6]) conrad1.get() Response: [2,6] conrad1.toggle([6]) conrad1.get() Response: [2] is_active - Check if board is active / inactive. The functions named above will work if the board was correctly initialized and if is_active is True. Otherwise an error will be displayed. Example conrad1.is_active() True

18.3 Additional Documentation

Scripts can be written using the available functions to realize an automation task/project. An example of such a script can be found under: .. seealso:: tta_playground/demos/demo_relay.py Further documentation for the unit is found at: .. seealso:: tta_doc/source/tta_units_relay_relay.rst

18.3. Additional Documentation 239 CHAPTER NINETEEN

TUTORIAL SERIAL UNIT (TTA.UNITS.SERIAL)

The serial module encapsulates the access to the serial ports. In this tutorial all functions of the Serial Unit will be described. A brief introduction of the basic functions can be found in: tta.units.serial Main contents: • Creating a Serial Unit • Functions of the Serial Unit • Using Eventsources • Available Drivers

19.1 Creating a Serial Unit

To create a Serial Unit at least a serial port has to be specified in the constructor. Additionally a driver can be set, to determine, which interface provides the serial port. By default the Python module “pySerial” will be used. Using pySerial every port registered at the operating system can be used (e.g. “COM1” on Windows or “/dev/ttyS0” on Linux). If omitted, the baudrate will be set to 19200 and the timeout will be set to 1 second. A different baudrate has to be set, when creating the Serial Unit, as it can not be modified afterwards. The timeout can be changed at any time (see Functions of the Serial Unit). Before the Serial Unit is closed, it will wait for open read/receive processes to end. Otherwise the serial interface could be left in an inconsistent state and can not be opened again. By default the Serial Unit will wait 3 read timeout intervals. This can lead to long shutdown times, if long timeout intervals are set. Therefore a maximum shutdown time in seconds can be set using the parameter max_shutdown_time: class tta.units.serial.Serial(port=’COM1’, baudrate=19200, timeout=1, driver=’pySerial’, max_shutdown_time=20, **kwargs) Serial Unit to get access to a serial interface. Additional keyword parameters can be added. See the pySerial (serial) documentation for further informa- tion about the available parameters. The following parameters are always used: Parameters • driver (int) – Serial driver, that will be used. By possible values: DRIVER_PYSERIAL (default), DRIVER_VIRTUAL • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 19200 if omitted) • timeout (float) – Read and write timeout in seconds

240 TTA Documentation, Release 1.15.2

• max_shudown_time (float) – The max time in seconds, for which the unit will wait before interrupting an active read when shutting down

The following constants can be set as “driver” parameter. For a complete list of implemented drivers see Available Drivers : DRIVER_PYSERIAL Set this value to the “driver=” keyword argument in order to create a Serial Unit using the pySerial Python module (serial) as Serial interface. This enables accessing the serial ports registered at the operating system. DRIVER_VIRTUAL The driver will create a virtual serial device for testing purposes. Any data sent using this device can be read from it. Examples:: from tta.units.serial import Serial from tta.units.serial import DRIVER_PYSERIAL from tta.units.serial import DRIVER_VIRTUAL

# create an unit using pySerial on COM1 serial_unit_1= Serial(port="COM1", baudrate=9600, timeout=1) serial_unit_1.start_up()

# timeout and baudrate will be set to default values, if they are omitted serial_unit_2= Serial("COM2") serial_unit_2.start_up()

# create a virtual unit for testing purposes serial_unit_3= Serial("COM3", baudrate=9600, timeout=1.4, driver=DRIVER_VIRTUAL) serial_unit_3.start_up()

# calling an identical constructor will return the same Serial Unit object serial_unit_4= Serial("COM4", baudrate=19200, timeout=5) serial_unit_4.start_up() serial_unit_5= Serial("COM4", baudrate=19200, timeout=5) # Returns the same Unit.

˓→start_up() # does not need to be

˓→called, as the # Unit is already started.

# Attention: calling a different constructor (other timeout in this case) will create

˓→a new Serial Unit serial_unit_6= Serial("COM5", timeout=5) serial_unit_6.start_up() serial_unit_7= Serial("COM5", timeout=4) # Will cause an exception, as "COM5" is

˓→already opened # and thus can not be accessed.

# limit the shutdown time, when using long timeout intervals # (unit will wait for "read()" methods to finish before shutting down) serial_unit_8= Serial("COM6", timeout=600, max_shutdown_time=4)

Note: Remember to call start_up() to start the Serial Unit after it has been created. The unit can not be used before it is started.

19.1. Creating a Serial Unit 241 TTA Documentation, Release 1.15.2

Additional Parameters: To support different driver-specific features additional keyword parameters can be added in the constructor. The unknown parameters will directly be forwarded to the driver. The driver itself decides, whether to use the parameters, to ignore them or to raise an exception:

# create a Serial Unit using pySerial on COM1 with enabled hardware (DSR/DTR) flow

˓→control (pySerial specific) serial_unit_1= Serial(port="COM1", baudrate=9600, dsrdtr= True) serial_unit_1.start_up()

19.2 Functions of the Serial Unit

The Serial Unit provides several functions to access and configure the serial interface. Note that the functions for sending and receiving data will be executed in the units thread, thus only one send and/or receive function will be executed at the same time. This way the Unit can be used by several clients simultaneously without generating conflicts.

19.3 Sending

Data can be sent using the write() method:

Serial.write(string) Write data over serial port connection. Parameters string (bytes) – Data to send (must be a bytes object or an ascii string) Returns Number of bytes sent. Return type int

All byte data types (bytes, bytearray, bytes sequences) or ascii strings can be send: serial_unit= Serial("COM1") serial_unit.start_up() serial_unit.write("ascii strings are allowed") serial_unit.write(b'bytes sequences are preferred') serial_unit.write(bytes([100,23,44]))

The write() method will return the number of bytes sent as integer value. Timeout: A timeout for sending data can be specified for the Serial Unit (see Configuring). If the timeout period is exceeded, the “SerialTimeoutException” will be raised: try: serial_unit.write(b"write till timeout") except SerialTimeoutException: # code for handling the timeout print("Timeout while sending.")

242 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

Exceptions: Exceptions will be raised in each of the following situations: • An invalid data type is sent (TypeError) • The Serial Unit is not started (portNotOpenError) • General error using the serial interface (SerialException) Examples:

serial_unit= Serial("COM1") serial_unit.write("port not opened yet") # raises portNotOpenError serial_unit.start_up() serial_unit.write("now the port is opened") # will work serial_unit.wirte("non ascii chars: öäü") # raises TypeError

19.3.1 Receiving

In general there a two ways to read data: 1. Synchronous reads 2. Asynchronous reads using EventSources

Note: Synchronous and asynchronous reading can not be combined. Synchronous reads while a EventSource is attached lead to unexpected results and vice versa.

Synchronous reading: Received data can be read from the serial ports buffer by using the methods read() or readline(). The method readline() uses “\n” as delimiter:

Serial.read(nchar=1) Read data sent by the Serial. This function only works for synchronous reading. Use event_read(), if a similar function is needed while using an EventSource. Parameters nchar (int) – Number of bytes to read. Returns Bytestring containing bytes read from the port. Return type bytes Raises • SerialAsyncModeError – Function was called, while EventSources were attached to the unit. • SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1]. Serial.readline() Read characters from the line. This function only works for synchronous reading. Use event_readline(), if a similar function is needed while using an EventSource.

19.3. Sending 243 TTA Documentation, Release 1.15.2

Returns Bytestring containing bytes read from the port. Return type bytes Raises • SerialAsyncModeError – Function was called, while EventSources were attached to the unit. • SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1].

The methods will return byte sequences (see bytes):

serial_unit= Serial("COM1") serial_unit.start_up()

returned_bytes1= serial_unit.read(10) # read 10 bytes returned_bytes2= serial_unit.read() # read everything in the buffer or till

˓→timeout returned_bytes3= serial_unit.readline() # read till '\n' occures

A timeout for receiving data can be specified for the Serial Unit (see Configuring). In case of a timeout the “Seri- alReadTimeoutError” will be raised. If the timeout is set to “0” seconds the exception will directly be raised, if the requested bytes are not available in the buffer (e.g. read(10) if there are only 9 or less bytes in the buffer). Setting the timeout to “None” will disable timeouts. The read functions will wait forever in this case. Any data received/read till the timeout is stored in the args[1] attribute of the timeout exception:

try: data= serial_unit.readline() except SerialReadTimeoutError as exception: data= exception.args[1] # args[1] stores the data read

˓→till timeout

Other exceptions will be raised in each of the following situations: • The Serial Unit is not started (portNotOpenError) • General error using the serial interface (SerialException) • An EventSource is attached to the Serial Unit (SerialAsyncModeError) Examples:

serial_unit= Serial("COM1") read_bytes= serial_unit.read(10) # raises portNotOpenError, as unit is not

˓→started serial_unit.start_up() read_bytes= serial_unit.read(10) # read(10) works as unit is started now

src= EventSource(serial_unit) # add an EventSource serial_unit.read(10) # raises SerialAsyncModeError

Asynchronous reading: To receive data asynchronously an EventSource (tta.core.event.source) has to be attached to the Serial Unit. The EventSources can be read similar to synchronous reading by using the methods event_read() and event_readline(). For details see Using Eventsources.

244 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

19.3.2 Configuring

To change or read the configuration at runtime, the Serial Unit provides several methods. Always use this methods to change or read the configuration. Avoid reading or manipulating single variables directly, because the values will not be forwarded to / read from the actual driver, if necessary. The following methods are implemented at the moment: Read Timeout: The timeout for reading data can be specified using the get_timeout() and set_timeout() methods. Timeouts can be set to any positive floating-point values. To disable the timeout set it to “None”. Serial.get_timeout() Get the read timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float Serial.set_timeout(timeout) Set the read timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) Examples:

serial_unit= Serial("COM1", timeout=2.5) print(serial_unit.get_timeout()) # prints "2.5" serial_unit.set_timeout(7.1) # set timeout to 7.1 seconds print(serial_unit.get_timeout()) # prints "7.1" serial_unit.set_timeout(None) # disable timeout (read function will wait

˓→forever)

Write Timeout: The timeout for sending data can be specified using the get_write_timeout() and set_write_timeout() methods. Timeouts can be set to any positive floating-point values. To disable the timeout set it to “None”. If no “write_timeout” keyword parameter was set in the constructor of the Serial Unit, the write timeout is to the value set in the “timeout” keyword parameter. Serial.get_write_timeout() Get the write timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float Serial.set_write_timeout(timeout) Set the write timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) Examples:

serial_unit= Serial("COM1", timeout=2.5) print(serial_unit.get_write_timeout()) # prints "2.5" serial_unit.set_write_timeout(7.1) # set timeout to 7.1 seconds print(serial_unit.get_write_timeout()) # prints "7.1" serial_unit.set_write_timeout(None) # disable timeout serial_unit.set_write_timeout(0) # will cause an exception, if data can

˓→not be sent directly

19.3. Sending 245 TTA Documentation, Release 1.15.2

Current state: To check whether a specific Serial Unit is already started or not use the is_open() method: Serial.is_open() Check if the port is open. Returns Open state of the serial port. Return type bool

Buffers: The current size of the input and output buffer can be read using the get functions get_input_buffer_size() and get_output_buffer_size(): Serial.get_input_buffer_size() Get the number of received bytes in the input buffer. Returns Number of bytes in the input buffer. Return type int Serial.get_output_buffer_size() Get the number of bytes in the output buffer waiting to be sent. Returns Number of bytes in the output buffer. Rytpe int The buffers can be flushed using the methods reset_input_buffer() and reset_output_buffer() Serial.reset_input_buffer() Delete all received content in the ports input buffer. Serial.reset_output_buffer() Delete all unsent content in the ports output buffer.

Status lines: There are several methods to get and set the actual state of the Serial Units status lines. The following status lines are supported at the moment: • Request To Send (RTS) • Data Terminal Ready (DTR) • Clear To Send (CTS) - read only • Data Set Ready (DSR) - read only • Ring Indicator (RI) - read only • Carrier Detect (CD) - read only Serial.get_rts() Get the State of the “Request To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool

246 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

Serial.set_rts(state) Set the state of the “Request To Send” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) Serial.get_dtr() Get the State of the “Data Terminal Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool Serial.set_dtr(state) Set the State of the “Data Terminal Ready” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) Serial.get_cts() Get the State of the “Clear To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool Serial.get_dsr() Get the State of the “Data Set Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool Serial.get_ri() Get the State of the “Ring Indicator” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool Serial.get_cd() Get the State of the “Carrier Detect” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool

19.3.3 Method overview class tta.units.serial.Serial(port=’COM1’, baudrate=19200, timeout=1, driver=’pySerial’, max_shutdown_time=20, **kwargs) Serial Unit to get access to a serial interface. Additional keyword parameters can be added. See the pySerial (serial) documentation for further informa- tion about the available parameters. The following parameters are always used: Parameters • driver (int) – Serial driver, that will be used. By possible values: DRIVER_PYSERIAL (default), DRIVER_VIRTUAL • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 19200 if omitted) • timeout (float) – Read and write timeout in seconds

19.3. Sending 247 TTA Documentation, Release 1.15.2

• max_shudown_time (float) – The max time in seconds, for which the unit will wait before interrupting an active read when shutting down _add_source(event_source) Overrides the _add_source() function of EventSource. If no EventSources were already added, the asyn- chronous reading will be started. Parameters event_source (EventSource) – EventSource to be added Raises • UnitIsDownError – If Unit already closed • TypeError – If event_source is not of type EventSource • ValueError – If event_source was already added _asyncread() Permanently reads the serial port and adds the read data to the attached EventSources. The function will be started, when a EventSource is added to the Unit and the port is opened. _remove_source(event_source) Overrides the _remove_source() function of EventSource. If all EventSources are removed, the asyn- chronous reading will be stopped. Parameters event_source (EventSource) – EventSource to be removed _shutdown() Shutdown the Port. event_read(event_source, nchar=1) Read data sent by the Serial using an EventSource Parameters • event_source (EventSource) – EventSource to read from. The Event Source has to be attached to a Serial Unit. • nchar (int) – Number of bytes to read. Returns bytes containing bytes read from the port. Return type bytes Raises SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1]. event_readline(event_source, terminator=b’\n’) Read a byte sequence using an EventSource Parameters • event_source (EventSource) – EventSource to read from. The Event Source has to be attached to a Serial Unit. • terminator (bytes) – Bytestring delimiting the sequence, that should be returned. Returns bytestring containing bytes read from the port. Return type bytes Raises SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1]. get_cd() Get the State of the “Carrier Detect” line.

248 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

Returns State of the line (True = on/high level, False = off/low level) Return type bool get_cts() Get the State of the “Clear To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dsr() Get the State of the “Data Set Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dtr() Get the State of the “Data Terminal Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_input_buffer_size() Get the number of received bytes in the input buffer. Returns Number of bytes in the input buffer. Return type int get_output_buffer_size() Get the number of bytes in the output buffer waiting to be sent. Returns Number of bytes in the output buffer. Rytpe int get_ri() Get the State of the “Ring Indicator” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_rts() Get the State of the “Request To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_timeout() Get the read timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float get_write_timeout() Get the write timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float

19.3. Sending 249 TTA Documentation, Release 1.15.2

is_open() Check if the port is open. Returns Open state of the serial port. Return type bool read(nchar=1) Read data sent by the Serial. This function only works for synchronous reading. Use event_read(), if a similar function is needed while using an EventSource. Parameters nchar (int) – Number of bytes to read. Returns Bytestring containing bytes read from the port. Return type bytes Raises • SerialAsyncModeError – Function was called, while EventSources were attached to the unit. • SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1]. readline() Read characters from the line. This function only works for synchronous reading. Use event_readline(), if a similar function is needed while using an EventSource. Returns Bytestring containing bytes read from the port. Return type bytes Raises • SerialAsyncModeError – Function was called, while EventSources were attached to the unit. • SerialReadTimeoutError – Reading process exceeded timeout duration. Already received data can be accessed in args[1]. reset_input_buffer() Delete all received content in the ports input buffer. reset_output_buffer() Delete all unsent content in the ports output buffer. set_dtr(state) Set the State of the “Data Terminal Ready” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_rts(state) Set the state of the “Request To Send” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_timeout(timeout) Set the read timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited)

250 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

set_write_timeout(timeout) Set the write timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) start_up() Open the Port. write(string) Write data over serial port connection. Parameters string (bytes) – Data to send (must be a bytes object or an ascii string) Returns Number of bytes sent. Return type int

19.4 Using Eventsources

The Serial Unit supports the usage of EventSources (tta.core.event.source). As soon as an EventSource is added to the unit, all data send to the unit will be stored byte by byte in the EventSource(s). This way several clients can read/listen to the serial interface simultaneously. Each Event contains a single byte in its “value” attribute. After the last EventSource has been removed from the unit, the data will be stored in the buffer again.

Note: Bytes that are already in the serial ports buffer when the first EventSource is attached, will directly be pushed to the EventSource.

Example: import time from tta.units.serial import Serial serial_unit= Serial("COM1") serial_unit.start_up() src= EventSource(serial_unit) time.sleep(2.0) # wait for data to be send src.close() for event in src: one_byte= event.value # read the transmitted byte from the events "value

˓→" attribute print(one_byte)

For convenience an EventSource can be read similar to synchronous reading using event_read() or event_readline():

Serial.event_read(event_source, nchar=1) Read data sent by the Serial using an EventSource Parameters • event_source (EventSource) – EventSource to read from. The Event Source has to be attached to a Serial Unit. • nchar (int) – Number of bytes to read.

19.4. Using Eventsources 251 TTA Documentation, Release 1.15.2

Returns bytes containing bytes read from the port. Return type bytes Raises SerialReadTimeoutError – Reading process exceeded timeout duration. Already re- ceived data can be accessed in args[1]. Serial.event_readline(event_source, terminator=b’\n’) Read a byte sequence using an EventSource Parameters • event_source (EventSource) – EventSource to read from. The Event Source has to be attached to a Serial Unit. • terminator (bytes) – Bytestring delimiting the sequence, that should be returned. Returns bytestring containing bytes read from the port. Return type bytes Raises SerialReadTimeoutError – Reading process exceeded timeout duration. Already re- ceived data can be accessed in args[1].

Unlike the read() method, a number of bytes to read has to specified in the event_read() method (will be set to 1 if omitted). The event_readline() method allows the use of custom delimiters as parameter “terminator”. Furthermore the methods have the same timeout behavior as the synchronous reading methods (see Receiving). Example: src= EventSource(serial_unit)

# read 20 bytes from EventSource src data= serial_unit.event_read(src, 20)

# read from EventSource src till '\n' occurs data= serial_unit.event_readline(src)

# read from EventSource src till 'XXX' occurs data= serial_unit.event_readline(src, terminator=b'XXX')

# read till a timeout occurs try: data= serial_unit.event_readline(src) except SerialReadTimeoutError as exception: # handle timeout situation data= exception.args[1] # args[1] stores the data read

˓→till timeout

Like the synchronous read(line) methods, event_read() and event_readline() return byte sequences (see bytes).

Note: Consider, that synchronous reading methods can not be used, while EventSources are attached to the Serial Unit.

Note: Asynchronous reading requires about 10 times more CPU time than synchronous reading. Use synchronous reading, if baudrates over 38400 are needed.

252 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

The EventSources are constantly filled using the private method _asyncread(). Serial._asyncread() Permanently reads the serial port and adds the read data to the attached EventSources. The function will be started, when a EventSource is added to the Unit and the port is opened. The _asyncread() method is executed in a separate thread of the unit. Consequently there can be a small gap between the point of time when data arrives at the serial interface and the point of time when it is triggered in the EventSource(s), because the thread may be inactive at this moment. To avoid problems in request-response scenarios, always remember to insert a little waiting time (e.g. using time.sleep(xy)).

19.5 Available Drivers

The Serial unit can use one of several drivers in order to provide access to different serial ports. The drivers can be exchanged without changing the way the Serial unit behaves. Thus no code using the Serial unit has to be modified, if another driver is used. At the moment the following drivers are implemented for the Serial unit:

19.5.1 Driver: pySerial (default)

Uses the pySerial module for Python and is the default driver for the Serial unit. Use this driver, if you want to access a serial port that is known to the operating system (e.g. a COM port listed in the Windows Device Manager). Instantiation: As pySerial is the default driver used by the Serial Unit, it does not have to be set explicit in the constructor:

from tta.units.serial import Serial from tta.units.serial.serial import DRIVER_PYSERIAL serial_unit= Serial("COM1") # by default the pySerial

˓→driver will be used serial_unit= Serial("COM2", driver=DRIVER_PYSERIAL) # the driver can be set

˓→explicit too

Specific Features: • Additional pySerial specific parameters can be set as keyword parameters in the constructor of the Serial Unit. For a list of possible parameters see the pySerial documentation (link under Additional Documentation). The additional parameters will be forwarded to the pySerial constructor directly. • The driver instantiates a pySerial serial interface object (class serial.Serial). A reference to this object is stored in “self._driver._serialport” within the Serial Unit. The reference can be used to access the pySerial object directly. It is strongly recommended NOT to do this, as this may cause unexpected behavior of the Serial Unit. Examples:

from serial import PARITY_ODD

# create a Serial Unit using pySerial on COM1 with enabled hardware (DSR/DTR) flow

˓→control and # odd parity (both pySerial specific parameters) serial_unit= Serial(port="COM1", baudrate=9600, dsrdtr= True, parity=PARITY_ODD) serial_unit.start_up()

(continues on next page)

19.5. Available Drivers 253 TTA Documentation, Release 1.15.2

(continued from previous page) # Get a dictionary with port settings (pySerial specific function - not implemented

˓→in the Serial Unit) settings_dict= serial_unit._driver._serialport.get_settings()

Overview: class tta.units.serial.serial_driver_pyserial.DriverPySerial(unit_instance, port, baudrate=9600, timeout=None, **kwargs) Driver Class providing the pySerial interface. There are serveral mandatory parameters. Additional keyword parameters can be added. See the pySerial documentation for further information about the available parameters. The following parameters are always used: Parameters • unit_instance (Serial) – Serial Unit instance using this driver • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 9600 if omitted) • timeout (float) – Read and write timeout in seconds get_cd() Get the State of the “Carrier Detect” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_cts() Get the State of the “Clear To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dsr() Get the State of the “Data Set Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dtr() Get the State of the “Data Terminal Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_input_buffer_size() Get the number of received bytes in the input buffer. Returns Number of bytes in the input buffer. Return type int get_output_buffer_size() Get the number of bytes in the output buffer waiting to be sent.

254 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

Returns Number of bytes in the output buffer. Rytpe int get_ri() Get the State of the “Ring Indicator” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_rts() Get the State of the “Request To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_timeout() Get the read timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float get_write_timeout() Get the write timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float is_open() Check the Port. Returns Opened state of the serial interface. Return type bool open() Open the Port. read(nchar=1) Read data sent by the Serial Parameters nchar (int) – Number of bytes to read. Returns List containing bytes read from the port. Return type list Raises SerialException – Error during reading process. readline() Read characters from the line Returns List containing bytes read from the port. Return type list Raises SerialException – Error during reading process. reset_input_buffer() Delete all received content in the ports input buffer. reset_output_buffer() Delete all unsent content in the ports output buffer.

19.5. Available Drivers 255 TTA Documentation, Release 1.15.2

set_dtr(state) Set the State of the “Data Terminal Ready” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_rts(state) Set the state of the “Request To Send” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_timeout(timeout) Set the read _timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) set_write_timeout(timeout) Set the write _timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) shutdown() Shutdown the Port. write(input_data) Write data over serial port connection. Parameters input_data (str) – Data to send as string or bytes (array) object. Returns Number of bytes send. Return type int Raises • TypeError – Wrong type for input_data. • SerialException – Error during sending process. • SerialTimeoutException – Sending process exceeded _timeout duration.

19.5.2 Driver: Virtual

Creates an virtual serial port in the Serial unit. Data written to this unit/port can be read from it afterwards. This driver should only be used for testing purposes. Instantiation: To instantiate a Serial Unit using the virtual driver set the constant DRIVER_VIRTUAL as driver:

from tta.units.serial import Serial from tta.units.serial.serial import DRIVER_VIRTUAL serial_unit= Serial("COM1", driver=DRIVER_VIRTUAL) # creates a Serial Unit using

˓→the virtual driver

Specific Features: • Data written to a Serial Unit using this driver, can be read from it. Thus get_input_buffer_size() and get_output_buffer_size() will return the same value for example. • The driver does not emulate baudrates at the moment.

256 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

• Unknown keyword parameters will be added as variables to the driver. The keyword is used as variable name. Note that existing variables with the same name will be overwritten. The feature can be used to check, if keyword parameters were set correctly (e.g. from the config etc.). • The status lines (see Configuring) are implemented but will not behave like a real serial interface, because the virtual driver represents both the sender and the receiver, so the lines are shared. The state of the lines can still be manipulated manually to simulate a certain behavior. • Some exceptions can be caused manually (see Examples). Examples:

from tta.units.serial import Serial from tta.units.serial.serial import DRIVER_VIRTUAL serial_unit= Serial("COM1", driver=DRIVER_VIRTUAL, individual_parameter="individual_

˓→content")

# Read data written to the unit serial_unit.write(b"123456789") print(serial_unit.read(5)) # prints "12345"

# Unknown keyword parameters create variables print(serial_unit._driver._serialport.individual_parameter) # prints "individual_

˓→content"

# Sending b'Error' causes a "SerialException" serial_unit.write(b'Error')

# Sending b'Timeout' causes a "SerialTimeoutException" # Note: Read timeouts can be generated by reading from an empty unit serial_unit.write(b'Timeout')

# Manipulate a status line manually (set a high level on the CD line) serial_unit._serialport._line_cd= True print(serial_unit.get_cd())

Overview: class tta.units.serial.serial_driver_virtual.DriverTestVirtual(unit_instance, port=None, baudrate=9600, timeout=None, **kwargs) Driver Class providing a virtual interface for testing. Written/sent data will be stored in order to be read. Parameters • unit_instance (Serial) – Serial Unit instance using this driver • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 9600 if omitted) • timeout (float) – Read and write timeout in seconds get_cd() Get the State of the “Carrier Detect” line. False by default. Will be set True while writing.

19.5. Available Drivers 257 TTA Documentation, Release 1.15.2

Returns State of the line (True = on/high level, False = off/low level) Return type bool get_cts() Get the State of the “Clear To Send” line. True by default. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dsr() Get the State of the “Data Set Ready” line. True by default. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dtr() Get the State of the “Data Terminal Ready” line. True by default. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_input_buffer_size() Get the number of received bytes in the input buffer. Returns Number of bytes in the input buffer. Return type int get_output_buffer_size() Get the number of bytes in the output buffer waiting to be sent. Returns Number of bytes in the output buffer. Rytpe int get_ri() Get the State of the “Ring Indicator” line. False by default. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_rts() Get the State of the “Request To Send” line. False by default. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_timeout() Get the read timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float get_write_timeout() Get the write timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float

258 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

is_open() Check the Port. Returns Opened state of the serial interface. Return type bool open() Open the Port. read(nchar=1) Read data sent by the Serial Parameters nchar (int) – Number of bytes to read. Returns List containing bytes read from the port. Return type list Raises SerialException – Error during reading process. readline() Read characters from the line Returns List containing bytes read from the port. Return type list Raises SerialException – Error during reading process. reset_input_buffer() Delete all received content in the ports input buffer. Affects the output buffer as well, because the buffer is shared for the virtual device. reset_output_buffer() Delete all unsent content in the ports output buffer. Affects the input buffer as well, because the buffer is shared for the virtual device. set_dtr(state) Set the State of the “Data Terminal Ready” line. Will change DSR as well, because data written to this unit can be read from it. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_rts(state) Set the state of the “Request To Send” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_timeout(timeout) Set the read timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) set_write_timeout(timeout) Set the write timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) shutdown() Shutdown the Port. write(input_data) Simulate writing data over serial port connection. The data will be stored and can be read using read() or readline().

19.5. Available Drivers 259 TTA Documentation, Release 1.15.2

Parameters input_data (str) – Data to send as string or bytes (array) object. Returns Number of bytes send. Return type int Raises • TypeError – Wrong type for input_data. • SerialException – Raised, if b’Error’ is sent. • SerialTimeoutException – Raised, if b’Timeout’ is sent.

19.5.3 Add custom driver

Additional custom drivers can be added this way: • Add a new module named like tta.units.serial.serial_driver_ (e.g. “tta.units.serial.serial_driver_myserialinterface”). Add a class named like Driver (e.g. DriverMyserialinterface) in this module. The class must be derived from tta.units.serial.serial_driver_base.SerialDriverBase and has to contain the constant “DRIVER_NAME”. • Override all methods of tta.units.serial.serial_driver_base.SerialDriverBase: class tta.units.serial.serial_driver_base.SerialDriverBase(unit_instance, port, baudrate=9600, time- out=None, **kwargs) Base class for Serial unit drivers. This class defines the interface which must be implemented by Serial unit drivers. There are serveral mandatory parameters. Additional keyword parameters can be added. The following param- eters are always used: Parameters • port (str) – Device name, e.g. COM1 • baudrate (int) – Baud rate (set to 9600 if omitted) • timeout (float) – Read and write timeout in seconds get_cd() Get the State of the “Carrier Detect” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_cts() Get the State of the “Clear To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dsr() Get the State of the “Data Set Ready” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_dtr() Get the State of the “Data Terminal Ready” line.

260 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

Returns State of the line (True = on/high level, False = off/low level) Return type bool get_input_buffer_size() Get the number of received bytes in the input buffer. Returns Number of bytes in the input buffer. Return type int get_output_buffer_size() Get the number of bytes in the output buffer waiting to be sent. Returns Number of bytes in the output buffer. Rytpe int get_ri() Get the State of the “Ring Indicator” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_rts() Get the State of the “Request To Send” line. Returns State of the line (True = on/high level, False = off/low level) Return type bool get_timeout() Get the read timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float get_write_timeout() Get the write timeout. Returns Timeout in seconds or ‘None’ (block unlimited) Return type float is_open() Check the Port. Return True if port is opened, else return False. Returns Opened state of the serial interface. Return type bool open() Open the Port. read(nchar=1) Read data sent by the Serial Parameters nchar (int) – Number of bytes to read. Returns Bytes read from the port. Return type bytes Raises SerialException – Error during reading process.

19.5. Available Drivers 261 TTA Documentation, Release 1.15.2

readline() Read bytes till the occurence of “n” an return them as bytes object. Returns Bytes read from the port. Return type bytes Raises SerialException – Error during reading process. reset_input_buffer() Delete all received content in the ports input buffer. reset_output_buffer() Delete all unsent content in the ports output buffer. set_dtr(state) Set the State of the “Data Terminal Ready” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_rts(state) Set the state of the “Request To Send” line. Parameters state (bool) – State of the line (True = on/high level, False = off/low level) set_timeout(timeout) Set the read _timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) set_write_timeout(timeout) Set the write _timeout. Parameters timeout (float) – Timeout in seconds or ‘None’ (will block unlimited) shutdown() Shutdown the Port. write(input_data) Write data over serial port connection. Parameters input_data (str) – Data to send as string or bytes (array) object. Returns Number of bytes send. Return type int Raises • TypeError – Wrong type for input_data. • SerialException – Error during sending process. • SerialTimeoutException – Sending process exceeded _timeout duration. • In the module tta.units.serial.serial add the class name of the created driver class (e.g. Seri- alDriverMyserialinterface) to the list DRIVER_CLASSES. • (optional) For convenience add a constant named DRIVER_ to the tta.units.serial. serial module (e.g. DRIVER_MYSERIALINTERFACE = DriverMyserialinterface.DRIVER_NAME). This constant should be imported in the ./serial/__init__.py module too.

262 Chapter 19. Tutorial Serial unit (tta.units.serial) TTA Documentation, Release 1.15.2

19.6 Additional Documentation

• Demo: ../tta_demos/demo_serial.py • pySerial documentation: https://pythonhosted.org/pyserial/

19.6. Additional Documentation 263 CHAPTER TWENTY

TUTORIAL TESTCASE SUBSTEPS

TTA offers the option to use substeps, this is often used when reoccuring steps are looped over but should still be seen as individual steps later in the report to have a better overview.

20.1 Getting Started

There are generally two ways to incorporate substeps into your testcase, or rather how you can mark the output to refer to the substep instead of the overarching step. The first option is to directly declare the following asserts to relate to its own substep like this:

def my_custom_substep(self,x,y): self.assert_type= AssertType.SubStep z=x+y self.assertEqual(z, x+y, msg="Add") z=x * y self.assertEqual(z, x*y, msg="Multiply") def step_001_dynamically_load_steps(self): for i in range(3,10): self.my_custom_substep(i, i+1) self.assert_type= AssertType.Step

This can also be achieved by creating the substep directly and then passing it to the assert functions such as: def my_custom_substep_with_result(self, x, y,result): z=x+y self.assertEqual(z, x+y, msg="Add", result=result) z=x * y self.assertEqual(z, x*y, msg="Multiply", result=result) def step_002_dynamically_load_steps_with_result(self): for i in range(3, 10): res= self.current_step_result.add_test_step_result("The result for number %s"

˓→%i,"TheDescription") self.my_custom_substep_with_result(i, i+1, res)

20.2 Additional Documentation

Substeps are generally used to avoid having too many individual steps which could make the testcase hard to refactor and understand. If the functions are similar and only the input parameters change it is a good option to reduce unnecessary code or if you want to start a single step multiple times with randomly generated inputs.

264 CHAPTER TWENTYONE

LICENSE

This is a list of python packages used by TTA showing package information and licenses. TTA does not modify any python packages it uses.

Note: If you want to modify python packages yourself and redistribute them (in your own testing tools), please consider the package licenses.

Color Category (see: Wikipedia - Licenses) Blue Permissive license Green Weak copyleft license Orange Strong copyleft license

You can find all installed package archives in the local install directory: Installed Python Packages

21.1 Python Packages asn1crypto (0.24.0) Author: wbond E-Mail: [email protected] Homepage: https://github.com/wbond/asn1crypto PyPI-Link: https://pypi.python.org/pypi/asn1crypto License: ‘MIT’ License :: OSI Approved :: MIT License astroid (2.1.0) Author: Python Code Quality Authority E-Mail: [email protected] Homepage: https://github.com/PyCQA/astroid PyPI-Link: https://pypi.python.org/pypi/astroid License: ‘LGPL’ bcrypt (3.1.6) Author: The Python Cryptographic Authority developers E-Mail: [email protected]

265 TTA Documentation, Release 1.15.2

Homepage: https://github.com/pyca/bcrypt/ PyPI-Link: https://pypi.python.org/pypi/bcrypt License: ‘Apache License, Version 2.0’ beautifulsoup4 (4.7.1) Author: Leonard Richardson E-Mail: [email protected] Homepage: http://www.crummy.com/software/BeautifulSoup/bs4/ PyPI-Link: https://pypi.python.org/pypi/beautifulsoup4 License: ‘MIT’ License :: OSI Approved :: MIT License bitstring (3.1.5) Author: Scott Griffiths E-Mail: dr.scottgriffi[email protected] Homepage: https://github.com/scott-griffiths/bitstring PyPI-Link: https://pypi.python.org/pypi/bitstring License: ‘The MIT License: http://www.opensource.org/licenses/mit-license.php’ License :: OSI Approved :: MIT License bs4 (0.0.1) Author: Leonard Richardson E-Mail: [email protected] Homepage: https://pypi.python.org/pypi/beautifulsoup4 PyPI-Link: https://pypi.python.org/pypi/bs4 License: ‘MIT’ License :: OSI Approved :: MIT License certifi (2018.11.29) Author: Kenneth Reitz E-Mail: [email protected] Homepage: https://certifi.io/ PyPI-Link: https://pypi.python.org/pypi/certifi License: ‘MPL-2.0’ cffi (1.12.2) Author: Armin Rigo, Maciej Fijalkowski E-Mail: python-cffi@googlegroups.com Homepage: http://cffi.readthedocs.org PyPI-Link: https://pypi.python.org/pypi/cffi License: ‘MIT’ chardet (3.0.4) Author: Daniel Blanchard E-Mail: [email protected] Homepage: https://github.com/chardet/chardet PyPI-Link: https://pypi.python.org/pypi/chardet License: ‘LGPL’ License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)

266 Chapter 21. License TTA Documentation, Release 1.15.2

Click (7.0) Author: Armin Ronacher E-Mail: [email protected] Homepage: https://palletsprojects.com/p/click/ PyPI-Link: https://pypi.python.org/pypi/Click License: ‘BSD’ License :: OSI Approved :: BSD License cloudpickle (0.8.0) Author: Cloudpipe E-Mail: [email protected] Homepage: https://github.com/cloudpipe/cloudpickle PyPI-Link: https://pypi.python.org/pypi/cloudpickle License: ‘BSD 3-Clause License’ License :: OSI Approved :: BSD License colorama (0.4.1) Author: Jonathan Hartley E-Mail: [email protected] Homepage: https://github.com/tartley/colorama PyPI-Link: https://pypi.python.org/pypi/colorama License: ‘BSD’ License :: OSI Approved :: BSD License cryptography (2.5) Author: The cryptography developers E-Mail: [email protected] Homepage: https://github.com/pyca/cryptography PyPI-Link: https://pypi.python.org/pypi/cryptography License: ‘BSD or Apache License, Version 2.0’ License :: OSI Approved :: Apache License :: OSI Approved :: BSD License cycler (0.10.0) Author: Thomas A Caswell E-Mail: [email protected] Homepage: http://github.com/matplotlib/cycler PyPI-Link: https://pypi.python.org/pypi/cycler License: ‘BSD’ dask (1.1.1) Author: None E-Mail: None Homepage: http://github.com/dask/dask/ PyPI-Link: https://pypi.python.org/pypi/dask License: ‘BSD’ decorator (4.3.2) Author: Michele Simionato

21.1. Python Packages 267 TTA Documentation, Release 1.15.2

E-Mail: [email protected] Homepage: https://github.com/micheles/decorator PyPI-Link: https://pypi.python.org/pypi/decorator License: ‘new BSD License’ License :: OSI Approved :: BSD License defusedxml (0.6.0) Author: Christian Heimes E-Mail: [email protected] Homepage: https://github.com/tiran/defusedxml PyPI-Link: https://pypi.python.org/pypi/defusedxml License: ‘PSFL’ License :: OSI Approved :: Python Software Foundation License dnspython (1.16.0) Author: Bob Halley E-Mail: [email protected] Homepage: http://www.dnspython.org PyPI-Link: https://pypi.python.org/pypi/dnspython License: ‘BSD-like’ docopt (0.6.2) Author: Vladimir Keleshev E-Mail: [email protected] Homepage: http://docopt.org PyPI-Link: https://pypi.python.org/pypi/docopt License: ‘MIT’ License :: OSI Approved :: MIT License docutils (0.14) Author: docutils-develop list E-Mail: [email protected] Homepage: http://docutils.sourceforge.net/ PyPI-Link: https://pypi.python.org/pypi/docutils License: ‘public domain, Python, 2-Clause BSD, GPL 3 (see COPYING.txt)’ License :: Public Domain License :: OSI Approved :: Python Software Foundation License License :: OSI Approved :: BSD License License :: OSI Approved :: GNU General Public License (GPL) dpkt (1.9.1) Author: Dug Song E-Mail: [email protected] Homepage: http://dpkt.googlecode.com/ PyPI-Link: https://pypi.python.org/pypi/dpkt License: ‘BSD’ License :: OSI Approved :: BSD License eventlet (0.24.1)

268 Chapter 21. License TTA Documentation, Release 1.15.2

Author: Linden Lab E-Mail: [email protected] Homepage: http://eventlet.net PyPI-Link: https://pypi.python.org/pypi/eventlet License :: OSI Approved :: MIT License Flask (1.0.2) Author: Armin Ronacher E-Mail: [email protected] Homepage: https://www.palletsprojects.com/p/flask/ PyPI-Link: https://pypi.python.org/pypi/Flask License: ‘BSD’ License :: OSI Approved :: BSD License Flask-SocketIO (3.2.2) Author: Miguel Grinberg E-Mail: [email protected] Homepage: http://github.com/miguelgrinberg/Flask-SocketIO/ PyPI-Link: https://pypi.python.org/pypi/Flask-SocketIO License: ‘MIT’ License :: OSI Approved :: MIT License gherkin-official (4.1.3) Author: Cucumber Ltd and Björn Rasmusson E-Mail: [email protected] Homepage: https://github.com/cucumber/gherkin-python PyPI-Link: https://pypi.python.org/pypi/gherkin-official License: ‘MIT’ gitdb2 (2.0.5) Author: Sebastian Thiel E-Mail: [email protected] Homepage: https://github.com/gitpython-developers/gitdb PyPI-Link: https://pypi.python.org/pypi/gitdb2 License: ‘BSD License’ License :: OSI Approved :: BSD License GitPython (2.1.11) Author: Sebastian Thiel, Michael Trier E-Mail: [email protected], [email protected] Homepage: https://github.com/gitpython-developers/GitPython PyPI-Link: https://pypi.python.org/pypi/GitPython License: ‘BSD License’ License :: OSI Approved :: BSD License greenlet (0.4.15) Author: None E-Mail: None Homepage: https://github.com/python-greenlet/greenlet

21.1. Python Packages 269 TTA Documentation, Release 1.15.2

PyPI-Link: https://pypi.python.org/pypi/greenlet License: ‘MIT License’ License :: OSI Approved :: MIT License gTTS (2.0.3) Author: Pierre Nicolas Durette E-Mail: [email protected] Homepage: https://github.com/pndurette/gTTS PyPI-Link: https://pypi.python.org/pypi/gTTS License: ‘MIT’ License :: OSI Approved :: MIT License gTTS-token (1.1.3) Author: Boudewijn van Groos E-Mail: [email protected] Homepage: https://github.com/boudewijn26/gTTS-token PyPI-Link: https://pypi.python.org/pypi/gTTS-token License: ‘MIT’ License :: OSI Approved :: MIT License idna (2.8) Author: Kim Davies E-Mail: [email protected] Homepage: https://github.com/kjd/idna PyPI-Link: https://pypi.python.org/pypi/idna License: ‘BSD-like’ License :: OSI Approved :: BSD License isodate (0.6.0) Author: Gerhard Weis E-Mail: [email protected] Homepage: https://github.com/gweis/isodate/ PyPI-Link: https://pypi.python.org/pypi/isodate License: ‘BSD’ License :: OSI Approved :: BSD License isort (4.3.4) Author: Timothy Crosley E-Mail: [email protected] Homepage: https://github.com/timothycrosley/isort PyPI-Link: https://pypi.python.org/pypi/isort License: ‘MIT’ License :: OSI Approved :: MIT License itsdangerous (1.1.0) Author: Armin Ronacher E-Mail: [email protected] Homepage: https://palletsprojects.com/p/itsdangerous/ PyPI-Link: https://pypi.python.org/pypi/itsdangerous

270 Chapter 21. License TTA Documentation, Release 1.15.2

License: ‘BSD’ License :: OSI Approved :: BSD License Jinja2 (2.10) Author: Armin Ronacher E-Mail: [email protected] Homepage: http://jinja.pocoo.org/ PyPI-Link: https://pypi.python.org/pypi/Jinja2 License: ‘BSD’ License :: OSI Approved :: BSD License jira (2.0.0) Author: Sorin Sbarnea E-Mail: [email protected] Homepage: https://github.com/pycontribs/jira PyPI-Link: https://pypi.python.org/pypi/jira License: ‘BSD’ License :: OSI Approved :: BSD License kiwisolver (1.0.1) Author: The Nucleic Development Team E-Mail: [email protected] Homepage: https://github.com/nucleic/kiwi PyPI-Link: https://pypi.python.org/pypi/kiwisolver License: ‘Kiwi/BSD’ lazy-object-proxy (1.3.1)

Author: Ionel Cristian Maries˘ , E-Mail: [email protected] Homepage: https://github.com/ionelmc/python-lazy-object-proxy PyPI-Link: https://pypi.python.org/pypi/lazy-object-proxy License: ‘BSD’ License :: OSI Approved :: BSD License lxml (4.3.1) Author: lxml dev team E-Mail: [email protected] Homepage: http://lxml.de/ PyPI-Link: https://pypi.python.org/pypi/lxml License: ‘BSD’ License :: OSI Approved :: BSD License MarkupSafe (1.1.0) Author: Armin Ronacher E-Mail: [email protected] Homepage: https://www.palletsprojects.com/p/markupsafe/ PyPI-Link: https://pypi.python.org/pypi/MarkupSafe License: ‘BSD’ License :: OSI Approved :: BSD License

21.1. Python Packages 271 TTA Documentation, Release 1.15.2 matplotlib (3.0.2) Author: John D. Hunter, Michael Droettboom E-Mail: [email protected] Homepage: http://matplotlib.org PyPI-Link: https://pypi.python.org/pypi/matplotlib License: ‘BSD’ License :: OSI Approved :: Python Software Foundation License mccabe (0.6.1) Author: Ian Cordasco E-Mail: [email protected] Homepage: https://github.com/pycqa/mccabe PyPI-Link: https://pypi.python.org/pypi/mccabe License: ‘Expat license’ License :: OSI Approved :: MIT License monotonic (1.5) Author: Ori Livneh E-Mail: [email protected] Homepage: https://github.com/atdt/monotonic PyPI-Link: https://pypi.python.org/pypi/monotonic License: ‘Apache’ License :: OSI Approved :: Apache Software License netifaces (0.10.9) Author: Alastair Houghton E-Mail: [email protected] Homepage: https://github.com/al45tair/netifaces PyPI-Link: https://pypi.python.org/pypi/netifaces License: ‘MIT License’ License :: OSI Approved :: MIT License networkx (2.2) Author: Aric Hagberg E-Mail: [email protected] Homepage: http://networkx.github.io/ PyPI-Link: https://pypi.python.org/pypi/networkx License: ‘BSD’ License :: OSI Approved :: BSD License nose (1.3.7) Author: Jason Pellerin E-Mail: [email protected] Homepage: http://readthedocs.org/docs/nose/ PyPI-Link: https://pypi.python.org/pypi/nose License: ‘GNU LGPL’ License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) numpy (1.16.1+mkl)

272 Chapter 21. License TTA Documentation, Release 1.15.2

Author: Travis E. Oliphant et al. E-Mail: None Homepage: https://www.numpy.org PyPI-Link: https://pypi.python.org/pypi/numpy License: ‘BSD’ oauthlib (3.1.0) Author: The OAuthlib Community E-Mail: [email protected] Homepage: https://github.com/oauthlib/oauthlib PyPI-Link: https://pypi.python.org/pypi/oauthlib License: ‘BSD’ License :: OSI Approved :: BSD License olefile (0.46) Author: Philippe Lagadec E-Mail: [email protected] Homepage: https://www.decalage.info/python/olefileio PyPI-Link: https://pypi.python.org/pypi/olefile License: ‘BSD’ License :: OSI Approved :: BSD License onepy (0.2.1) Author: Varun Srinivasan E-Mail: [email protected] Homepage: https://github.com/varunsrin/one-py PyPI-Link: https://pypi.python.org/pypi/onepy License :: OSI Approved :: MIT License opencv-python (4.0.0.21) Author: None E-Mail: None Homepage: https://github.com/skvark/opencv-python PyPI-Link: https://pypi.python.org/pypi/opencv-python License: ‘MIT’ License :: OSI Approved :: MIT License paramiko (2.4.2) Author: Jeff Forcier E-Mail: [email protected] Homepage: https://github.com/paramiko/paramiko/ PyPI-Link: https://pypi.python.org/pypi/paramiko License: ‘LGPL’ License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) pbr (5.4.3) Author: OpenStack E-Mail: [email protected] Homepage: https://docs.openstack.org/pbr/latest/

21.1. Python Packages 273 TTA Documentation, Release 1.15.2

PyPI-Link: https://pypi.python.org/pypi/pbr License :: OSI Approved :: Apache Software License pdfkit (0.6.1) Author: Golovanov Stanislav E-Mail: [email protected] Homepage: UNKNOWN PyPI-Link: https://pypi.python.org/pypi/pdfkit License: ‘MIT’ Pillow (5.4.1) Author: Alex Clark (Fork Author) E-Mail: [email protected] Homepage: http://python-pillow.org PyPI-Link: https://pypi.python.org/pypi/Pillow License: ‘Standard PIL License’ Pint (0.9) Author: Hernan E. Grecco E-Mail: [email protected] Homepage: https://github.com/hgrecco/pint PyPI-Link: https://pypi.python.org/pypi/Pint License: ‘BSD’ License :: OSI Approved :: BSD License pip (19.2.3) Author: The pip developers E-Mail: [email protected] Homepage: https://pip.pypa.io/ PyPI-Link: https://pypi.python.org/pypi/pip License: ‘MIT’ License :: OSI Approved :: MIT License psd-tools (1.4) Author: Mikhail Korobov E-Mail: [email protected] Homepage: https://github.com/kmike/psd-tools PyPI-Link: https://pypi.python.org/pypi/psd-tools License: ‘MIT License’ License :: OSI Approved :: MIT License psutil (5.5.0) Author: Giampaolo Rodola E-Mail: [email protected] Homepage: https://github.com/giampaolo/psutil PyPI-Link: https://pypi.python.org/pypi/psutil License: ‘BSD’ License :: OSI Approved :: BSD License pyasn1 (0.4.5)

274 Chapter 21. License TTA Documentation, Release 1.15.2

Author: Ilya Etingof E-Mail: [email protected] Homepage: https://github.com/etingof/pyasn1 PyPI-Link: https://pypi.python.org/pypi/pyasn1 License: ‘BSD’ License :: OSI Approved :: BSD License PyAudio (0.2.11) Author: Hubert Pham E-Mail: UNKNOWN Homepage: http://people.csail.mit.edu/hubert/pyaudio/ PyPI-Link: https://pypi.python.org/pypi/PyAudio License: ‘MIT’ pycparser (2.19) Author: Eli Bendersky E-Mail: [email protected] Homepage: https://github.com/eliben/pycparser PyPI-Link: https://pypi.python.org/pypi/pycparser License: ‘BSD’ pycryptodomex (3.7.3) Author: Helder Eijs E-Mail: [email protected] Homepage: https://www.pycryptodome.org PyPI-Link: https://pypi.python.org/pypi/pycryptodomex License: ‘BSD, Public Domain’ License :: OSI Approved :: BSD License License :: Public Domain PyJWT (1.7.1) Author: Jose Padilla E-Mail: [email protected] Homepage: http://github.com/jpadilla/pyjwt PyPI-Link: https://pypi.python.org/pypi/PyJWT License: ‘MIT’ License :: OSI Approved :: MIT License pylint (2.2.2) Author: Python Code Quality Authority E-Mail: [email protected] Homepage: https://github.com/PyCQA/pylint PyPI-Link: https://pypi.python.org/pypi/pylint License: ‘GPL’ License :: OSI Approved :: GNU General Public License (GPL) PyNaCl (1.3.0) Author: The PyNaCl developers E-Mail: [email protected]

21.1. Python Packages 275 TTA Documentation, Release 1.15.2

Homepage: https://github.com/pyca/pynacl/ PyPI-Link: https://pypi.python.org/pypi/PyNaCl License: ‘Apache License 2.0’ pyparsing (2.3.1) Author: Paul McGuire E-Mail: [email protected] Homepage: https://github.com/pyparsing/pyparsing/ PyPI-Link: https://pypi.python.org/pypi/pyparsing License: ‘MIT License’ License :: OSI Approved :: MIT License pyserial (3.4) Author: Chris Liechti E-Mail: [email protected] Homepage: https://github.com/pyserial/pyserial PyPI-Link: https://pypi.python.org/pypi/pyserial License: ‘BSD’ License :: OSI Approved :: BSD License PySocks (1.6.8) Author: Anorov E-Mail: [email protected] Homepage: https://github.com/Anorov/PySocks PyPI-Link: https://pypi.python.org/pypi/PySocks License: ‘BSD’ python-dateutil (2.8.0) Author: Gustavo Niemeyer E-Mail: [email protected] Homepage: https://dateutil.readthedocs.io PyPI-Link: https://pypi.python.org/pypi/python-dateutil License: ‘Dual License’ License :: OSI Approved :: BSD License License :: OSI Approved :: Apache Software License python-engineio (3.3.2) Author: Miguel Grinberg E-Mail: [email protected] Homepage: http://github.com/miguelgrinberg/python-engineio/ PyPI-Link: https://pypi.python.org/pypi/python-engineio License: ‘MIT’ License :: OSI Approved :: MIT License python-socketio (3.1.2) Author: Miguel Grinberg E-Mail: [email protected] Homepage: http://github.com/miguelgrinberg/python-socketio/ PyPI-Link: https://pypi.python.org/pypi/python-socketio

276 Chapter 21. License TTA Documentation, Release 1.15.2

License: ‘MIT’ License :: OSI Approved :: MIT License python-yubico (1.3.2) Author: Dain Nilsson E-Mail: [email protected] Homepage: https://github.com/Yubico/python-yubico PyPI-Link: https://pypi.python.org/pypi/python-yubico License: ‘BSD 2 clause’ License :: OSI Approved :: BSD License pyttsx3 (2.7) Author: None E-Mail: None Homepage: None PyPI-Link: https://pypi.python.org/pypi/pyttsx3 License: ‘MIT’ pytz (2018.9) Author: Stuart Bishop E-Mail: [email protected] Homepage: http://pythonhosted.org/pytz PyPI-Link: https://pypi.python.org/pypi/pytz License: ‘MIT’ License :: OSI Approved :: MIT License pyusb (1.0.2) Author: Wander Lairson Costa E-Mail: [email protected] Homepage: http://walac.github.io/pyusb PyPI-Link: https://pypi.python.org/pypi/pyusb License: ‘BSD’ License :: OSI Approved :: BSD License PyWavelets (1.0.1) Author: None E-Mail: None Homepage: https://github.com/PyWavelets/pywt PyPI-Link: https://pypi.python.org/pypi/PyWavelets License: ‘MIT’ License :: OSI Approved :: MIT License pywin32 (224) Author: Mark Hammond (et al) E-Mail: [email protected] Homepage: https://github.com/mhammond/pywin32 PyPI-Link: https://pypi.python.org/pypi/pywin32 License: ‘PSF’ PyYAML (3.13)

21.1. Python Packages 277 TTA Documentation, Release 1.15.2

Author: Kirill Simonov E-Mail: [email protected] Homepage: http://pyyaml.org/wiki/PyYAML PyPI-Link: https://pypi.python.org/pypi/PyYAML License: ‘MIT’ License :: OSI Approved :: MIT License requests (2.21.0) Author: Kenneth Reitz E-Mail: [email protected] Homepage: http://python-requests.org PyPI-Link: https://pypi.python.org/pypi/requests License: ‘Apache 2.0’ License :: OSI Approved :: Apache Software License requests-oauthlib (1.2.0) Author: Kenneth Reitz E-Mail: [email protected] Homepage: https://github.com/requests/requests-oauthlib PyPI-Link: https://pypi.python.org/pypi/requests-oauthlib License: ‘ISC’ License :: OSI Approved :: BSD License requests-toolbelt (0.9.1) Author: Ian Cordasco, Cory Benfield E-Mail: [email protected] Homepage: https://toolbelt.readthedocs.org PyPI-Link: https://pypi.python.org/pypi/requests-toolbelt License: ‘Apache 2.0’ License :: OSI Approved :: Apache Software License rtcclient (0.6.0) Author: Di Xu E-Mail: [email protected] Homepage: https://github.com/dixudx/rtcclient PyPI-Link: https://pypi.python.org/pypi/rtcclient License: ‘Apache License, Version 2.0’ scikit-image (0.14.2) Author: None E-Mail: None Homepage: http://scikit-image.org PyPI-Link: https://pypi.python.org/pypi/scikit-image License: ‘Modified BSD’ License :: OSI Approved :: BSD License scikit-learn (0.20.3) Author: None E-Mail: None

278 Chapter 21. License TTA Documentation, Release 1.15.2

Homepage: http://scikit-learn.org PyPI-Link: https://pypi.python.org/pypi/scikit-learn License: ‘new BSD’ scipy (1.2.1) Author: None E-Mail: None Homepage: https://www.scipy.org PyPI-Link: https://pypi.python.org/pypi/scipy License: ‘BSD’ License :: OSI Approved :: BSD License selenium (3.141.0) Author: UNKNOWN E-Mail: UNKNOWN Homepage: https://github.com/SeleniumHQ/selenium/ PyPI-Link: https://pypi.python.org/pypi/selenium License: ‘Apache 2.0’ License :: OSI Approved :: Apache Software License setuptools (41.2.0) Author: Python Packaging Authority E-Mail: [email protected] Homepage: https://github.com/pypa/setuptools PyPI-Link: https://pypi.python.org/pypi/setuptools License :: OSI Approved :: MIT License six (1.12.0) Author: Benjamin Peterson E-Mail: [email protected] Homepage: https://github.com/benjaminp/six PyPI-Link: https://pypi.python.org/pypi/six License: ‘MIT’ License :: OSI Approved :: MIT License smmap2 (2.0.5) Author: Sebastian Thiel E-Mail: [email protected] Homepage: https://github.com/gitpython-developers/smmap PyPI-Link: https://pypi.python.org/pypi/smmap2 License: ‘BSD’ License :: OSI Approved :: BSD License socketIO-client (0.7.2) Author: Roy Hyunjin Han E-Mail: [email protected] Homepage: https://github.com/invisibleroads/socketIO-client PyPI-Link: https://pypi.python.org/pypi/socketIO-client License: ‘MIT’

21.1. Python Packages 279 TTA Documentation, Release 1.15.2

License :: OSI Approved :: MIT License SoundFile (0.10.2) Author: Bastian Bechtold E-Mail: [email protected] Homepage: https://github.com/bastibe/PySoundFile PyPI-Link: https://pypi.python.org/pypi/SoundFile License: ‘BSD 3-Clause License’ License :: OSI Approved :: BSD License soupsieve (1.7.3) Author: Isaac Muse E-Mail: [email protected] Homepage: https://github.com/facelessuser/soupsieve PyPI-Link: https://pypi.python.org/pypi/soupsieve License: ‘MIT License’ License :: OSI Approved :: MIT License SQLAlchemy (1.2.17) Author: Mike Bayer E-Mail: [email protected] Homepage: http://www.sqlalchemy.org PyPI-Link: https://pypi.python.org/pypi/SQLAlchemy License: ‘MIT License’ License :: OSI Approved :: MIT License suds-py3 (1.3.3.0) Author: Cackharot (original Jeff Ortel) E-Mail: [email protected] Homepage: https://github.com/cackharot/suds-py3 PyPI-Link: https://pypi.python.org/pypi/suds-py3 License: ‘LGPL’ License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) svn (0.3.46) Author: Dustin Oprea E-Mail: [email protected] Homepage: https://github.com/dsoprea/PySvn PyPI-Link: https://pypi.python.org/pypi/svn License: ‘GPL 2’ tika (1.19) Author: Chris Mattmann E-Mail: [email protected] Homepage: http://github.com/chrismattmann/tika-python PyPI-Link: https://pypi.python.org/pypi/tika License: ‘ Apache License Version 2.0, January 2004

280 Chapter 21. License TTA Documentation, Release 1.15.2

http://www.apache.org/licenses/’ toolz (0.9.0) Author: https://raw.github.com/pytoolz/toolz/master/AUTHORS.md E-Mail: None Homepage: http://github.com/pytoolz/toolz/ PyPI-Link: https://pypi.python.org/pypi/toolz License: ‘BSD’ License :: OSI Approved :: BSD License typed-ast (1.3.1) Author: David Fisher E-Mail: ddfi[email protected] Homepage: https://github.com/python/typed_ast PyPI-Link: https://pypi.python.org/pypi/typed-ast License: ‘Apache License 2.0’ urllib3 (1.24.1) Author: Andrey Petrov E-Mail: [email protected] Homepage: https://urllib3.readthedocs.io/ PyPI-Link: https://pypi.python.org/pypi/urllib3 License: ‘MIT’ License :: OSI Approved :: MIT License websocket-client (0.54.0) Author: liris E-Mail: [email protected] Homepage: https://github.com/websocket-client/websocket-client.git PyPI-Link: https://pypi.python.org/pypi/websocket-client License: ‘BSD’ License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Werkzeug (0.14.1) Author: Armin Ronacher E-Mail: [email protected] Homepage: https://www.palletsprojects.org/p/werkzeug/ PyPI-Link: https://pypi.python.org/pypi/Werkzeug License: ‘BSD’ License :: OSI Approved :: BSD License winpcapy (1.0.2) Author: Or Weis E-Mail: [email protected] Homepage: https://github.com/orweis/winpcapy PyPI-Link: https://pypi.python.org/pypi/winpcapy License: ‘GPLv2’ wrapt (1.11.1) Author: Graham Dumpleton

21.1. Python Packages 281 TTA Documentation, Release 1.15.2

E-Mail: [email protected] Homepage: https://github.com/GrahamDumpleton/wrapt PyPI-Link: https://pypi.python.org/pypi/wrapt License: ‘BSD’ License :: OSI Approved :: BSD License xlrd (1.2.0) Author: John Machin E-Mail: [email protected] Homepage: http://www.python-excel.org/ PyPI-Link: https://pypi.python.org/pypi/xlrd License: ‘BSD’ License :: OSI Approved :: BSD License xmltodict (0.12.0) Author: Martin Blech E-Mail: [email protected] Homepage: https://github.com/martinblech/xmltodict PyPI-Link: https://pypi.python.org/pypi/xmltodict License: ‘MIT’ License :: OSI Approved :: MIT License

282 Chapter 21. License CHAPTER TWENTYTWO

TUTORIAL UPDATE LICENSE

Once you open the GUI you can quickly check the current status of your license in the top right corner. The license indicator as shown below is colorcoded depending on how long your license is still valid for: • Green: More than 14 days left • Yellow: Less than 14 days left • Red: License expired

Fig. 1: TTA License indicator.

Once your license is expired you won’t be able to use TTA anymore, some basic GUI and report functionality will remain to ensure that you can still access your reports but the testcase runner will no longer be functional until you update your license file.

22.1 Getting started:

You can update your license by opening the TTA GUI and clicking the license button in the top right corner. Here you should see a popup window that indicates how many days your license is still valid alongside a colorcoded button allowing you to upload a new license file.

Fig. 2: TTA evaluation license dialog.

283 TTA Documentation, Release 1.15.2

Once you have clicked on the upload icon on the right you will be prompted to choose a valid .tml license file to upload. After you have uploaded your license file you should reload the user interface for it to take effect. The uploaded license needs to fit the installed version and the attached YubiKey number (if applicable). The YubiKey number is either on the bottom of the YubiKey or next to “Connected YubiKey ID”. Further information about the license version or the customer the license is issued can be found within the license file.

Fig. 3: TTA License dialog with an attached YubiKey.

22.2 Operation

Please note: An official TTA YubiKey is usable for every version of TTA. Every TTA YubiKey has exactly one respective license file it works with. For upgrading from a 1.x to 1.y version you need to renew your license file. If you have problems with your license, please make sure that the YubiKey is plugged in correctly: The serial number must be on the bottom. If you don’t have a valid license file, please contact the TTA contract person. If you are the contract person and have not received a license file yet, please contact us here: TMU.TTA- [email protected]

284 Chapter 22. Tutorial Update License CHAPTER TWENTYTHREE

FAQ & CONTACT

23.1 Your most frequently asked questions

Question: Where do I start ? Answer: You should first start by installing TTA if you haven’t already. After that it is usefull to go through our Getting Started tutorial as it explains the very basics of our program. Additionally we have specific sections for different roles such as Test Manager or Tester on our starting page that might be interesting to you. Question: I need to update my License, what do I do ? Answer: If you possess a valid TTA license you can simply load it into the GUI as shown here. If your licenses have expired you can contact us at [email protected] to extend your license. Question: How do I write a new Testcase ? Answer: If you have TTA (and Python) installed you can begin writing your testcase right away. You simply need to import the TestCaseBase or AdvancedTestCaseBase class and your scripts will run through TTA. For your scripts to show up in the GUI simply copy them into the workspace folder (either under local or an active repository). If you want to learn more about writing a testcase visit this page here Question: How do I configure my workstation ? Answer: The configuration of TTA can be adjusted through our config file which is located in your tta_workspace folder under tta_config. A more detailed guide can be found here. Question: What is version control and how do I use Git/Subversion ? Answer: Git and Subversion are the most popular version control systems on the market today, we recommend that you use some sort of VCS to keep track of your test cases. This could be especially usefull if you need to revert back to old versions or want to test a hardware with old specifications. You can follow these links to learn more about git and subversion. For a more detailed explanation of how to integrate them into TTA look here. Question: Why is this TTA unit not working correctly? ? Answer: Please ensure that the unit is correctly configured (see Tutorial TTA Configuration). In case your unit needs some hardware device to communicate with, check if the driver and needed software modules (e. g. libraries) are installed properly. This information should be available in the hardware’s manual. Additionally, have a look at our instructions about device configuration Device configuration. If the unit requires some hardware device (like the CAN Unit does), please ensure that the device drivers (and maybe needed library packages) are correctly installed in your operating system. Question: Where do I find a documentation overview ? Answer: For an overview of the most important topics you can visit our Index Manual here, if you are looking for something specific the search field at the top right is a good place to start. Question: What is Eclipse/PyDev ?

285 TTA Documentation, Release 1.15.2

Answer: Eclipse is an open-source IDE (integrated development environment) which provides a lot of functionality to edit and maintain your code. Together with PyDev, an Eclipse extension, it also supports Python. If you already have your own working environment set up you can just continue as usual and dont have to use our provided Eclipse version. If you want to learn more about eclipse click here. Question: How do I use the GUI ? Answer: The GUI is built on HTML5/AngularJS and runs in your browser, as long as you have the server running you can access it by visiting http://localhost:8000. You can also access the GUI remotely from a different pc by typing IP:8000 into the addressbar. For a detailed explanation of the GUI functionality you can look here. Question: Why does TTA not start up correctly? Answer: If something is wrong during TTA startup, you might start an analysis by executing the tta_info.exe program. You can find tta_info.exe either in “C:\Program Files (x86)\MAGNA Telemotive\TTA” or in “C:\Users\[your user name]\AppData\Local\Programs\MAGNA Telemotive\TTA”.

23.2 How to contact us

You can contact us via the Support dialogue in the GUI or alternatively write an email to TMU.TTA- [email protected] and your issue will be addressed shortly.

286 Chapter 23. FAQ & Contact PYTHON MODULE INDEX

a t android.logcat, 76 template, 166 term, 166 b timer, 167 bpng, 87 timer.event_source, 167 tta.core.config_manager, 205 c tta.core.config_units.generate, 207 config_manager, 205 tta.core.context, 208 context, 208 tta.core.event.event, 210 tta.core.event.filter, 210 d tta.core.event.source, 213 datalogger, 95 tta.core.exception, 216 tta.core.logger, 217 e tta.core.unit_base, 218 event, 210 tta.core.unit_driver_base, 221 exception, 216 tta.core.unit_exception, 222 tta.core.unit_manager, 222 f tta.core.util, 227 filter, 210 tta.lib.catalog.arxml, 71 tta.lib.catalog.fibex, 70 i tta.reporting.constants, 62 imagegrabber, 122 tta.reporting.htmlconverter, 63 ip_animation, 125 tta.reporting.report, 55 isotp, 130 tta.runner.runner, 45 tta.runner.suite, 49 l tta.units.android.logcat, 76 logger, 217 tta.units.audio.audio, 84 tta.units.can.bpng, 87 o tta.units.datalogger.datalogger, 95 ocr, 134 tta.units.imagegrabber.imagegrabber, 122 p tta.units.imageprocessing.animation, powersupply, 144 125 tta.units.isotp.isotp, 130 q tta.units.ocr.ocr, 134 qxdm, 157 tta.units.odx, 139 tta.units.pcap.pcap, 143 s tta.units.powersupply.powersupply, source, 213 144

287 TTA Documentation, Release 1.15.2 tta.units.qxdm.qxdm, 157 unit_exception, 222 tta.units.template.template, 166 unit_manager, 222 tta.units.term.term, 166 util, 227 tta.units.timer.event_source, 167 tta.units.timer.timer, 167 u x unit_base, 221 XYZ, 207

288 Python Module Index INDEX

_ConfigManager__get_unit_config_set()tta.core.config_manager.ConfigManager method, 205 _UnitManager__watchdog()tta.core.unit_manager.UnitManager method, 223 __call__()tta.core.unit_base.UnitMetaClass method, 221 __get__()tta.core.unit_base.MethodWrapper method, 219 __init__()tta.core.unit_base.MethodWrapper method, 219 __init__()tta.core.unit_base.UnitBase method, 219 __init__()tta.core.unit_exception.TTAUnitError method, 222 __weakref__tta.core.unit_base.MethodWrapper attribute, 219 __weakref__tta.core.unit_base.tta_value_from_configfile attribute, 221 _add_source()tta.core.unit_base.UnitBase method, 219 _add_source()tta.units.serial.Serial method, 248 _asyncread()tta.units.serial.Serial method, 248, 253 _call_in_unit_thread()tta.core.unit_base.UnitBase method, 219 _fix_unit_name()tta.core.unit_manager.UnitManager static method, 223 _get_config_folder()in module tta.core.config_manager, 207 _get_logger_instance()tta.core.unit_base.UnitBase method, 220 _get_workspace_folder()in module tta.core.config_manager, 207 _recursive_dict_merge()tta.core.config_manager.ConfigManager static method, 205 _remove_all_sources()tta.core.unit_base.UnitBase method, 220 _remove_source()tta.core.unit_base.UnitBase method, 220 _remove_source()tta.units.serial.Serial method, 248 _reset()tta.core.unit_manager.UnitManager method, 223 _set_config()tta.core.config_manager.ConfigManager method, 205 _set_unit_config()tta.core.config_manager.ConfigManager method, 205 _shutdown()tta.core.unit_base.UnitBase method, 220 _shutdown()tta.units.serial.Serial method, 248 _trigger_event()tta.core.unit_base.UnitBase method, 220 _unregister_all()tta.core.unit_manager.UnitManager method, 223 accept()tta.core.event.filter.CombinedEventFilter method, 210 accept()tta.core.event.filter.CombinedEventFilterAnd method, 211 accept()tta.core.event.filter.CombinedEventFilterOr method, 211 accept()tta.core.event.filter.CombinedEventFilterXor method, 211 accept()tta.core.event.filter.EventFilter method, 212 accept()tta.core.event.filter.InvertedFilter method, 212 accept()tta.core.event.filter.TypeFilter method, 212 accept()tta.units.can.CANFilter method, 94 accept()tta.units.can.CANFilterRange method, 94 accept()tta.units.can.CANFilterType method, 95 accept()tta.units.qxdm.qxdm.QXDMFilter method, 158

289 TTA Documentation, Release 1.15.2 accessTimingParameters()tta.units.uds.UDS method, 169 Activetta.units.vector.canoe.CANoeNode attribute, 192 actualtta.reporting.bindings.TestStepResult attribute, 59 ADBclass in tta.units.android.android, 74 add()tta.reporting.bindings.TestStepContainer method, 59 add_command_to_sequence()tta.units.android.android.AndroidBase method, 75 add_config_dict()tta.core.config_manager.ConfigManager method, 206 add_config_file()tta.core.config_manager.ConfigManager method, 206 add_configuration_option()tta.units.ethernet.ethernet_protocols.SomeIPSD method, 111 add_data()tta.core.logger.LoggerManager method, 217 add_endpoint_option()tta.units.ethernet.ethernet_protocols.SomeIPSD method, 111 add_event_string()tta.units.android.logcat.Logcat method, 77 add_file()tta.runner.suite.FileListSuite method, 49 add_file()tta.runner.suite.FileTreeSuite method, 50 add_files()tta.runner.suite.FileListSuite method, 49 add_files()tta.runner.suite.FileTreeSuite method, 50 add_image()tta.reporting.bindings.TestStepResult method, 59 add_item()tta.reporting.bindings.MetaDataList method, 61 add_list()tta.reporting.bindings.MetaDataList method, 61 add_session_report()tta.units.ptc.ptc.PTC method, 146 add_suite()tta.runner.suite.FileTreeSuite method, 50 add_test_result()tta.reporting.bindings.TTAReport method, 57 add_test_results()tta.reporting.bindings.TTAReport method, 57 add_test_step_result()tta.reporting.bindings.TestStepResult method, 59 add_text()tta.reporting.bindings.TestStepResult method, 59 add_watchdog()tta.core.unit_base.UnitBase method, 220 AdminDataclass in tta.units.odx, 140 AdvancedTestCaseBaseclass in tta.testcase.testcase_base, 39 ALLtta.runner.suite.SuiteShuffle attribute, 50 AllDTCstta.units.uds.UDSType.DTCSettingOption attribute, 181 AllNetworkstta.units.uds.UDSType.CommunicationNet2 attribute, 180 allocate_send_queue()tta.units.ethernet.ethernetbase.NetworkAdapter method, 100 Alternatetta.units.can.CANMsgType.Rate attribute, 92 AnalysisOnlytta.units.vector.canoe.SysVariable attribute, 196 android.logcatmodule, 76 AndroidBaseclass in tta.units.android.android, 75 append_entry()tta.units.ethernet.ethernet_protocols.SomeIPSD method, 111 ARPclass in tta.units.ethernet.ethernet_protocols, 107 assertActual()tta.testcase.testcase_assert.AssertMixin method, 32 assertAlmostEqual()tta.testcase.testcase_assert.AssertMixin method, 33 assertCalled()tta.testcase.testcase_assert.AssertMixin method, 33 assertEqual()tta.testcase.testcase_assert.AssertMixin method, 34 assertFalse()tta.testcase.testcase_assert.AssertMixin method, 34 assertGreater()tta.testcase.testcase_assert.AssertMixin method, 34 assertGreaterEqual()tta.testcase.testcase_assert.AssertMixin method, 34 assertIn()tta.testcase.testcase_assert.AssertMixin method, 35 assertIs()tta.testcase.testcase_assert.AssertMixin method, 35 assertIsInstance()tta.testcase.testcase_assert.AssertMixin method, 35 assertIsNone()tta.testcase.testcase_assert.AssertMixin method, 35 assertIsNot()tta.testcase.testcase_assert.AssertMixin method, 36 assertIsNotNone()tta.testcase.testcase_assert.AssertMixin method, 36 assertLess()tta.testcase.testcase_assert.AssertMixin method, 36 assertLessEqual()tta.testcase.testcase_assert.AssertMixin method, 36 AssertMixinclass in tta.testcase.testcase_assert, 32

290 Index TTA Documentation, Release 1.15.2 assertNotAlmostEqual()tta.testcase.testcase_assert.AssertMixin method, 36 assertNotEqual()tta.testcase.testcase_assert.AssertMixin method, 37 assertNotIn()tta.testcase.testcase_assert.AssertMixin method, 37 assertNotIsInstance()tta.testcase.testcase_assert.AssertMixin method, 37 assertTrue()tta.testcase.testcase_assert.AssertMixin method, 38 AssertTypeclass in tta.testcase.testcase_assert, 38 async_func()in module tta.core.unit_base, 221 AudioDataclass in tta.units.audio.audio, 84

Basetta.units.can.CANMsgType.Ident attribute, 92 BasePacketclass in tta.units.ethernet.ethernet_protocols, 104 bdatatta.units.audio.audio.AudioData attribute, 85 BLOCKEDtta.reporting.constants.ResultEnum attribute, 62 bpngmodule, 87 BPNGComclass in tta.units.can.bpng, 87 BPNGComUnitclass in tta.units.can.bpng, 88 build_idtta.units.qpst.qpst.QPST attribute, 151 BusyPendingtta.units.uds.UDSType.Error attribute, 175 BusyRepeattta.units.uds.UDSType.Error attribute, 175 call_capl_function()tta.units.vector.canoe.CANoe method, 186 call_efs_function()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 155 call_efs_function_with_variants()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 155 CANclass in tta.units.can, 89 CAN1MBaudtta.units.uds.UDSType.LinkMode attribute, 182 CAN500kBaudtta.units.uds.UDSType.LinkMode attribute, 182 cancel()tta.core.event.source.TimeoutEventSource.Timer method, 215 CANCELEDtta.reporting.constants.ResultEnum attribute, 62 CANFilterclass in tta.units.can, 93 CANFilterRangeclass in tta.units.can, 94 CANFilterTypeclass in tta.units.can, 94 CANMessageclass in tta.units.can, 91 CANMsgFlagclass in tta.units.can.bpng, 88 CanMsgStructclass in tta.units.can.bpng, 89 CANMsgTypeclass in tta.units.can, 91 CANMsgType.Dirclass in tta.units.can, 91 CANMsgType.Frameclass in tta.units.can, 91 CANMsgType.Identclass in tta.units.can, 92 CANMsgType.Rateclass in tta.units.can, 92 CANoeclass in tta.units.vector.canoe, 185 CANoeDiagnosticclass in tta.units.vector.canoe, 193 CANoeNodeclass in tta.units.vector.canoe, 191 CANoeSignalclass in tta.units.vector.canoe, 194 Captureclass in tta.units.pcap.pcap, 143 capture()tta.units.ethernet.ethernetbase.NetworkAdapter method, 102 capture()tta.units.pcap.pcap.PacketCapture method, 144 capture_resulttta.units.pcap.pcap.PacketCapture attribute, 144 CErrFrameCntrclass in tta.units.can.bpng, 88 CF_ERRORtta.units.can.bpng.CANMsgFlag attribute, 88 CF_TXMESSAGEtta.units.can.bpng.CANMsgFlag attribute, 88 CF_TXREQUESTtta.units.can.bpng.CANMsgFlag attribute, 88 change_parameter()tta.units.vector.canoe.CANoeDiagnostic method, 193 check_adb()tta.units.android.android.ADB class method, 74 check_trace_summary_for_pattern()tta.units.qxdm.qxdm.QXDMHelper class method, 159

Index 291 TTA Documentation, Release 1.15.2 checkCRC()tta.units.flash.Flash method, 114 checkProgrammingDependencies()tta.units.flash.Flash method, 114 checkProgrammingPreconditions()tta.units.flash.Flash method, 114 Checksumclass in tta.units.odx, 142 ChecksumResultclass in tta.units.odx, 143 clear_command_sequence()tta.units.android.android.AndroidBase method, 75 clearDiagnosticInformation()tta.units.uds.UDS method, 169 close()tta.core.event.source.CombinedEventSource method, 213 close()tta.core.event.source.EventSource method, 214 close()tta.core.event.source.TimeoutEventSource method, 215 close()tta.units.timer.event_source.CyclicSource method, 167 close_can()tta.units.can.bpng.BPNGCom method, 87 close_canoe_on_shutdown()tta.units.vector.canoe.CANoe method, 186 close_driver()tta.units.can.bpng.BPNGCom method, 88 close_shell_connection()tta.units.android.android.AndroidBase method, 75 CombinedEventFilterclass in tta.core.event.filter, 210 CombinedEventFilterAndclass in tta.core.event.filter, 211 CombinedEventFilterOrclass in tta.core.event.filter, 211 CombinedEventFilterXorclass in tta.core.event.filter, 211 CombinedEventSourceclass in tta.core.event.source, 213 Commenttta.units.vector.canoe.SysVariable attribute, 196 communicationControl()tta.units.flash.Flash method, 118 communicationControl()tta.units.uds.UDS method, 169 CompanyDataclass in tta.units.odx, 140 ComParamSpecclass in tta.units.odx, 139 ComParamSubsetclass in tta.units.odx, 139 compare()tta.units.audio.audio.Signal method, 82, 85 compare()tta.units.audio.audio.SignalProcessing class method, 87 compare_video()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 compile_capl()tta.units.vector.canoe.CANoe method, 186 Compression1tta.units.uds.UDSType.DataFormat attribute, 184 Compression2tta.units.uds.UDSType.DataFormat attribute, 184 Compression3tta.units.uds.UDSType.DataFormat attribute, 184 Compression4tta.units.uds.UDSType.DataFormat attribute, 184 Compression5tta.units.uds.UDSType.DataFormat attribute, 184 Compression6tta.units.uds.UDSType.DataFormat attribute, 185 Compression7tta.units.uds.UDSType.DataFormat attribute, 185 computeKey()tta.units.flash.Flash method, 114 ConditionsNotCorrecttta.units.uds.UDSType.Error attribute, 175 config_managermodule, 205 ConfigEntryMissingError, 205 ConfigEntryTypeError, 205 ConfigInvalidError, 205 ConfigManagerclass in tta.core.config_manager, 205 ConfigManagerLockedError, 207 Confirmedtta.units.uds.UDSType.DTCReadStat attribute, 183 connect()tta.units.android.android.ADB static method, 74 connect()tta.units.ptc.ptc.PTC method, 147 connect_gps()tta.units.qxdm.qxdm.QXDM method, 157 connect_target()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 155 connect_target()tta.units.qxdm.qxdm.QXDM method, 157 Conrad8RelayBoardclass in tta.units.relay.conrad8relay, 160 contenttta.reporting.bindings.TestStepResult attribute, 60 Contextclass in tta.core.context, 208

292 Index TTA Documentation, Release 1.15.2 contextmodule, 208 controlDTCSettings()tta.units.uds.UDS method, 170 convert_data()tta.units.datalogger.datalogger.DataLogger method, 95 copy()tta.core.event.source.EventSource method, 214 CounterEventSourceclass in tta.core.event.source, 213 create()tta.reporting.bindings.TTAReport class method, 57 create_capture()tta.units.ethernet.ethernetbase.NetworkAdapter method, 103 create_new_thread()tta.units.android.logcat.Logcat method, 77 create_packet_from_bytes()tta.units.ethernet.ethernetbase.Packet static method, 103 create_request()tta.units.vector.canoe.CANoeDiagnostic method, 194 create_test_result()tta.testcase.testcase_base.TestCaseBase method, 38 create_testcase()tta.units.ptc.ptc.PTC method, 147 create_testobjective()tta.units.ptc.ptc.PTC method, 147 create_testsession()tta.units.ptc.ptc.PTC method, 147 create_testsuite()tta.units.ptc.ptc.PTC method, 147 createdtta.reporting.bindings.Image attribute, 60 createdtta.reporting.bindings.Text attribute, 60 createdtta.reporting.bindings.TTAReport attribute, 57 CReceivedDataclass in tta.units.can.bpng, 88 current_step_resulttta.testcase.testcase_base.AdvancedTestCaseBase attribute, 39 CyclicSourceclass in tta.units.timer.event_source, 167 datatta.units.audio.audio.AudioData attribute, 85 Datatta.units.can.CANMsgType.Frame attribute, 91 DataBlockclass in tta.units.odx, 142 DataFDtta.units.can.CANMsgType.Frame attribute, 91 DataLoggerclass in tta.units.datalogger.datalogger, 95 dataloggermodule, 95 decode()tta.units.ethernet.ethernet_protocols.RawPacket method, 111 decode_to_dpkt()tta.units.ethernet.ethernet_protocols.RawPacket method, 111 Defaulttta.units.uds.UDSType.Session attribute, 176 defaultSession()tta.units.flash.Flash method, 114 delete_session_report()tta.units.ptc.ptc.PTC method, 147 Descclass in tta.units.odx, 141 descriptiontta.reporting.bindings.TTAReport attribute, 57 destroy_queue()tta.units.ethernet.ethernetbase.NetworkAdapter method, 100 Developmenttta.units.uds.UDSType.Session attribute, 176 devices()tta.units.android.android.ADB static method, 74 DHCPclass in tta.units.ethernet.ethernet_protocols, 109 DiagLayerContainerclass in tta.units.odx, 139 diagnosticSessionControl()tta.units.uds.UDS method, 170 disableFaultSave()tta.units.flash.Flash method, 114 disableNonDiagnosticCommunication()tta.units.flash.Flash method, 115 DisableRapidPowerShutDownSequencetta.units.uds.UDSType.Reset attribute, 178 DisableRxAndEnableTxtta.units.uds.UDSType.Communication attribute, 179 DisableRxAndTxtta.units.uds.UDSType.Communication attribute, 179 disconnect()tta.units.android.android.ADB static method, 74 disconnect()tta.units.ptc.ptc.PTC method, 147 download_data()tta.units.datalogger.datalogger.DataLogger method, 96 DriftJittertta.units.vector.canoe.CANoeNode attribute, 192 DriftJitterActivetta.units.vector.canoe.CANoeNode attribute, 192 DRIVER_NAMEtta.core.unit_driver_base.UnitDriverBase attribute, 222 DRIVER_PYSERIALbuilt-in variable, 241 DRIVER_VIRTUALbuilt-in variable, 241

Index 293 TTA Documentation, Release 1.15.2

DriverPySerialclass in tta.units.serial.serial_driver_pyserial, 254 DriverTestVirtualclass in tta.units.serial.serial_driver_virtual, 257 DTCByStatusMasktta.units.uds.UDSType.DTCRead attribute, 182 DTCExtDataRecordByDTCNumbertta.units.uds.UDSType.DTCRead attribute, 182 DTCSnapshotRecordByDTCNumbertta.units.uds.UDSType.DTCRead attribute, 182 durationtta.units.audio.audio.AudioData attribute, 85 dynamicallyDefineIdentifier()tta.units.uds.UDS method, 170

EcuConfigclass in tta.units.odx, 140 EcuMemclass in tta.units.odx, 141 EcuMemConnectorclass in tta.units.odx, 141 ECUProgrammingtta.units.uds.UDSType.Session attribute, 176 ecuReset()tta.units.uds.UDS method, 170 edit_session_report()tta.units.ptc.ptc.PTC method, 147 efs_copy_file()tta.units.qpst.qpst.QPST method, 151 efs_copy_pc_to_phone()tta.units.qpst.qpst.QPST method, 151 efs_copy_phone_to_pc()tta.units.qpst.qpst.QPST method, 151 efs_create_link()tta.units.qpst.qpst.QPST method, 152 efs_delete()tta.units.qpst.qpst.QPST method, 152 efs_dir_list()tta.units.qpst.qpst.QPST method, 152 efs_max_dir_entriestta.units.qpst.qpst.QPST attribute, 152 efs_max_file_sizetta.units.qpst.qpst.QPST attribute, 152 efs_max_link_depthtta.units.qpst.qpst.QPST attribute, 152 efs_max_mountstta.units.qpst.qpst.QPST attribute, 152 efs_max_nametta.units.qpst.qpst.QPST attribute, 152 efs_max_pathtta.units.qpst.qpst.QPST attribute, 152 efs_mk_dir()tta.units.qpst.qpst.QPST method, 152 efs_read_link()tta.units.qpst.qpst.QPST method, 152 efs_remove_tree()tta.units.qpst.qpst.QPST method, 153 efs_rename()tta.units.qpst.qpst.QPST method, 153 efs_rm_dir()tta.units.qpst.qpst.QPST method, 153 efs_stat_file()tta.units.qpst.qpst.QPST method, 153 efs_stat_fs()tta.units.qpst.qpst.QPST method, 153 efs_stat_link()tta.units.qpst.qpst.QPST method, 154 efs_versiontta.units.qpst.qpst.QPST attribute, 154 enableFaultSave()tta.units.flash.Flash method, 115 enableNonDiagnosticCommunication()tta.units.flash.Flash method, 115 EnableRapidPowerShutDownSequencetta.units.uds.UDSType.Reset attribute, 178 EnableRxAndDisableTxtta.units.uds.UDSType.Communication attribute, 179 EnableRxAndDisableTxWithEnhAddrtta.units.uds.UDSType.Communication attribute, 179 EnableRxAndTxtta.units.uds.UDSType.Communication attribute, 179 EnableRxAndTxWithEnhAddrtta.units.uds.UDSType.Communication attribute, 179 Encryption1tta.units.uds.UDSType.DataFormat attribute, 185 Encryption2tta.units.uds.UDSType.DataFormat attribute, 185 Encryption3tta.units.uds.UDSType.DataFormat attribute, 185 Encryption4tta.units.uds.UDSType.DataFormat attribute, 185 Encryption5tta.units.uds.UDSType.DataFormat attribute, 185 Encryption6tta.units.uds.UDSType.DataFormat attribute, 185 Encryption7tta.units.uds.UDSType.DataFormat attribute, 185 endtta.reporting.bindings.TestResult attribute, 58 endtta.reporting.bindings.TestStepResult attribute, 60 end_lifecycle()tta.core.context.Context method, 208 end_now()tta.reporting.bindings.TestResult method, 58 end_now()tta.reporting.bindings.TestStepResult method, 60

294 Index TTA Documentation, Release 1.15.2

EnvVariableclass in tta.units.vector.canoe, 195 eraseMemory()tta.units.flash.Flash method, 115 Errortta.core.unit_manager.UnitSelfTest.Result attribute, 226 Errortta.units.can.CANMsgType.Frame attribute, 91 esntta.units.qpst.qpst.QPST attribute, 154 Ethernetclass in tta.units.ethernet.ethernet_protocols, 104 Eventclass in tta.core.event.event, 210 eventmodule, 210 event_read()tta.units.serial.Serial method, 248, 251 event_readline()tta.units.serial.Serial method, 248, 252 EventFilterclass in tta.core.event.filter, 211 EventObserverInterfaceclass in tta.core.event.source, 213 EventSourceclass in tta.core.event.source, 213 ExceedAttemptstta.units.uds.UDSType.Error attribute, 175 exceptionmodule, 216 exec_com_function()tta.units.vector.canoe.CANoe method, 186 execute()tta.units.term.term.Term method, 167 execute_all_test_modules()tta.units.vector.canoe.CANoe method, 186 execute_command_sequence()tta.units.android.android.AndroidBase method, 75 execute_single_command()tta.units.android.android.AndroidBase method, 75 expectedtta.reporting.bindings.TestStepResult attribute, 60 ExpectedIdentclass in tta.units.odx, 142 export_session_attachment()tta.units.ptc.ptc.PTC method, 148 export_suite_tc()tta.units.ptc.ptc.PTC method, 148 export_video()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 export_view_text()tta.units.qxdm.qxdm.QXDM method, 157 Extendedtta.units.can.CANMsgType.Ident attribute, 92 ExtendedDiagnostictta.units.uds.UDSType.Session attribute, 176 extendedSession()tta.units.flash.Flash method, 115 extrap_next()tta.units.imageprocessing.warping.ImageProcessingWarping method, 129

FAILEDtta.reporting.constants.ResultEnum attribute, 62 FailurePreventsExecutiontta.units.uds.UDSType.Error attribute, 175 FileListSuiteclass in tta.runner.suite, 49 FileTreeItemclass in tta.runner.suite, 50 FileTreeSuiteclass in tta.runner.suite, 50 Filterclass in tta.units.odx, 143 filtermodule, 210 find_log_line()tta.units.android.logcat.Logcat method, 77 find_log_line()tta.units.android.logcat.Logcat.Logcatlistener method, 76 Flashclass in tta.units.flash, 113, 118 Flashclass in tta.units.odx, 140 FlashClassclass in tta.units.odx, 142 FlashDataclass in tta.units.odx, 142 FlashResultclass in tta.units.flash, 119 flush()tta.runner.runner.ProcessStdout method, 45 force_documentationtta.testcase.testcase_base.AdvancedTestCaseBase attribute, 39 FreezeCurrentStatetta.units.uds.UDSType.InputOutputPar attribute, 183 from_file()tta.units.audio.audio.Signal class method, 80, 85 from_recorder()tta.units.audio.audio.Signal class method, 81, 85 from_unc()in module tta.core.util, 227 FTPclass in tta.units.ftp, 120 FullNametta.units.vector.canoe.CANoeNode attribute, 192 FullNametta.units.vector.canoe.CANoeSignal attribute, 194

Index 295 TTA Documentation, Release 1.15.2

FullNametta.units.vector.canoe.TestModule attribute, 198 FullNametta.units.vector.canoe.TestReport attribute, 199 FunctionDictionaryclass in tta.units.odx, 140

GateWayVehicleWakeuptta.units.uds.UDSType.Communication attribute, 179 GeneralProgrammingFailuretta.units.uds.UDSType.Error attribute, 175 GeneralRejecttta.units.uds.UDSType.Error attribute, 175 generate()tta.core.config_units.generate.Generator method, 207 GenerateReport()tta.units.vector.canoe.TestReport method, 199 Generatorclass in tta.core.config_units.generate, 207 get()tta.core.event.source.EventSource method, 214 get()tta.reporting.bindings.MetaDataList method, 61 get()tta.testcase.testcase_base.ParameterSet method, 43 get()tta.units.odx.ODXLink method, 141 get()tta.units.relay.conrad8relay.Conrad8RelayBoard method, 160 get()tta.units.relay.Relay method, 159 get_active_instances()tta.core.unit_manager.UnitManager method, 223 get_active_shared()tta.core.unit_manager.UnitManager method, 223 get_actual_current()tta.units.powersupply.powersupply.PowerSupply method, 144 get_actual_power()tta.units.powersupply.powersupply.PowerSupply method, 144 get_actual_voltage()tta.units.powersupply.powersupply.PowerSupply method, 144 get_adapter()tta.units.ethernet.ethernetbase.Interfaces static method, 97 get_adapter_info()tta.units.ethernet.ethernetbase.Interfaces static method, 97 get_all_adapters()tta.units.ethernet.ethernetbase.Interfaces static method, 97 get_all_fields()tta.units.ptc.ptc.PTC method, 148 get_available_devices()tta.units.audio.recorder.Recorder static method, 81 get_bytes_of_frame()tta.units.ethernet.ethernetbase.Packet static method, 103 get_cd()tta.units.serial.Serial method, 247, 248 get_cd()tta.units.serial.serial_driver_base.SerialDriverBase method, 260 get_cd()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_cd()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 257 get_child_state()tta.units.vector.canoe.TestModule method, 198 get_close_reason()tta.core.event.source.EventSource method, 214 get_com_obj()tta.units.vector.canoe.CANoe method, 187 get_config_folder()tta.core.config_manager.ConfigManager static method, 206 get_config_sources()tta.core.config_manager.ConfigManager method, 206 get_configuration()tta.units.vector.canoe.CANoe method, 187 get_context()tta.core.unit_manager.UnitManager method, 224 get_context()tta.runner.runner.Runner method, 45, 47 get_context_by_instance()tta.core.unit_manager.UnitManager method, 224 get_cts()tta.units.serial.Serial method, 247, 249 get_cts()tta.units.serial.serial_driver_base.SerialDriverBase method, 260 get_cts()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_cts()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_current()tta.units.powersupply.powersupply.PowerSupply method, 144 get_current_config_manager()in module tta.core.config_manager, 207 get_current_unit_manager()in module tta.core.unit_manager, 226 get_data()tta.units.ftp.FTP method, 120 get_data_provider()tta.core.logger.LoggerManager method, 217 get_datablock()tta.units.odx.Session method, 141 get_datablocks()tta.units.odx.Session method, 141 get_diag()tta.units.vector.canoe.CANoe method, 187 get_display()tta.units.multimeter.Multimeter method, 131 get_document_info()in module tta.lib.catalog.arxml, 71

296 Index TTA Documentation, Release 1.15.2 get_document_info()in module tta.lib.catalog.fibex, 70 get_document_version()in module tta.lib.catalog.arxml, 71 get_document_version()in module tta.lib.catalog.fibex, 70 get_DominantFrequencyclass in tta.units.audio.audio.Signal, 83 get_DominantFrequency()tta.units.audio.audio.Signal method, 85 get_DominantFrequency()tta.units.audio.audio.SignalProcessing class method, 87 get_dsr()tta.units.serial.Serial method, 247, 249 get_dsr()tta.units.serial.serial_driver_base.SerialDriverBase method, 260 get_dsr()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_dsr()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_dtr()tta.units.serial.Serial method, 247, 249 get_dtr()tta.units.serial.serial_driver_base.SerialDriverBase method, 260 get_dtr()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_dtr()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_duty_cycle()tta.units.pwm.pwm.PWM method, 150 get_duty_cycle()tta.units.pwm.pwm_driver_base.PWMDriverBase method, 150 get_efs_dir_list()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 get_efs_property()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 get_entry()tta.core.config_manager.ConfigManager method, 206 get_environment_var()tta.units.vector.canoe.CANoe method, 187 get_FFTclass in tta.units.audio.audio.Signal, 83 get_FFT()tta.units.audio.audio.Signal method, 86 get_FFT()tta.units.audio.audio.SignalProcessing static method, 87 get_file()tta.units.ftp.FTP method, 120 get_first_frame()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 get_flashdata()tta.units.odx.DataBlock method, 142 get_frame_at_timestamp()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 get_frequency()tta.units.pwm.pwm.PWM method, 150 get_frequency()tta.units.pwm.pwm_driver_base.PWMDriverBase method, 150 get_image()tta.units.imagegrabber.imagegrabber.ImageGrabber method, 122 get_incidents()tta.core.unit_manager.UnitManager method, 224 get_init_arguments()in module tta.core.util, 227 get_input_buffer_size()tta.units.serial.Serial method, 246, 249 get_input_buffer_size()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_input_buffer_size()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_input_buffer_size()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_instance()tta.core.unit_driver_base.UnitDriverBase class method, 222 get_ip()tta.units.ethernet.ethernetbase.NetworkAdapter method, 98 get_items()tta.runner.suite.FileTreeSuite method, 50 get_last_generation_status()tta.units.vector.canoe.TestReport method, 199 get_logger()tta.core.logger.LoggerManager method, 217 get_logger_path()tta.core.logger.LoggerManager method, 217 get_logs()tta.units.android.logcat.Logcat method, 77 get_logs()tta.units.android.logcat.Logcat.Logcatlistener method, 77 get_mac()tta.units.ethernet.ethernetbase.NetworkAdapter method, 98 get_max_current()tta.units.powersupply.powersupply.PowerSupply method, 144 get_max_voltage()tta.units.powersupply.powersupply.PowerSupply method, 145 get_min_current()tta.units.powersupply.powersupply.PowerSupply method, 145 get_min_voltage()tta.units.powersupply.powersupply.PowerSupply method, 145 get_name()tta.core.context.Context method, 208 get_netmask()tta.units.ethernet.ethernetbase.NetworkAdapter method, 98 get_next_test()tta.runner.suite.FileListSuite method, 49 get_next_test()tta.runner.suite.FileTreeSuite method, 50 get_next_test()tta.runner.suite.TestSuite method, 51

Index 297 TTA Documentation, Release 1.15.2 get_node()tta.units.vector.canoe.CANoe method, 187 get_NoisePower()tta.units.audio.audio.Signal method, 86 get_NoisePower()tta.units.audio.audio.SignalProcessing class method, 87 get_odx()tta.units.odx.PDX method, 136 get_odx_files()tta.units.odx.PDX method, 136 get_outgoing_values()tta.testcase.testcase_base.TestCaseBase method, 38 get_output()tta.units.powersupply.powersupply.PowerSupply method, 145 get_output_buffer_size()tta.units.serial.Serial method, 246, 249 get_output_buffer_size()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_output_buffer_size()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 254 get_output_buffer_size()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_parameters()tta.units.ocr.ocr.OCR method, 135 get_phone_information()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 get_power()tta.units.powersupply.powersupply.PowerSupply method, 145 get_process_output()tta.units.android.android.AndroidBase method, 75 get_project_information()in module tta.lib.catalog.arxml, 71 get_project_information()in module tta.lib.catalog.fibex, 70 get_protocols()in module tta.lib.catalog.fibex, 70 get_responses()tta.units.vector.canoe.CANoe method, 187 get_ri()tta.units.serial.Serial method, 247, 249 get_ri()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_ri()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 get_ri()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_rts()tta.units.serial.Serial method, 246, 249 get_rts()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_rts()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 get_rts()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_seq_number()tta.core.context.Context method, 208 get_session()tta.units.odx.SessionDesc method, 142 get_session_descs()tta.units.odx.Flash method, 140 get_session_tc()tta.units.ptc.ptc.PTC method, 148 get_signal()tta.units.vector.canoe.CANoe method, 188 get_single_session()tta.units.odx.Flash method, 140 get_SNRclass in tta.units.audio.audio.Signal, 83 get_SNR()tta.units.audio.audio.Signal method, 86 get_SNR()tta.units.audio.audio.SignalProcessing class method, 87 get_start_time()tta.core.context.Context method, 208 get_state()tta.units.vector.canoe.TestModule method, 198 get_status()tta.units.multimeter.Multimeter method, 131 get_system_var()tta.units.vector.canoe.CANoe method, 188 get_tcs_from_suite()tta.units.ptc.ptc.PTC method, 148 get_tesseract_parameters()tta.units.ocr.ocr.OCR method, 135 get_tesseract_version()tta.units.ocr.ocr.OCR method, 135 get_test_case_class()tta.runner.runner.Runner class method, 45, 48 get_test_module()tta.units.vector.canoe.CANoe method, 188 get_test_report()tta.units.vector.canoe.CANoe method, 188 get_test_results()tta.testcase.testcase_base.TestCaseBase method, 38 get_test_setup_node_state()tta.units.vector.canoe.CANoe method, 189 get_testcase_verdict()tta.units.vector.canoe.TestModule method, 198 get_THDclass in tta.units.audio.audio.Signal, 82 get_THD()tta.units.audio.audio.Signal method, 86 get_THD()tta.units.audio.audio.SignalProcessing class method, 87 get_time()tta.units.datalogger.datalogger.DataLogger method, 96 get_timeout()tta.units.serial.Serial method, 245, 249

298 Index TTA Documentation, Release 1.15.2 get_timeout()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_timeout()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 get_timeout()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 get_timeout_between_events()tta.core.event.source.TimeoutEventSource method, 215 get_timestamp()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 get_total_iterations()tta.runner.suite.FileTreeSuite method, 50 get_ts()tta.units.ethernet.ethernet_protocols.RawPacket method, 111 get_unit_config()tta.core.config_manager.ConfigManager method, 206 get_unit_parameters()tta.core.unit_manager.UnitManager method, 224 get_version()tta.units.ocr.ocr.OCR method, 135 get_voltage()tta.units.powersupply.powersupply.PowerSupply method, 145 get_workspace_folder()tta.core.config_manager.ConfigManager static method, 206 get_worst_result()in module tta.reporting.report, 57 get_write_timeout()tta.units.serial.Serial method, 245, 249 get_write_timeout()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 get_write_timeout()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 get_write_timeout()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 GetMemberPhysValue()tta.units.vector.canoe.SysVariable method, 196 GetMemberValue()tta.units.vector.canoe.SysVariable method, 196 GetSymbolicValueName()tta.units.vector.canoe.SysVariable method, 196 grid_extrap_frame()tta.units.imageprocessing.warping.ImageProcessingWarping method, 129 grid_reorder()tta.units.imageprocessing.warping.ImageProcessingWarping class method, 129 grid_warp()tta.units.imageprocessing.warping.ImageProcessingWarping method, 129 handle()tta.core.logger.TTALogger method, 218 Hardtta.units.uds.UDSType.Reset attribute, 179 hardReset()tta.units.flash.Flash method, 115 has_active_instances()tta.core.unit_manager.UnitManager method, 224 has_context()tta.core.unit_manager.UnitManager method, 224 HintError, 216

ICMPclass in tta.units.ethernet.ethernet_protocols, 106 ICMPDestinationUnreachableclass in tta.units.ethernet.ethernet_protocols, 106 ICMPEchoclass in tta.units.ethernet.ethernet_protocols, 106 ICMPParameterProblemclass in tta.units.ethernet.ethernet_protocols, 107 ICMPRedirectclass in tta.units.ethernet.ethernet_protocols, 107 ICMPSourceQuenchclass in tta.units.ethernet.ethernet_protocols, 107 ICMPTimeExceededclass in tta.units.ethernet.ethernet_protocols, 106 idtta.reporting.bindings.TestResult attribute, 58 idtta.reporting.bindings.TestStepResult attribute, 60 IdentDescclass in tta.units.odx, 142 Imageclass in tta.reporting.bindings, 60 ImageGrabberclass in tta.units.imagegrabber.imagegrabber, 122 imagegrabbermodule, 122 ImageProcessingAnimationclass in tta.units.imageprocessing.animation, 125 ImageProcessingWarpingclass in tta.units.imageprocessing.warping, 129 imeitta.units.qpst.qpst.QPST attribute, 154 import_module_from_file()in module tta.core.util, 227 import_module_from_file_34_35()in module tta.core.util, 227 import_module_from_file_36()in module tta.core.util, 227 import_video()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 127 INCOMPLETEtta.reporting.constants.ResultEnum attribute, 62 InfiniteTimingtta.units.uds.UDSType.InputOutputState attribute, 184 inputOutputControlByIdentifier()tta.units.uds.UDS method, 171

Index 299 TTA Documentation, Release 1.15.2

Interfacesclass in tta.units.ethernet.ethernetbase, 97 InvalidKeytta.units.uds.UDSType.Error attribute, 175 InvalidUnitClassError, 222 InvalidUnitInstanceError, 223 InvertedFilterclass in tta.core.event.filter, 212 IOTesttta.units.uds.UDSType.Session attribute, 176 IPclass in tta.units.ethernet.ethernet_protocols, 105 ip_animationmodule, 125 ip_to_bytes()tta.units.ethernet.ethernetbase.Packet static method, 104 is_active()tta.core.context.Context method, 208 is_active()tta.units.relay.conrad8relay.Conrad8RelayBoard method, 160 is_active()tta.units.relay.Relay method, 159 is_capturing()tta.units.pcap.pcap.PacketCapture method, 144 is_closed()tta.core.event.source.EventSource method, 214 is_compareable()tta.units.audio.audio.AudioData method, 85 is_connected()tta.units.datalogger.datalogger.DataLogger method, 96 is_empty()tta.core.unit_manager.UnitManager method, 225 is_empty()tta.runner.suite.FileTreeSuite method, 50 is_open()tta.units.serial.Serial method, 246, 249 is_open()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 is_open()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 is_open()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 258 is_screen_off()tta.units.android.android.AndroidBase method, 75 is_shell_alive()tta.units.android.android.AndroidBase method, 76 is_supported()in module tta.lib.catalog.arxml, 71 is_supported()in module tta.lib.catalog.fibex, 70 is_usbtta.units.qpst.qpst.QPST attribute, 154 is_worse_result()in module tta.reporting.report, 57 isatty()tta.runner.runner.ProcessStdout method, 45 IsOnlinetta.units.vector.canoe.CANoeSignal attribute, 194 ISOTPclass in tta.units.isotp.isotp, 130 isotpmodule, 130 items()tta.reporting.bindings.MetaDataList method, 61 ItemTypeEnumclass in tta.reporting.constants, 62 join_capture()tta.units.pcap.pcap.PacketCapture method, 144 keytta.reporting.bindings.MetaDataItem attribute, 62 keytta.reporting.bindings.MetaDataList attribute, 61 KeyOffOntta.units.uds.UDSType.Reset attribute, 179 keys()tta.reporting.bindings.MetaDataList method, 61 kill_server()tta.units.android.android.ADB static method, 75

LastWrittenFullNametta.units.vector.canoe.TestReport attribute, 199 linktta.reporting.bindings.Image attribute, 61 linkControl()tta.units.uds.UDS method, 171 list_dir()tta.units.ftp.FTP method, 121 load_config()tta.units.qxdm.qxdm.QXDM method, 157 load_item_store()tta.units.qxdm.qxdm.QXDM method, 157 load_result()in module tta.reporting.report, 57 load_sequence()tta.units.powersupply.powersupply.PowerSupply method, 145 load_testcase()tta.units.ptc.ptc.PTC method, 148 lock_phone()tta.units.qpst.qpst.QPST method, 154 lock_phone()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 log_exception()tta.core.logger.TTALogger method, 218

300 Index TTA Documentation, Release 1.15.2

Logcatclass in tta.units.android.logcat, 76 Logcat.Logcatlistenerclass in tta.units.android.logcat, 76 loggermodule, 217 loggertta.testcase.testcase_base.AdvancedTestCaseBase attribute, 39 loggertta.testcase.testcase_base.TestCaseBase attribute, 38 LOGGER_NAMEin module tta.reporting.constants, 62 LoggerManagerclass in tta.core.logger, 217 Longtta.core.unit_manager.UnitSelfTest.Test attribute, 226 Losttta.core.unit_manager.UnitSelfTest.Result attribute, 226 mac_to_bytes()tta.units.ethernet.ethernetbase.Packet static method, 104 MainNetworktta.units.uds.UDSType.CommunicationNet2 attribute, 180 make_empty_init()tta.core.config_units.generate.Generator static method, 208 MaxValuetta.units.vector.canoe.SysVariable attribute, 196 measurement_running()tta.units.vector.canoe.CANoe method, 189 meidtta.units.qpst.qpst.QPST attribute, 154 Memclass in tta.units.odx, 143 MessageCatalogParserclass in tta.lib.catalog.catalog, 69 meta_datatta.reporting.bindings.TestResult attribute, 58 meta_datatta.testcase.testcase_base.TestCaseBase attribute, 39 MetaDataItemclass in tta.reporting.bindings, 62 MetaDataListclass in tta.reporting.bindings, 61 MethodWrapperclass in tta.core.unit_base, 219 MinValuetta.units.vector.canoe.SysVariable attribute, 196 MissingDocumentationError, 216 mod_init()in module tta.core.util, 227 model_numbertta.units.qpst.qpst.QPST attribute, 154 MostRecentConfirmedDTCtta.units.uds.UDSType.DTCRead attribute, 182 MsgFormatIncorrecttta.units.uds.UDSType.Error attribute, 175 Multimeterclass in tta.units.multimeter, 131 MultipleEcuJobSpecclass in tta.units.odx, 140 nametta.reporting.bindings.TTAReport attribute, 57 Nametta.units.vector.canoe.CANoeNode attribute, 192 Nametta.units.vector.canoe.SysVariable attribute, 196 Nametta.units.vector.canoe.TestModule attribute, 198 Nametta.units.vector.canoe.TestReport attribute, 199 NetworkAdapterclass in tta.units.ethernet.ethernetbase, 98, 100, 102, 103 NetworkManagementtta.units.uds.UDSType.CommunicationNet1 attribute, 179 NO_RUNtta.reporting.constants.ResultEnum attribute, 62 NONEtta.runner.suite.SuiteShuffle attribute, 50 NoResponseFromSubnetComponenttta.units.uds.UDSType.Error attribute, 175 Normaltta.units.uds.UDSType.CommunicationNet1 attribute, 179 NormalAndNetworkManagementtta.units.uds.UDSType.CommunicationNet1 attribute, 180 not_wrapped_method()tta.units.template.template.Template method, 166 NoTesttta.units.uds.UDSType.InputOutputState attribute, 184 NotificationTypetta.units.vector.canoe.EnvVariable attribute, 195 NotificationTypetta.units.vector.canoe.SysVariable attribute, 196 NumberOfDTCByStatusMasktta.units.uds.UDSType.DTCRead attribute, 182

OCRclass in tta.units.ocr.ocr, 134 ocrmodule, 134 ODXLinkclass in tta.units.odx, 141 Offtta.units.uds.UDSType.DTCSetting attribute, 181 OKtta.core.unit_manager.UnitSelfTest.Result attribute, 226

Index 301 TTA Documentation, Release 1.15.2

Ontta.units.uds.UDSType.DTCSetting attribute, 181 on_eventsource_closed()tta.core.event.source.CombinedEventSource method, 213 on_eventsource_closed()tta.core.event.source.CounterEventSource method, 213 on_eventsource_closed()tta.core.event.source.EventObserverInterface method, 213 on_eventsource_closed()tta.core.event.source.TimeoutEventSource method, 215 on_message()tta.core.event.source.CombinedEventSource method, 213 on_message()tta.core.event.source.CounterEventSource method, 213 on_message()tta.core.event.source.EventObserverInterface method, 213 on_message()tta.core.event.source.TimeoutEventSource method, 215 open()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 open()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 open()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 open_can()tta.units.can.bpng.BPNGCom method, 88 open_configuration()tta.units.vector.canoe.CANoe method, 189 open_driver()tta.units.can.bpng.BPNGCom method, 88 open_shell_connection()tta.units.android.android.AndroidBase method, 76 OutOfRangetta.units.uds.UDSType.Error attribute, 175 Overloadtta.units.can.CANMsgType.Frame attribute, 91 OwnIdentclass in tta.units.odx, 143 pack()tta.units.ethernet.ethernet_protocols.BasePacket method, 104 Packetclass in tta.units.ethernet.ethernetbase, 103 PacketCaptureclass in tta.units.pcap.pcap, 143 Parameterclass in tta.testcase.testcase_base, 42 ParameterBoolclass in tta.testcase.testcase_base, 43 ParameterFloatclass in tta.testcase.testcase_base, 43 ParameterIntclass in tta.testcase.testcase_base, 42 ParameterSetclass in tta.testcase.testcase_base, 43 ParameterStrclass in tta.testcase.testcase_base, 43 ParentRelationEnumclass in tta.reporting.constants, 62 parse_document()in module tta.lib.catalog.arxml, 71 parse_document()in module tta.lib.catalog.fibex, 70 parse_entries()tta.units.ethernet.ethernet_protocols.SomeIPSD method, 111 parse_file()tta.lib.catalog.catalog.MessageCatalogParser class method, 69 parse_options()tta.units.ethernet.ethernet_protocols.SomeIPSD method, 111 parse_options()tta.units.ethernet.ethernet_protocols.TCP method, 109 PASSEDtta.reporting.constants.ResultEnum attribute, 63 Pause()tta.units.vector.canoe.TestModule method, 198 PDXclass in tta.units.odx, 136 Pendingtta.units.uds.UDSType.DTCReadStat attribute, 183 phone_modetta.units.qpst.qpst.QPST attribute, 154 phone_statustta.units.qpst.qpst.QPST attribute, 154 PhysMemclass in tta.units.odx, 143 play()tta.units.audio.audio.Signal method, 86 plot()tta.units.audio.audio.Signal method, 86 plot()tta.units.imageprocessing.animation.ImageProcessingAnimation class method, 127 plot_fft()tta.units.audio.plot.Plotter class method, 84 plot_signal()tta.units.audio.plot.Plotter class method, 84 plot_snr()tta.units.audio.plot.Plotter static method, 84 plot_thd()tta.units.audio.plot.Plotter class method, 84 Plotterclass in tta.units.audio.plot, 84 port_labeltta.units.qpst.qpst.QPST attribute, 154 port_nametta.units.qpst.qpst.QPST attribute, 154 postcondition_resultstta.reporting.bindings.TestResult attribute, 58

302 Index TTA Documentation, Release 1.15.2

PowerSupplyclass in tta.units.powersupply.powersupply, 144 powersupplymodule, 144 precondition_resultstta.reporting.bindings.TestResult attribute, 58 PrintableEnumclass in tta.reporting.constants, 62 ProcessStdoutclass in tta.runner.runner, 45 Programmingtta.units.uds.UDSType.LinkMode attribute, 182 programmingSession()tta.units.flash.Flash method, 115 PTCclass in tta.units.ptc.ptc, 146 pull()tta.units.android.android.ADB static method, 75 put()tta.core.event.source.EventSource method, 214 put_data()tta.units.ftp.FTP method, 121 put_file()tta.units.ftp.FTP method, 121 PWMclass in tta.units.pwm.pwm, 149 PWMDriverBaseclass in tta.units.pwm.pwm_driver_base, 150

QPSTclass in tta.units.qpst.qpst, 151 QPSTAutomationServerclass in tta.units.qpst.qpst_automation_server, 155 quit_application()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 quit_application()tta.units.qxdm.qxdm.QXDM method, 158 QXDMclass in tta.units.qxdm.qxdm, 157 qxdmmodule, 157 QXDMFilterclass in tta.units.qxdm.qxdm, 158 QXDMHelperclass in tta.units.qxdm.qxdm, 159

RawPacketclass in tta.units.ethernet.ethernet_protocols, 111 RawValuetta.units.vector.canoe.CANoeSignal attribute, 194 read()tta.units.serial.Serial method, 243, 250 read()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 read()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 read()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 read_item()tta.units.qxdm.qxdm.QXDM method, 158 read_items()tta.units.qxdm.qxdm.QXDM method, 158 readDataByIdentifier()tta.units.flash.Flash method, 118 readDataByIdentifier()tta.units.uds.UDS method, 171 readDataByPeriodicIdentifier()tta.units.uds.UDS method, 171 readDTCInformation()tta.units.uds.UDS method, 171 readline()tta.units.serial.Serial method, 243, 250 readline()tta.units.serial.serial_driver_base.SerialDriverBase method, 261 readline()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 readline()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 readMemoryByAddress()tta.units.uds.UDS method, 172 ReadOnlytta.units.vector.canoe.SysVariable attribute, 196 recognize()tta.units.ocr.ocr.OCR method, 135 recover()tta.core.unit_base.UnitBase method, 220 register_capl_function()tta.units.vector.canoe.CANoe method, 189 register_event_callback()tta.units.vector.canoe.CANoe method, 189 register_instance()tta.core.unit_manager.UnitManager method, 225 register_observer()tta.core.event.source.EventSource method, 214 Relayclass in tta.units.relay, 159 Reload()tta.units.vector.canoe.TestModule method, 198 Remotetta.units.can.CANMsgType.Frame attribute, 91 remove_watchdog()tta.core.unit_base.UnitBase method, 220 Reporttta.units.vector.canoe.TestModule attribute, 198 report_exception()tta.core.unit_manager.UnitManager method, 225

Index 303 TTA Documentation, Release 1.15.2 report_generated()tta.units.vector.canoe.TestReport method, 199 Requesttta.units.uds.UDSType.Routine attribute, 184 request()tta.units.isotp.isotp.ISOTP method, 130 requestDownload()tta.units.flash.Flash method, 115 requestDownload()tta.units.uds.UDS method, 172 RequestSeedtta.units.uds.UDSType.Security attribute, 176 requestSeed()tta.units.flash.Flash method, 116 RequestSeedFlashtta.units.uds.UDSType.Security attribute, 177 RequestSeedKWFStta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial1tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial10tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial11tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial12tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial13tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial14tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial15tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial16tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial2tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial3tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial4tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial5tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial6tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial7tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial8tta.units.uds.UDSType.Security attribute, 177 RequestSeedSpecial9tta.units.uds.UDSType.Security attribute, 177 RequestSequenceErrortta.units.uds.UDSType.Error attribute, 175 requestTransferExit()tta.units.uds.UDS method, 172 requestUpload()tta.units.uds.UDS method, 172 RequiredTimeDelayNotExpiredtta.units.uds.UDSType.Error attribute, 175 reset()tta.units.relay.conrad8relay.Conrad8RelayBoard method, 160 reset()tta.units.relay.Relay method, 159 reset_config()tta.core.config_manager.ConfigManager method, 207 reset_input_buffer()tta.units.serial.Serial method, 246, 250 reset_input_buffer()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 reset_input_buffer()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 reset_input_buffer()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 reset_iteration()tta.runner.suite.FileListSuite method, 49 reset_iteration()tta.runner.suite.FileTreeSuite method, 50 reset_iteration()tta.runner.suite.TestSuite method, 51 reset_output_buffer()tta.units.serial.Serial method, 246, 250 reset_output_buffer()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 reset_output_buffer()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 reset_output_buffer()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 reset_phone()tta.units.qpst.qpst.QPST method, 154 reset_phone()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 reset_phone()tta.units.qxdm.qxdm.QXDM method, 158 ResetToDefaultOrInitValuestta.units.uds.UDSType.InputOutputPar attribute, 183 responseOnEventService()tta.units.uds.UDS method, 173 ResponseTooLongtta.units.uds.UDSType.Error attribute, 175 restore_data()tta.core.logger.LoggerManager method, 217 RESULT_SEVERITYin module tta.reporting.constants, 62 ResultEnumclass in tta.reporting.constants, 62 ResultTypeEnumclass in tta.reporting.constants, 63 Resume()tta.units.vector.canoe.TestModule method, 198

304 Index TTA Documentation, Release 1.15.2

ReturnControlToECUtta.units.uds.UDSType.InputOutputPar attribute, 183 rm_file()tta.units.ftp.FTP method, 121 routineControl()tta.units.flash.Flash method, 118 routineControl()tta.units.uds.UDS method, 173 run()tta.core.event.source.TimeoutEventSource.Timer method, 215 run()tta.core.unit_base.UnitBase method, 220 run()tta.testcase.testcase_base.AdvancedTestCaseBase method, 40 run()tta.testcase.testcase_base.TestCaseBase method, 39 run()tta.units.pcap.pcap.Capture method, 143 run()tta.units.timer.event_source.CyclicSource method, 167 run_file()tta.runner.runner.Runner method, 45, 48 run_file_detached()tta.runner.runner.Runner method, 46, 48 run_in_thread()tta.units.android.logcat.Logcat.Logcatlistener method, 77 run_single()tta.runner.runner.Runner method, 46, 48 run_suite()tta.runner.runner.Runner method, 46, 49 run_test_case()tta.runner.runner.Runner method, 46, 49 Runnerclass in tta.runner.runner, 45, 47 runner_tester_present()tta.units.uds.UDS method, 173 RunTypeclass in tta.core.context, 209 Rxtta.units.can.CANMsgType.Dir attribute, 91 sampleratetta.units.audio.audio.Signal attribute, 86 samplerate()tta.units.audio.audio.Signal method, 82 save_item_store()tta.units.qxdm.qxdm.QXDM method, 158 SDGclass in tta.units.odx, 141 SDGCaptionclass in tta.units.odx, 141 search_all_matches()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 128 search_match()tta.units.imageprocessing.animation.ImageProcessingAnimation method, 128 Securityclass in tta.units.odx, 142 securityAccess()tta.units.flash.Flash method, 119 securityAccess()tta.units.uds.UDS method, 173 SecurityAccessDeniedtta.units.uds.UDSType.Error attribute, 175 Segmentclass in tta.units.odx, 143 SelectedConfigSetsInvalidError, 207 selftest()tta.core.unit_base.UnitBase method, 220 send()tta.units.can.bpng.BPNGCom method, 88 send()tta.units.can.CAN method, 89 send()tta.units.ethernet.ethernetbase.NetworkAdapter method, 99 send_from_pcapfile()tta.units.ethernet.ethernetbase.NetworkAdapter method, 101 send_multiple()tta.units.can.CAN method, 90 send_queue_queue()tta.units.ethernet.ethernetbase.NetworkAdapter method, 100 send_request()tta.units.vector.canoe.CANoeDiagnostic method, 194 send_spc()tta.units.qpst.qpst.QPST method, 154 send_spc()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 SendKeytta.units.uds.UDSType.Security attribute, 177 sendKey()tta.units.flash.Flash method, 116 SendKeyFlashtta.units.uds.UDSType.Security attribute, 177 SendKeyKWFStta.units.uds.UDSType.Security attribute, 177 SendKeySpecial1tta.units.uds.UDSType.Security attribute, 177 SendKeySpecial10tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial11tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial12tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial13tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial14tta.units.uds.UDSType.Security attribute, 178

Index 305 TTA Documentation, Release 1.15.2

SendKeySpecial15tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial16tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial2tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial3tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial4tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial5tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial6tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial7tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial8tta.units.uds.UDSType.Security attribute, 178 SendKeySpecial9tta.units.uds.UDSType.Security attribute, 178 Serialclass in tta.units.serial, 163, 240, 247 SerialDriverBaseclass in tta.units.serial.serial_driver_base, 260 ServiceNotSupportedtta.units.uds.UDSType.Error attribute, 175 ServiceNotSupportedInActiveSessiontta.units.uds.UDSType.Error attribute, 176 Sessionclass in tta.units.odx, 141 SessionDescclass in tta.units.odx, 142 set()tta.units.relay.conrad8relay.Conrad8RelayBoard method, 160 set()tta.units.relay.Relay method, 160 set_alive_status()tta.units.android.logcat.Logcat.Logcatlistener method, 77 set_child_state()tta.units.vector.canoe.TestModule method, 199 set_com_property()tta.units.vector.canoe.CANoe method, 189 set_current()tta.units.powersupply.powersupply.PowerSupply method, 145 set_dtr()tta.units.serial.Serial method, 247, 250 set_dtr()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 set_dtr()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 255 set_dtr()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 set_duty_cycle()tta.units.pwm.pwm.PWM method, 150 set_duty_cycle()tta.units.pwm.pwm_driver_base.PWMDriverBase method, 150 set_filter()tta.units.android.logcat.Logcat method, 77 set_filter()tta.units.ethernet.ethernetbase.NetworkAdapter method, 102 set_frequency()tta.units.pwm.pwm.PWM method, 150 set_frequency()tta.units.pwm.pwm_driver_base.PWMDriverBase method, 151 set_last_timestamp()tta.core.event.source.TimeoutEventSource.Timer method, 215 set_listener_intervall()tta.units.android.logcat.Logcat.Logcatlistener method, 77 set_locked()tta.core.config_manager.ConfigManager method, 207 set_mode()tta.units.multimeter.Multimeter method, 131 set_name()tta.core.context.Context method, 208 set_next_lifecycle_name()tta.core.context.Context method, 208 set_offline()tta.units.qpst.qpst.QPST method, 155 set_offline()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 set_output()tta.units.powersupply.powersupply.PowerSupply method, 145 set_power()tta.units.powersupply.powersupply.PowerSupply method, 145 set_queue_detached()tta.runner.runner.Runner method, 47, 49 set_range()tta.units.multimeter.Multimeter method, 131 set_rts()tta.units.serial.Serial method, 246, 250 set_rts()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 set_rts()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 256 set_rts()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 set_seq_number()tta.core.context.Context method, 209 set_start_time()tta.core.context.Context method, 209 set_test_setup_node_state()tta.units.vector.canoe.CANoe method, 190 set_time()tta.units.datalogger.datalogger.DataLogger method, 96 set_timeout()tta.units.serial.Serial method, 245, 250 set_timeout()tta.units.serial.serial_driver_base.SerialDriverBase method, 262

306 Index TTA Documentation, Release 1.15.2 set_timeout()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 256 set_timeout()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 set_timeout_between_events()tta.core.event.source.TimeoutEventSource method, 215 set_voltage()tta.units.powersupply.powersupply.PowerSupply method, 145 set_write_timeout()tta.units.serial.Serial method, 245, 250 set_write_timeout()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 set_write_timeout()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 256 set_write_timeout()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 SetMemberPhysValue()tta.units.vector.canoe.SysVariable method, 197 SetMemberValue()tta.units.vector.canoe.SysVariable method, 197 SetSymbolicValueName()tta.units.vector.canoe.SysVariable method, 197 setup_windows_console()in module tta.core.util, 228 Shorttta.core.unit_manager.UnitSelfTest.Test attribute, 226 ShortTermAdjustmenttta.units.uds.UDSType.InputOutputPar attribute, 183 shuffle()tta.runner.suite.FileTreeSuite method, 50 shutdown()tta.core.unit_driver_base.UnitDriverBase method, 222 shutdown()tta.core.unit_manager.UnitManager method, 225 shutdown()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 shutdown()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 256 shutdown()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 shutdown_watchdog()tta.core.unit_manager.UnitManager method, 225 Signalclass in tta.units.audio.audio, 85 SignalProcessingclass in tta.units.audio.audio, 87 Softtta.units.uds.UDSType.Reset attribute, 179 SomeIPclass in tta.units.ethernet.ethernet_protocols, 110 SomeIPSDclass in tta.units.ethernet.ethernet_protocols, 110 sourcemodule, 213 SourceIsClosedclass in tta.core.event.event, 210 split()tta.units.audio.audio.Signal method, 86 Standardtta.units.can.CANMsgType.Rate attribute, 92 starttta.reporting.bindings.TestResult attribute, 58 starttta.reporting.bindings.TestStepResult attribute, 60 Starttta.units.uds.UDSType.Routine attribute, 184 start()tta.core.event.source.TimeoutEventSource method, 216 Start()tta.units.vector.canoe.TestModule method, 198 start_capture()tta.units.ethernet.ethernetbase.NetworkAdapter method, 103 start_lifecycle()tta.core.context.Context method, 209 start_measurement()tta.units.vector.canoe.CANoe method, 190 start_now()tta.reporting.bindings.TestResult method, 58 start_now()tta.reporting.bindings.TestStepResult method, 60 start_pcap_dump()tta.units.ethernet.ethernetbase.NetworkAdapter method, 103 start_sequence()tta.units.powersupply.powersupply.PowerSupply method, 145 start_streaming()tta.units.can.CAN method, 90 start_thread()tta.units.android.logcat.Logcat method, 78 start_up()tta.units.serial.Serial method, 164, 251 start_video()tta.units.imagegrabber.imagegrabber.ImageGrabber method, 122 StartDelaytta.units.vector.canoe.CANoeNode attribute, 192 StartDelayActivetta.units.vector.canoe.CANoeNode attribute, 192 startup()tta.core.unit_manager.UnitManager method, 225 startup_watchdog()tta.core.unit_manager.UnitManager method, 225 Statetta.units.vector.canoe.CANoeSignal attribute, 194 Steptta.testcase.testcase_assert.AssertType attribute, 38 Stoptta.units.uds.UDSType.Routine attribute, 184 Stop()tta.units.vector.canoe.TestModule method, 198

Index 307 TTA Documentation, Release 1.15.2 stop_capture()tta.units.ethernet.ethernetbase.NetworkAdapter method, 103 stop_if_worse_thantta.testcase.testcase_base.AdvancedTestCaseBase attribute, 40 stop_measurement()tta.units.vector.canoe.CANoe method, 190 stop_measurement_on_shutdown()tta.units.vector.canoe.CANoe method, 190 stop_pcap_dump()tta.units.ethernet.ethernetbase.NetworkAdapter method, 103 stop_run()tta.runner.runner.Runner method, 47, 49 stop_sequence()tta.units.powersupply.powersupply.PowerSupply method, 146 stop_sequence()tta.units.vector.canoe.CANoe method, 190 stop_thread()tta.units.android.logcat.Logcat method, 78 stop_video()tta.units.imagegrabber.imagegrabber.ImageGrabber method, 122 store_results()tta.runner.runner.Runner method, 47, 49 SubFunctionNotSupported_x12tta.units.uds.UDSType.Error attribute, 176 SubFunctionNotSupportedInActiveSessiontta.units.uds.UDSType.Error attribute, 176 SubNetwork1tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork10tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork11tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork12tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork13tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork14tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork2tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork3tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork4tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork5tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork6tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork7tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork8tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubNetwork9tta.units.uds.UDSType.CommunicationNet2 attribute, 180 SubSteptta.testcase.testcase_assert.AssertType attribute, 38 SuiteShuffleclass in tta.runner.suite, 50 SysVariableclass in tta.units.vector.canoe, 196

TargetAddrOffsetclass in tta.units.odx, 143 TCPclass in tta.units.ethernet.ethernet_protocols, 108 Templateclass in tta.units.template.template, 166 templatemodule, 166 Termclass in tta.units.term.term, 166 termmodule, 166 test_nametta.testcase.testcase_base.AdvancedTestCaseBase attribute, 40 test_resultstta.reporting.bindings.TTAReport attribute, 58 test_step_resultstta.reporting.bindings.TestResult attribute, 58 TestCasetta.core.context.RunType attribute, 209 TestCaseBaseclass in tta.testcase.testcase_base, 38 TESTCASEStta.runner.suite.SuiteShuffle attribute, 51 testerPresent()tta.units.flash.Flash method, 116 testerPresent()tta.units.uds.UDS method, 173 testerPresentDisable()tta.units.flash.Flash method, 116 testerPresentDisable()tta.units.uds.UDS method, 174 testerPresentEnable()tta.units.flash.Flash method, 116 testerPresentEnable()tta.units.uds.UDS method, 174 TesterPresentStatustta.units.vector.canoe.CANoeDiagnostic attribute, 193 TestFailedtta.units.uds.UDSType.DTCReadStat attribute, 183 TestFailedSinceLastCleartta.units.uds.UDSType.DTCReadStat attribute, 183 TestFailedThisOpCycletta.units.uds.UDSType.DTCReadStat attribute, 183 TestModuleclass in tta.units.vector.canoe, 197

308 Index TTA Documentation, Release 1.15.2

TestNotCompletetta.units.uds.UDSType.DTCReadStat attribute, 183 TestNotCompleteThisOpCycletta.units.uds.UDSType.DTCReadStat attribute, 183 TestReportclass in tta.units.vector.canoe, 199 TestResultclass in tta.reporting.bindings, 58 TestResult()in module tta.reporting.report, 55 TestStepContainerclass in tta.reporting.bindings, 58 TestStepResultclass in tta.reporting.bindings, 59 TestSuiteclass in tta.runner.suite, 51 TestSuitetta.core.context.RunType attribute, 209 TestSuiteSimpletta.core.context.RunType attribute, 209 TestVarianttta.units.vector.canoe.TestModule attribute, 198 Textclass in tta.reporting.bindings, 60 timeout()in module tta.core.util, 228 TimeoutEventSourceclass in tta.core.event.source, 215 TimeoutEventSource.Timerclass in tta.core.event.source, 215 Timerclass in tta.units.timer.timer, 167 timermodule, 167 timer.event_sourcemodule, 167 TimerEventclass in tta.units.timer.event_source, 167 titletta.reporting.bindings.Image attribute, 61 titletta.reporting.bindings.Text attribute, 60 to_dict()tta.testcase.testcase_base.ParameterSet method, 43 to_file()tta.units.audio.audio.Signal method, 86 to_unc()in module tta.core.util, 228 to_xml_string()tta.reporting.bindings.TTAReport method, 58 to_yaml()tta.core.config_manager.ConfigManager method, 207 toggle()tta.units.relay.conrad8relay.Conrad8RelayBoard method, 161 toggle()tta.units.relay.Relay method, 160 transferData()tta.units.flash.Flash method, 116 transferData()tta.units.uds.UDS method, 174 TransferDataSuspendedtta.units.uds.UDSType.Error attribute, 176 transferExit()tta.units.flash.Flash method, 116 transferSingleData()tta.units.flash.Flash method, 116 TransitionModetta.units.uds.UDSType.Link attribute, 181 transmit_packets()tta.units.ethernet.ethernetbase.NetworkAdapter method, 100 transmit_queue()tta.units.ethernet.ethernetbase.NetworkAdapter method, 100 trigger_event_on_change()tta.units.vector.canoe.EnvVariable method, 195 trigger_event_on_change()tta.units.vector.canoe.SysVariable method, 197 tta.core.config_managermodule, 205 tta.core.config_units.generatemodule, 207 tta.core.contextmodule, 208 tta.core.event.eventmodule, 210 tta.core.event.filtermodule, 210 tta.core.event.sourcemodule, 213 tta.core.exceptionmodule, 216 tta.core.loggermodule, 217 tta.core.unit_basemodule, 218 tta.core.unit_driver_basemodule, 221 tta.core.unit_exceptionmodule, 222 tta.core.unit_managermodule, 222 tta.core.utilmodule, 227 tta.lib.catalog.arxmlmodule, 71 tta.lib.catalog.fibexmodule, 70 tta.reporting.constantsmodule, 62

Index 309 TTA Documentation, Release 1.15.2 tta.reporting.htmlconvertermodule, 63 tta.reporting.reportmodule, 55 tta.runner.runnermodule, 45 tta.runner.suitemodule, 49 tta.units.android.logcatmodule, 76 tta.units.audio.audiomodule, 84 tta.units.can.bpngmodule, 87 tta.units.datalogger.dataloggermodule, 95 tta.units.imagegrabber.imagegrabbermodule, 122 tta.units.imageprocessing.animationmodule, 125 tta.units.isotp.isotpmodule, 130 tta.units.ocr.ocrmodule, 134 tta.units.odxmodule, 139 tta.units.pcap.pcapmodule, 143 tta.units.powersupply.powersupplymodule, 144 tta.units.qxdm.qxdmmodule, 157 tta.units.template.templatemodule, 166 tta.units.term.termmodule, 166 tta.units.timer.event_sourcemodule, 167 tta.units.timer.timermodule, 167 tta_value_from_configfileclass in tta.core.unit_base, 221 TTAAbortWithBlockedErrorclass in tta.testcase.testcase_assert, 30 TTAAbortWithCanceledErrorclass in tta.testcase.testcase_assert, 31 TTAAbortWithFailedErrorclass in tta.testcase.testcase_assert, 30 TTAAbortWithIncompleteErrorclass in tta.testcase.testcase_assert, 30 TTAAbortWithPassedErrorclass in tta.testcase.testcase_assert, 30 TTAAbortWithResultErrorclass in tta.testcase.testcase_assert, 30 TTAContextError, 216 TTADLLError, 216 TTAError, 216 TTAEventSourceClosedError, 216 TTAEventSourceDispatchError, 216 TTAFileHandlerclass in tta.core.logger, 218 TTAFlashError, 216 TTAIllegalDriverError, 216 TTAImageGrabberError, 216 TTAImageGrabberNoImageError, 216 TTAInvalidTestScriptError, 47 TTAISOTPSequenceError, 216 TTAISOTPTimeoutError, 216 TTALicenseError, 216 TTALoggerclass in tta.core.logger, 218 TTALoggerDataclass in tta.core.logger, 218 TTALoggerDataBaseclass in tta.core.logger, 218 TTAModifiedError, 216 TTAODXError, 216 TTAReportclass in tta.reporting.bindings, 57 TTAReport()in module tta.reporting.report, 55 TTARunnerError, 47 TTARuntimeError, 47 TTAUDSError, 217 TTAUDSTransmissionError, 217 TTAUnitError, 222 TTAUnitInitError, 217

310 Index TTA Documentation, Release 1.15.2

TTAUnitManagerContextError, 217 TTAUnitShutdownError, 217 Txtta.units.can.CANMsgType.Dir attribute, 91 typetta.testcase.testcase_base.ParameterBool attribute, 44 typetta.testcase.testcase_base.ParameterFloat attribute, 43 typetta.testcase.testcase_base.ParameterInt attribute, 43 typetta.testcase.testcase_base.ParameterStr attribute, 43 Typetta.units.vector.canoe.EnvVariable attribute, 195 Typetta.units.vector.canoe.SysVariable attribute, 197 type_hint()in module tta.reporting.report, 57 TypeFilterclass in tta.core.event.filter, 212

UDPclass in tta.units.ethernet.ethernet_protocols, 108 UDSclass in tta.units.uds, 169 UDSTypeclass in tta.units.uds, 175, 176, 178–184 UDSType.Communicationclass in tta.units.uds, 179 UDSType.CommunicationNet1class in tta.units.uds, 179 UDSType.CommunicationNet2class in tta.units.uds, 180 UDSType.DataFormatclass in tta.units.uds, 184 UDSType.DTCClearclass in tta.units.uds, 182 UDSType.DTCReadclass in tta.units.uds, 182 UDSType.DTCReadStatclass in tta.units.uds, 183 UDSType.DTCSettingclass in tta.units.uds, 181 UDSType.DTCSettingOptionclass in tta.units.uds, 181 UDSType.Errorclass in tta.units.uds, 175 UDSType.InputOutputParclass in tta.units.uds, 183 UDSType.InputOutputStateclass in tta.units.uds, 184 UDSType.Linkclass in tta.units.uds, 181 UDSType.LinkModeclass in tta.units.uds, 182 UDSType.Resetclass in tta.units.uds, 178 UDSType.Routineclass in tta.units.uds, 184 UDSType.Securityclass in tta.units.uds, 176 UDSType.Sessionclass in tta.units.uds, 176 UnCompressedtta.units.uds.UDSType.DataFormat attribute, 185 UnEncryptedtta.units.uds.UDSType.DataFormat attribute, 185 unit_basemodule, 219, 221 unit_exceptionmodule, 222 unit_managermodule, 222 UnitBaseclass in tta.core.unit_base, 219 UnitContextclass in tta.core.unit_manager, 223 UnitDriverBaseclass in tta.core.unit_driver_base, 221 UnitIsDownError, 223 UnitManagerclass in tta.core.unit_manager, 223 UnitMetaClassclass in tta.core.unit_base, 221 UnitSelfTestclass in tta.core.unit_manager, 226 UnitSelfTest.Resultclass in tta.core.unit_manager, 226 UnitSelfTest.Testclass in tta.core.unit_manager, 226 UnitWatchDogclass in tta.core.unit_manager, 226 Unknowntta.core.unit_manager.UnitSelfTest.Result attribute, 226 unlock_phone()tta.units.qpst.qpst.QPST method, 155 unlock_phone()tta.units.qpst.qpst_automation_server.QPSTAutomationServer method, 156 unregister()tta.core.unit_base.UnitBase method, 221 unregister_capl_function()tta.units.vector.canoe.CANoe method, 190 unregister_instance()tta.core.unit_manager.UnitManager method, 225

Index 311 TTA Documentation, Release 1.15.2 unregister_observer()tta.core.event.source.EventSource method, 215 unregister_unit()tta.core.unit_manager.UnitManager method, 225 unregister_unit_instances()tta.core.unit_manager.UnitManager method, 226 update_config()tta.core.logger.LoggerManager method, 218 update_path()tta.core.logger.TTAFileHandler method, 218 update_watchdogs()tta.core.unit_manager.UnitManager method, 226 uploadData()tta.units.flash.Flash method, 117 UploadDownloadNotAcceptedtta.units.uds.UDSType.Error attribute, 176 utilmodule, 227 validate()tta.core.config_manager.ConfigManager method, 207 valuetta.reporting.bindings.Image attribute, 61 valuetta.reporting.bindings.MetaDataItem attribute, 62 valuetta.reporting.bindings.Text attribute, 60 Valuetta.units.vector.canoe.CANoeSignal attribute, 195 Valuetta.units.vector.canoe.EnvVariable attribute, 195 Valuetta.units.vector.canoe.SysVariable attribute, 197 VehicleInfoSpecclass in tta.units.odx, 140 VerdictImpacttta.units.vector.canoe.TestModule attribute, 198 VerifyModetta.units.uds.UDSType.Link attribute, 181 VLANclass in tta.units.ethernet.ethernet_protocols, 105 wait_for_generation()tta.units.vector.canoe.TestReport method, 199 wait_interval()tta.units.android.logcat.Logcat.Logcatlistener method, 77 WarnIndicatorRequestedtta.units.uds.UDSType.DTCReadStat attribute, 183 Warningtta.core.unit_manager.UnitSelfTest.Result attribute, 226 with_name()tta.core.context.Context method, 209 wrapped_method()tta.units.template.template.Template method, 166 write()tta.runner.runner.ProcessStdout method, 45 write()tta.units.serial.Serial method, 242, 251 write()tta.units.serial.serial_driver_base.SerialDriverBase method, 262 write()tta.units.serial.serial_driver_pyserial.DriverPySerial method, 256 write()tta.units.serial.serial_driver_virtual.DriverTestVirtual method, 259 write_html_reports()in module tta.reporting.htmlconverter, 63 writeDataByIdentifier()tta.units.flash.Flash method, 119 writeDataByIdentifier()tta.units.uds.UDS method, 174 writeFingerprint()tta.units.flash.Flash method, 117 writeMemoryByAddress()tta.units.uds.UDS method, 174 WrongBlockSequenceCountertta.units.uds.UDSType.Error attribute, 176

XYZmodule, 207

312 Index