Step 3: How to Implement Exception Handling to Send Data

Objective

In this step, you will learn how to implement exception handling to send data from the simulation platform to the host PC.


Basics

Exceptions

View the following list for a detailed description of exceptions:

  • You can use exceptions, for example, in a try and except statement. The following example demonstrates how exception handling for a division by zero error can be implemented:

    from rttlib import errors
    def TestException():
        try:
            10/0
            yield None
        except ZeroDivisionError:
            raise errors.RTTException("integer division by zero")
    def MainGenerator(*args):
        yield TestException()
  • You can also use exceptions to send data from the simulation platform to the host PC:

    • Exceptions are sent directly to the host PC.

    • Data loss can be excluded if messages are sent via exceptions.

    • Only strings can be sent.

    • If an exception is thrown, the RTT sequence is in a fixed status (error status).

    • Not as intuitive as other methods to send data.

    • Raising an exception must be the last line of code in a script. Following code will never be reached.

Functionality of the RTT sequence

The RTT sequence will be started three times in a row.

  • A sequence argument will be passed to the RTT sequence. The battery voltage of the simulation application will be set to the value of the sequence argument.

  • The warning light switch will be stimulated.

  • Each run of the RTT sequence ends when the warning light has flashed synchronously for 5 s or when non-synchronous flashing is detected.

  • Data will be sent to the host PC via exceptions.

Functionality of the loader script

The loader script has the following functionality:

  • Subsequently starting RTT sequences for different battery voltages.

  • Receiving data from the RTT sequences via exceptions.

  • Writing a report of the complete test.

View the following illustration for more details:

Parts

This step is divided into the following parts:

  1. myUtilities.py: To write the Python module, refer to Part 1.

  2. stimulusdemo.py: To write the Python module, refer to Part 2.

  3. RTTSequence.py: To write an RTT sequence for this step, refer to Part 3.

  4. EventHandler.py: To write the Python module, refer to Part 4.

  5. LoaderTools.py: To write a Python module with different utilities for the loader script, refer to Part 5.

  6. RTTLoader.py: To write a loader script for this step, refer to Part 6.

  7. To start the RTT sequence, refer to Part 7.


