Step 1: How to Access Variables From a Simulation Application with Real-Time Testing

Objective

In lesson 1, you learned the basic principles of Real-Time Testing without interactions between your RTT sequences and the simulation application. In this step, you will learn how to access variables from the simulation application with RTT sequences. You will also learn how to implement your own Python modules.


Basics

Simulation application

In your RTT sequences, you have read and write access to the variables from the simulation application. This lets you measure and stimulate the variables in each sampling step without latencies. View the following illustration to get a detailed description of one sampling step of a simulation application.

One sampling step is divided into:

  • Reading the model inputs.

  • The model inputs can be modified by an RTT sequence in the preComputation channel before they are passed onto the simulation application.

  • The simulation application takes the model inputs, which are modified by an RTT sequence in the preComputation channel, and calculates the model outputs.

  • After the model outputs are calculated by the simulation application, the outputs can be modified by an RTT sequence running in the postComputation channel.

  • The model outputs are updated after the execution of an RTT sequence in the postComputation channel.

Python modules

You can build your own Python modules for Real-Time Testing. Python modules are integrated into the BCG file, which is downloaded to the simulation platform.

Writing your own user modules has the following advantages:

  • You can group common code into separate modules.

  • Your RTT sequences become shorter and clearer.

  • You can easily reuse Python modules.

Functionality of the RTT sequence

In this step, you will access the simulation application with your RTT sequence. You will stimulate the WarningLightSwitch to switch on the warning light for 10 s.

View the following illustration for more details:

Parts

This step is divided into the following parts:

  1. stimulusdemo.py: To write a Python module to stimulate model variables, 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 variable stimulation

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

    • …\Lesson2Step1\SimulationPlatform\

    • …\Lesson2Step1\HostPC\

  2. Create a new Python script.

  3. Copy the following code to the Python editor:

    """
    File:        stimulusdemo.py
    Destination: Simulation platform
    Description: Generator functions to stimulate variables from the 
                 simulation application.
    """
    
    # Provides functions for common real-time operations.
    from rttlib import utilities
    
    
    # ----------------------------------------------------------------------------
    # Generator functions to stimulate variables from the simulation application.
    #-----------------------------------------------------------------------------
    
    def constGen(var, constValue):
        """
        Stimulate a variable with a constant value.
    
        Parameters: 
            var       : Variable to be stimulated.
            constValue: Constant value of the signal.
        """
        # This generator function runs until it is terminated externally, for
        # example, by a ParallelRace generator function.
        while(1):
            # Start the stimulation of the variable.
            var.Value = constValue
            yield None
  4. Save the file as: …\SimulationPlatform\stimulusdemo.py.


Interim result

You have written your own Python module to stimulate variables from a simulation application. Continue with the next part to write an RTT sequence.


Part 2: To write an RTT sequence to stimulate variables from a simulation application

  1. Create a new Python script.

  2. Copy the following code to the Python editor:

    """
    File:        RTTSequence.py
    Destination: Simulation platform
    Description: To stimulate the warning light switch.
    """
    
    
    # Provides functions for common real-time operations.
    from rttlib import utilities
    # Import the variable module from the rttlib package. Lets you create a 
    # variable object. You must specify the variable with its full path as 
    # specified in the TRC file.
    from rttlib import variable
    # Import scheduler to use ParallelRace().
    from rttlib import scheduler 
    
    
    # Import your Python module
    import stimulusdemo
    
    # Create variable objects for accessing variables of the simulation 
    # application. An easy way to get a variable's name and path is to copy the 
    # variable from ControlDesk's Variables pane and paste it directly into your
    # Python editor.
    WarningLightSwitch = variable.Variable(
            r'Model Root/WarningLightSwitch[0|1]/Value')
    BatteryVoltage = variable.Variable(r'Model Root/BatteryVoltage[V]/Value')
    
    # Identifier for RTT print messages.
    rttPrefix = r" *RTT:* "
    
    
    # ----------------------------------------------------------------------------
    # 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. Infinite nesting levels of generator
        functions are supported by the dSPACE scheduler.    
        """
    
        yield stimulusdemo.constGen(WarningLightSwitch, 1)
        print(rttPrefix + "Stimulation of WarningLightSwitch finished.")
    
    
    # ----------------------------------------------------------------------------
    # MainGenerator function
    # ----------------------------------------------------------------------------
    def MainGenerator():
        """
        Main generator function of the RTT sequence.
        """
        print(rttPrefix + "Start of real-time test execution on target platform")
        
        # Set the duration of the stimulation.
        numberOfSeconds = 10
        
        # Setting default values before the test starts.
        yield resetGen()
    
        print(rttPrefix + "Switch on the WarningLightSwitch for %d seconds." \
              % numberOfSeconds)
    
    
        # Start the stimulation. Generator functions must be called with the
        # yield keyword.
        # All parameters of the ParallelRace() generator must be generator 
        # functions, too. The ParallelRace ends when the specified number of 
        # seconds (numberOfSeconds) has passed.
        yield scheduler.ParallelRace(stimulateWarningLightSwitchGen(), 
                                     utilities.Wait(numberOfSeconds))
        
        # Setting default values.
        yield resetGen()
    
        print(rttPrefix + "End of real-time test execution.")
  3. Save the file as: …\SimulationPlatform\RTTSequence.py.


Interim result

In this part, you have learned how to access and stimulate variables from a simulation application. You have also learned how to import your own Python modules in your RTT sequence. Continue with the next part to write a loader script. With a loader script, you can create and start RTT sequences on your simulation platform.


Part 3: 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 the RTT sequence.
    """
    
    # 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 real-time testing demo utilities.
    import rttdemoutilities
    
    def executeDemo(boardName):
        """
        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 = rttdemoutilities.RTTMSequencesEvents(board.Sequences)
        
        # Load a sequence to the real-time platform.
        sequence = board.Sequences.Create(bcgFileName)
        
        # Start the sequence on the real-time platform.
        sequence.Run()
        
        # Check every second if the RTT sequence has finished. Timeout = 30 s.
        numberOfSeconds = 1
        for i in range(30):
            # Suspend host script for the execution time of the RTT sequence.
            time.sleep(numberOfSeconds)
            # rttmanagerlib provides some constants to check the state of 
            # RTT sequences.
            if(sequence.State != rttmanagerlib.constants.sesRunning):
                time.sleep(numberOfSeconds)
                break
    
    # ----------------------------------------------------------------------------
    # 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: …\HostPC\RTTLoader.py.


Interim result

You have written a loader script. The loader script is now suspended as long as the RTT sequence is running and no longer for a predefined time interval. You can use constants of the rttmanagerlib module to check the state of RTT sequences. Continue with the next part to start your RTT sequence.


Part 4: To start the RTT sequence to access variables from the simulation application

  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 access and stimulate variables from a simulation application.

  • To import your own Python modules.

  • To check in your loader script whether an RTT sequence is still running or not.


What’s next

In the next step, you will stimulate model variables with different generator functions.


Redaction