Step 1: How to Implement Event Handling

Objective

In this step, you will learn how to implement event handling for events triggered by RTT sequences. The events can be evaluated on the host PC.


Basics

Event handling

In the earlier lessons, you have already used event handling to get information of RTT sequences on the host PC. In your loader scripts, you have imported the Python module rttdemoutilities.py to implement event handling. Instead of using rttdemoutilities.py it is also possible to write your own Python module for event handling.

Events are triggered by RTT sequences running on the simulation platform. The event handler writes information about an event to the standard output on the host PC. Print messages, for example, are sent from the running RTT sequence to the standard output on your host PC only if you have implemented event handling.

You can use the following methods from the RTTMSequencesEvents class:

Method

Description

OnError

To output the RTT sequence object in which the error occurred.

OnStateChanged

To output a changed state of an RTT sequence.

OnWrite

To output print commands from RTT sequences.

OnRemove

To output information about a removed RTT sequence from the simulation platform.

OnCreate

To output a created RTT sequence.

Functionality of the RTT sequence

Your RTT sequence will mainly write two messages with a time interval of 10 s. All messages triggered by the event handler are marked with a prefix.

View the following illustration for more details:

Parts

This step is divided into the following parts:

  1. EventHandler.py: To write a Python module for event handling, refer to Part 1

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

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

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


Part 1: To write a Python module for event handling

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

    • …\Lesson3Step1\SimulationPlatform\

    • …\Lesson3Step1\HostPC\

  2. Create a new Python script.

  3. 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 from an integer value 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 real-time testing 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
            """
            print("OnError:\nTraceback (most recent call last):\n%s%s: %s" 
                    % (Sequence.LastExecutionError.Stack, 
                       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))

  4. Save the file as: …\Lesson3Step1\HostPC\EventHandler.py.


Interim result

You have written an additional Python module (EventHandler.py) to implement your own event handler. Continue with the next step to write an RTT sequence.


Part 2: To write an RTT sequence with implemented event handling

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        RTTSequence.py
    Destination: Simulation platform
    Description: Write two messages with a delay of 10 s.
    """
    
    # Provides functions for common real-time operations.
    from rttlib import utilities
    
    # Module global variables.
    currentTime = utilities.currentTime
    
    # Identifier for RTT print messages.
    rttPrefix = " *RTT:* "
    
    
    # ----------------------------------------------------------------------------
    # MainGenerator function
    # ----------------------------------------------------------------------------
    def MainGenerator():
        """
        Main generator function of the RTT sequence.
        """
        # The print command triggers the OnWrite method from the 
        # RTTMSequenceEvents class on the host PC.
        print(rttPrefix + "Start of real-time test execution on target platform")
    
        # Read value from the simulation application.
        startTime = currentTime.Value
    
        # Write current time.
        print(rttPrefix + "currentTime.Value = %.3f" % currentTime.Value)
        print(rttPrefix + "Wait for 10 seconds. ")
    
        # Wait for 10s.
        numberOfSeconds = 10
        yield utilities.Wait(numberOfSeconds)
    
        # Write current time again at the end of the while loop.
        print(rttPrefix + "currentTime.Value = %.3f" % currentTime.Value)
        
        print(rttPrefix + "End of real-time test execution.")
  3. Save the file as: …\Lesson3Step1\SimulationPlatform\RTTSequence.py.


Interim result

You have written an RTT sequence which triggers your own event handler. Continue with the next step to write a loader script.


Part 3: To write a loader script that initializes your event handler

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        RTTLoader.py
    Destination: Host PC
    Description: Load and start the RTT sequence with your own event handler.
    """
    
    # 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 event handler
    import EventHandler
    
    def executeDemo(boardName):
        """
        Executes the Real-Time Testing demo.
        """
        
        # Create new RTTManagerServer instance
        rttManager = rttmanagerlib.RealTimeTestManagerServer()
    
        # Convert the RTT sequence into a signed byte code generator (BCG) file
        bcgFileName = rttManager.BCGServiceProvider.Generate(testScriptName,[])
    
        # Establish the real-time platform connection
        board = rttManager.AccessBoard(boardName)
        
        # Instead of using rttdemoutilities, connect to your own sequences event 
        # handler. The corresponding method from your RTTMSequencesEvents class is
        # added as prefix to the output.
        sequencesEvents = EventHandler.RTTMSequencesEvents(board.Sequences)
        
        # Load a sequence to the real-time platform
        sequence = board.Sequences.Create(bcgFileName)
    
        # ------------------------------------------------------------------------
        # Manage the RTT sequence
        # ------------------------------------------------------------------------
        # Start the RTT sequence
        sequence.Run()
        
        # Suspend host script.
        time.sleep(2)
        
        # Pause the RTT sequence.
        sequence.Pause()
        time.sleep(2)
        
        # Continue the RTT sequence.
        sequence.Continue()
        
        # Suspend host script for the execution time of the RTT script
        numberOfSeconds = 11
        time.sleep(numberOfSeconds)
    
       
    # ----------------------------------------------------------------------------
    # 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"
    executeDemo(boardName)
    
    print("RTT test completed.")
  3. Save the file as: …\Lesson3Step1\HostPC\RTTLoader.py.


Interim result

You have written a loader script and you have implemented your own event handler. Continue with the next step to start your RTT sequence.


Part 4: To start the RTT sequence

  1. Open your loader script.

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

    You can compare your results with the illustration below.


Result

In this step, you have learned how to implement event handling and how to get information of the RTT sequence on the host PC.


What’s next

In the next step, you will write data to the dSPACE Log.


Redaction