Part 1: To write the utilities module

  1. In the File Explorer, navigate to your Work folder and create the following subfolders:

    • …\Lesson3Step3\SimulationPlatform\

    • …\Lesson3Step3\HostPC\

  2. Create a new Python script.

  3. Copy the following code to the Python editor:

    """
    File:        myUtilities.py
    Destination: Simulation platform
    Description: Classes are added to the module to send results via 
                 exceptions from the simulation platform to the host PC.
    """
    
    # Module imports
    from rttlib import utilities
    
    # Module global variables
    currentTime = utilities.currentTime
    
    # Identifier for RTT print messages.
    rttPrefix = " *RTT:* "
    rttLoggedPostfix = " - dSPACE Log."
    
    # Enable message printing.
    utilities.Logging.Enable = 1
    utilities.Logging.Direction = utilities.Logging.TO_LOGFILE
    
    # Possible test states:
    testSuccess   = 1
    testUndefined = 0
    testFailure   = -1
    
    
    # ----------------------------------------------------------------------------
    # Classes
    # ----------------------------------------------------------------------------
    class RTTFailureException(Exception):
        """
        Exception class for test failures. The RTTFailureException behaves like
        the standard exception. If RTTFailureException is raised, the name of the 
        class, a message string, and traceback information are sent to the 
        event handler on the host PC.
        """
        pass
    
    
    class TestResult(object):
        """
        This class holds the results of a test and sends the results
        via exceptions to the host PC.
        """
    
    
        def __init__(self):
            """
            Base class constructor to create a new test result object.
            """
            # Create a variable for storing the battery voltage.
            self.UBattery = 0
    
            # Create a variable for storing the test status.
            self.testStatus = testUndefined
    
            # Create a variable to store a failure message of an RTT sequence.
            self.testMessage = ""
    
    
        def addFailureGen(self):
            """
            Generator function to add a failure to the TestResult object.
    
            Description: 
                A failure message is stored to self.testMessage and 
                self.testStatus is set to testFailure. 
            """
            if self.UBattery < 8.0:
                self.testMessage = ("FAIL: Warning light is flashing " +
                                 "nonsynchronously. Low battery voltage.")
            else:
                self.testMessage = "Undefined"
    
            yield None
    
            self.testStatus = testFailure
            yield None
    
    
        def sendToHostGen(self):
            """
            Generator function to send the results to the host PC.
    
            Description: 
                This function sends the test results to the host PC via an
                exception of the type RTTMFailureException. Make sure that the
                sendToHostGen call is the last line of code in your RTT sequence. 
                Following code will never be reached.
            """
            
            # If self.testMessage is empty, the test is passed.
            if not self.testMessage:
                self.testStatus = testSuccess
            yield None
    
            # If self.testStatus = testFailure raise an exception and send a
            # failure message.
            if testFailure == self.testStatus:
                raise RTTFailureException(self.testMessage)
    
    
    # ----------------------------------------------------------------------------
    # Functions
    # ----------------------------------------------------------------------------
    def logInfo(message):
        """
        Writes messages to the standard output and to the dSPACE Log.
        
        Parameters:
            message: String to be printed and logged.
        """
        print(rttPrefix + message)
        utilities.Logging.info(rttPrefix + message + rttLoggedPostfix)
    
    
    # ----------------------------------------------------------------------------
    # Generator functions
    # ----------------------------------------------------------------------------
    def frontRearObservatorGen(signalFront, signalRear, UBattery, TestResults):
        """
        Checks if the front and rear signals are flashing synchronously.
    
        Parameters: 
            signalFront: A model variable for the front signal.
            signalRear : A model variable for the rear signal.
            UBattery   : A model variable for the battery voltage.
            TestResults: An object of the TestResult class.
            
        Description: 
            Checks if the warning light is flashing synchronously.
        """
        
        # Store the battery voltage of the current RTT sequence to the TestResult
        # object and set the test status to testUndefined.
        TestResults.UBattery = UBattery
        TestResults.testStatus = testUndefined
    
    
        # Infinite while loop. Each iteration consists of a complete
        # watch-detect-validate cycle.
        while(1):
            # Check if states of the front and the rear signal are different.
            signalDifference = signalFront.Value - signalRear.Value
    
            if signalDifference:
    
                # Wait for the next generator loop.
                yield None
                
                # If the front and rear signals differ, wait for 50 ms.
                yield utilities.Wait(0.05)
    
    
                # Start a validation loop and check for the next 100 ms 
                # whether all signals have the same value or not.
                startValidation = currentTime.Value
                while currentTime.Value < startValidation + 0.1:
                
                    # Wait for the next generator loop.
                    yield None
    
                    # Check if states of the front and rear signals are different
                    signalDifference = signalFront.Value - signalRear.Value
    
                    # If the signal values are different, the test has failed.
                    # Call addFailureGen to store the failure to the TestResult
                    # object.
                    if signalDifference:
                        TestResults.testStatus = testFailure
                        yield TestResults.addFailureGen()
                        return
            yield None
        yield None
  4. Save the file as: …\Lesson3Step3\SimulationPlatform\myUtilities.py.


Interim result

You have extended the utilities module. Failures during the test are written to a TestReport object and sent via exceptions to the host PC. Use exceptions instead of print messages to avoid time-consuming print statements and data loss.

Continue with the next part to write the Python module stimulusdemo.py.


Part 2: To write the stimulusdemo module

  1. Copy the Python module from the previous step: …\Lesson2Step4\SimulationPlatform\stimulusdemo.py.

  2. Paste the Python module into the folder: …\Lesson3Step3\SimulationPlatform\.


Interim result

You have created the Python module stimulusdemo.py. Continue with the next part to write an RTT sequence.


Part 3: To write an RTT sequence with implemented exception handling

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        RTTSequence.py
    Destination: Simulation platform
    Description: Stimulation of the warning light switch and the battery voltage
                 with a constant value. Results are sent via exceptions to the 
                 host PC.
    """
    
    # Provides functions for common real-time operations.
    from rttlib import utilities
    # Import the variable module from the rttlib package. 
    from rttlib import variable
    # Import scheduler to use ParallelRace().
    from rttlib import scheduler 
    
    
    # Import your Python modules.
    import stimulusdemo
    import myUtilities
    
    # Create variable objects for accessing simulation application.
    WarningLightSwitch = variable.Variable(
            r'Model Root/WarningLightSwitch[0|1]/Value')
    BatteryVoltage = variable.Variable(r'Model Root/BatteryVoltage[V]/Value')
    # To shorten the script only the lights on the left side are investigated.
    FL = variable.Variable(r'Model Root/FrontLightEcu/TurnSignalLeft')
    RL = variable.Variable(r'Model Root/RearLightEcu/TurnSignalLeft')
    
    # Identifier for RTT print messages.
    rttPrefix = " *RTT:* "
    
    # Initialize a TestResult object.
    TestResults = myUtilities.TestResult()
    
    
    #-----------------------------------------------------------------------------
    # Generator functions
    #-----------------------------------------------------------------------------
    def resetGen():
        """
        Set the variables from the simulation application back to default values.
        """
        WarningLightSwitch.Value = 0
        BatteryVoltage.Value = 12.0
        yield None
    
      
    def stimulateWarningLightSwitchGen():
        """
        Stimulates the warning light switch.
        """
        yield stimulusdemo.constGen(WarningLightSwitch, 1)
    
    
    def stimulateBatteryVoltageGen(argument):
        """
        Stimulates the battery voltage with the value passed as sequence argument.
        """
        yield stimulusdemo.constGen(BatteryVoltage, argument)
    
      
    def ObserverGen(argument):
        """
        Observer function to check if the warning light is flashing synchronously.
        
        Parameters:
            argument       : Current sequence argument.
        """
        yield myUtilities.frontRearObservatorGen(FL, RL, argument, TestResults)
    
    
    # ----------------------------------------------------------------------------
    # MainGenerator function
    # ----------------------------------------------------------------------------
    def MainGenerator(*args):
        """
        Main generator function of the RTT sequence.
        
        Description:
            To pass a sequence argument the main generator must be called 
            with *args.
        """
        numberOfSeconds = 5
        
        # Set default values before the test starts.
        yield resetGen()
        
        # Suspend the RTT sequence to avoid malfunctions if the battery voltage
        # was very low before the reset.
        yield utilities.Wait(2)
    
        
        # Start all generator functions with ParallelRace(). The ParallelRace will
        # end if numberOfSeconds is reached or the observer has detected a 
        # failure.
        yield scheduler.ParallelRace(
                stimulateWarningLightSwitchGen(),
                stimulateBatteryVoltageGen(args[0]),
                ObserverGen(args[0]),
                utilities.Wait(numberOfSeconds))
        yield None
    
        yield resetGen()
        yield None
    
        # Send failures via exceptions. Make sure that the sendToHostGen is the
        # last line of code in the RTT sequence. Following lines will never be
        # reached.
        yield TestResults.sendToHostGen()
  3. Save the file as: …\Lesson3Step3\SimulationPlatform\RTTSequence.py.


Interim result

You have written an RTT sequence. Failures are sent via exceptions to the host PC. Continue with the next part to write the Python module EventHandler.py.


Part 4: To write a Python module for event handling

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        EventHandler.py
    Destination: Host PC
    Description: To implement event handling.
    """
    
    import rttmanagerlib
    
    # Dictionary to translate the state of RTT sequences to a readable string.
    State2Str = {rttmanagerlib.constants.sesNew        : "New",
                 rttmanagerlib.constants.sesTerminated : "Terminated",
                 rttmanagerlib.constants.sesError      : "Error",
                 rttmanagerlib.constants.sesStopped    : "Stopped",
                 rttmanagerlib.constants.sesRunning    : "Running",
                 rttmanagerlib.constants.sesPaused     : "Paused",
                }
    
    #-----------------------------------------------------------------------------
    # Classes
    #-----------------------------------------------------------------------------
    class RTTMSequencesEvents(rttmanagerlib._IRTSequencesEvents):
        """
        Event class to attach to RTT sequences events. 
        
        Description:
            Class to implement event handling. The name of the class can be 
            freely chosen. But it is important that the class inherits the 
            properties and methods from the hidden class 
            rttmanagerlib._IRTSequencesEvents.
        """
    
        def __init__(self, EventSource):
            """
            Base class constructor to connect to event source
            """
            rttmanagerlib._IRTSequencesEvents.__init__(self, EventSource)
    
            
        def OnError(self, Sequence):
            """
            Method OnError
            """
            # Only the type (class name) and the value (message string) of 
            # the exception are written to the standard output on the host PC. 
            print("OnError: %s:\n%s" % (Sequence.LastExecutionError.Type, 
                                        Sequence.LastExecutionError.Value))  
    
            
        def OnStateChanged(self, Sequence, NewState):
            """
            Method OnStateChanged
            """
            print("OnStateChanged: State of %s was changed to %s." 
                    % (Sequence.Name, State2Str[NewState]))
    
            
        def OnWrite(self, Sequence, Output):
            """
            Method OnWrite
            """
            print("OnWrite:" + Output)
    
        def OnRemove(self, Name):
            """
            Method OnRemove
            """
            print("OnRemove: %s was removed." % (Name))
    
        def OnCreate(self, Sequence):
            """
            Method OnCreate
            """
            print("On Create: New RTT sequence %s created." 
                    % (Sequence.Name))

Interim result

You have written a Python module to implement event handling. Continue with the next step to write the Python module LoaderTools.py.


Part 5: To write a Python module with tools for the loader script

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        LoaderTools.py
    Destination: Host PC
    Description: To write a test report and other tools used in the loader script.
    """
    
    # This Python library is used to handle the test script download.
    import rttmanagerlib
    
    # Use the standard Python built-in libraries for operation-system commands.
    import time
    
    # Deques (double-ended queues) are a generalization of stacks and queues. Use
    # them instead of lists to save computation time and to make the data 
    # real-time capable.
    from collections import deque
    
    #-----------------------------------------------------------------------------
    # Classes
    #-----------------------------------------------------------------------------
    class TestReport(object):
        """ 
        Class to write a test report. Stores test results of all RTT sequences in 
        a dictionary and writes a report to the standard output.
        """
    
        def __init__(self):
            """
            Creates a new TestReport object.
    
            Description: 
                Initialize a TestReport object, which stores the results of all 
                RTT sequences.
            """
            
            # Create a dictionary to store the results of all RTT sequences.
            self.AllSequencesReport = {}
    
            # Summary of the test results. Remains on PASS only if all 
            # RTT Sequences are executed without failures. Otherwise it is 
            # set to FAIL.
            self.Summary = "PASS"
    
            
        def addResult(self, sequence, argument):
            """
            Stores results of the RTT sequences.
            Parameters: 
                sequence : Variable object of the current RTT sequence.
                argument : Current sequence argument, which is used 
                           to stimulate the battery voltage.
    
            Description: Stores the results of the current RTT sequence:
                self.CurrentSequenceReport = 
                    {"UBattery": argument, "RESULT": "PASS/FAIL"} 
    
                Stores the results of all RTT sequences in a nested dictionary:
                self.AllSequencesReport = 
                    {sequence_1: {"UBattery": argument, "RESULT": "PASS/FAIL"},
                     ..., 
                     sequence_n: {"UBattery": argument, "RESULT": "PASS/FAIL"}}
            """
            # Initialize a dictionary to save the results of the current 
            # RTT sequence.
            self.CurrentSequenceReport = {}
            
            # Add the battery voltage of the current RTT sequence to the 
            # dictionary.
            self.CurrentSequenceReport["UBattery"] = argument
    
            
            if(sequence.LastExecutionError):
                # Add the last error of the current RTT sequence to the 
                # dictionary.
                if("RTTFailureException" == sequence.LastExecutionError.Type):
                    self.CurrentSequenceReport["RESULT"] = (
                            sequence.LastExecutionError.Value)
                    self.Summary = "FAIL"
            else:
                # If no exception was sent the test is passed.
                self.CurrentSequenceReport["RESULT"] = "PASS"
                
            # Create a nested dictionary. Add the dictionary with the results of 
            # the current RTT sequence to the dictionary with the overall results.
            self.AllSequencesReport[sequence.Name] = self.CurrentSequenceReport  
    
        def WriteReport(self):
            """Writes a test report.
    
            Description: 
                Writes a short summary of all results to the standard output on
                the host PC. 
            """
            print("=" * 80)
            print(" -- TEST REPORT --".center(79))
            print("=" * 80)
            
            # Loop over the nested dictionary to get all results. Create an own
            # paragraph for each RTT sequence.
            for runSequences, seqData in self.AllSequencesReport.items():
                print("\n", runSequences)
                for key in seqData:
                    print("    " + key + ":", seqData[key])
                    
            print("=" * 80)
            
            # Summary of the complete test.
            print("Summary: " + self.Summary)
    
    #-----------------------------------------------------------------------------
    # Functions
    #-----------------------------------------------------------------------------
    def createDemoData():
        """
        Creates a deque to pass different battery voltages as 
        sequence arguments.
        """
        #Initialize testList
        testList = deque([12.0, 7.3, 10.0])
        return testList
    
    def waitForSequenceFinished(sequence):
        """
        Suspends the host script as long as the RTT sequence is in the 
        running state.
        """
        
        # Wait for 0.5 s so that the RTT sequence can switch to the running
        # state.
        time.sleep(0.5)
    
        # Sleep while the RTT sequence is in the running state.
        while rttmanagerlib.constants.sesRunning == sequence.State:
            time.sleep(1)
    
        # After the sequence state changes, wait again for 0.5 s
        # so that the event handler can process the last sequence events.
        time.sleep(0.5)
    
    def cleanUp(sequence, sequencesEvents):
        """
        Function to clean up at the end of an RTT sequence. 
        """
        # Delete sequences event handler to avoid the initialization of multiple
        # instances of the sequence event handler.
        if sequencesEvents:
            sequencesEvents.close()
            sequencesEvents = None
    
        # Wait 0.5 s so that the event handler has enough time to process
        # the onRemove event.
        time.sleep(0.5)
        
        # Remove current RTT sequence from the simulation platform.
        if sequence:
            sequence.Remove()
  3. Save the file as: …\Lesson3Step3\HostPC\LoaderTools.py.


Interim result

You have written a Python module with tools for the loader script. You can use the tools to handle the sent exceptions and to write a test report to the standard output. Continue with the next part to write a loader script.


Part 6: To write a loader script

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        RTTLoader.py
    Destination: Host PC
    Description: To load and start several RTT sequences subsequently. Each RTT
                 sequence is started with a sequence argument.
    """
    
    # This Python library is used to handle the test script download.
    import rttmanagerlib
    
    # Use the standard Python built-in libraries for operation-system commands.
    import pathlib
    import time
    
    # Get the path of your RTT sequence. 
    workingDir = pathlib.Path(__file__).parent.parent.resolve()
    testScriptName = str(workingDir / "SimulationPlatform" / "RTTSequence.py")
    
    # Import your Python modules.
    import EventHandler
    import LoaderTools
    
    def executeDemo(boardName, argument, Report):
        """
        Executes the Real-Time Testing demo.
        """
        
        # Create new RTTManagerServer instance.
        rttManager = rttmanagerlib.RealTimeTestManagerServer()
    
        # Generate byte code from the test script (RTT sequence).
        bcgFileName = rttManager.BCGServiceProvider.Generate(testScriptName,[])
    
        # Establish the real-time platform connection.
        board = rttManager.AccessBoard(boardName)
        
        # Connect to the sequences events handle.
        sequencesEvents = EventHandler.RTTMSequencesEvents(board.Sequences)
        
        # Load a sequence to the real-time platform.
        sequence = board.Sequences.Create(bcgFileName)
    
        # Wait for Sequence Events to print messages from RTT sequences.
        time.sleep(1)
        
        # Start the sequence on the real-time platform.
        sequence.Run(argument)
        
        # Suspend code execution as long as the RTT sequence is running.
        LoaderTools.waitForSequenceFinished(sequence)
    
        # Add results to the Report object.
        Report.addResult(sequence, argument)
    
        # Delete sequences event handler and remove current RTT sequence from the 
        # simulation platform.
        LoaderTools.cleanUp(sequence, sequencesEvents)
    
    # ----------------------------------------------------------------------------
    # Main program
    # ----------------------------------------------------------------------------
    """
    The executeDemo() function must be started with an argument which depends on
    your simulation platform. Use the same input as in Lesson 1, Step3.
    """
    
    boardName = "127.0.0.1/turnlamp"
    
    # Create a deque to pass different battery voltages as sequence arguments
    # to the RTT sequences.
    testList = LoaderTools.createDemoData()
    
    # Create a new testReport object.
    Report = LoaderTools.TestReport()
    
    # Subsequently run RTT sequences for each element in testList.
    for argument in (testList):
        executeDemo(boardName, argument, Report)
        
    # Write a test report.
    Report.WriteReport()
       
    print("\nRTT test completed.")
  3. Save the file as: …\Lesson3Step3\HostPC\RTTLoader.py.


Interim result

You have written a loader script. Continue with the next part to start the RTT sequences.


Part 7: To start the RTT sequences

  1. Open ControlDesk.

  2. On the Home ribbon, click Status Control – Start Measuring.

    ControlDesk globally starts measurement for the platform in the current experiment.

  3. Start your loader script located in: …\HostPC\RTTLoader.py.

    You can compare your results with the following animated graphic:


Result

In this step you have learned:

  • To send data from the simulation platform to the host PC via exceptions.


What’s next

In the next step, you will use dynamic variables to make data available on the simulation application and on the host PC.


Redaction