In this step, you will learn how to exchange data between the simulation platform and the host PC and vice versa by using host calls.
With a host call, you can send Python data objects from RTT sequences to the host PC. The host call suspends the execution of the RTT sequence until the host PC responds and sends the return arguments.
View the following list for more details:
Usually host calls are used for complex tasks, which require high computing power, to avoid task overruns on the simulation platform.
You can use host calls only with the rttmanagerlib module. You cannot use the Real-Time Test Manager for host calls.
Host calls are evaluated on the host PC by an event handler.
The RTT sequence is paused until the host PC has answered the host call.
One or more objects of arbitrary type can be returned to the RTT sequence in a tuple.
You can exchange data with a maximum size of 10 kbit.
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.
A host call is used to send data from the simulation platform to the host PC.
View the following illustration for more details:

This step is divided into the following parts:
myUtilities.py: To write the Python module, refer to Part 1.
stimulusdemo.py: To write the Python module, refer to Part 2.
RTTSequence.py: To write an RTT sequence for this step, refer to Part 3.
EventHandler.py: To write the Python module, refer to Part 4.
LoaderTools.py: To write a Python module with different utilities for the loader script, refer to Part 5.
RTTLoader.py: To write a loader script for this step, refer to Part 6.
To start the RTT sequence, refer to Part 7.
In the File Explorer, navigate to your Work folder and create the following subfolders:
…\Lesson3Step5\SimulationPlatform\
…\Lesson3Step5\HostPC\
Create a new Python script.
Copy the following code to the Python editor:
""" File: myUtilities.py Destination: Simulation platform Description: Results of the RTT sequences are exchanged between the simulation platform and the host PC via host calls. """ # Module imports import math from rttlib import utilities # Import the host call module from rttlib import hostcall # Use deques instead of lists to make the data real-time capable. from collections import deque# Module global variables currentTime = utilities.currentTime SequenceProperties = utilities.SequenceProperties() # To get the name of the RTT sequence. SequenceName = SequenceProperties.Name # Get the model step size of the real-time application modelStepSize = utilities.modelStepSize # Identifier for RTT print messages. rttPrefix = r" *RTT:* " # Possible test states: testSuccess = 1 testUndefined = 0 testFailure = -1# ---------------------------------------------------------------------------- # Generator functions # ---------------------------------------------------------------------------- def executeHostCallGen(*args): """ Executes a host call. Description: Sends a host call to the host PC and waits for an answer. """ # List to store the results returned from host hostCallResults = [] # Send a host call to the host PC and wait for the return arguments. # Syntax of host calls: yield hostcall.Hostcall([ReturnResult], Execution # argument 1, Execution argument 2, ..., Execution argument n) yield hostcall.Hostcall(hostCallResults, *args) # If a list object is returned by the OnHostCall function, you will get # a nested list as return object. hostCallResults = hostCallResults[0] # Print the answer from the host PC if hostCallResults[0] == testSuccess: print(rttPrefix + "The host PC has received and answered the " + "host call successfully.") yield Nonedef frontRearObservatorGen(signalFront, signalRear, UBattery, sequenceResults): """ 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. sequenceResults: A deque for the test results. Description: Checks if the warning light is flashing synchronously. If a failure occurs, the test parameters are written to a deque and the function returns. """ # Get start time. startTestTime = currentTime.Value# 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. if signalDifference: # Get a failure timer with 3 digits. Use the math module, # which is supported by Real-Time Testing instead of the # built-in function 'round'. failureTimer = (math.modf( (currentTime.Value - startTestTime)*1000))[1]/1000 # Write the results to the deque. sequenceResults[0] = UBattery sequenceResults[1] = failureTimer sequenceResults[2] = testFailure yield None # Terminate the test if a failure has been detected. return yield None yield None
Save the file as: …\Lesson3Step5\SimulationPlatform\myUtilities.py.
You have adapted the utilities module. Results of an RTT sequence are now exchanged with the host PC via host calls.
Continue with the next part to write the Python module stimulusdemo.py
Copy the Python module from the previous step: …\Lesson3Step4\SimulationPlatform\stimulusdemo.py.
Paste the Python module into the folder: …\Lesson3Step5\SimulationPlatform\.
You have created the Python module stimulusdemo.py, with the same functionality as in the previous step. Continue with the next part to write an RTT sequence.
Create a new Python script.
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 exchanged between the RTT sequences and the host PC via host calls. """ # 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 # The SequenceProperties class provides properties of the RTT sequence. SequenceProperties = utilities.SequenceProperties() # To get the name of the RTT sequence. SequenceName = SequenceProperties.Name# 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 = r" *RTT:* "# Possible test states: testSuccess = 1 testUndefined = 0 testFailure = -1 # Import deques from the collections package. Use deques instead of lists to # make the data real-time capable. from collections import deque # Create a deque to temporarily store the test results of the current # RTT sequence for reporting. sequenceResults = deque([0, 0, testUndefined]) #----------------------------------------------------------------------------- # Generator functions #----------------------------------------------------------------------------- def resetGen(): """ Set the variables from the simulation application back to default values. """ WarningLightSwitch.Value = 0 BatteryVoltage.Value = 12.0 yield Nonedef 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. """ yield myUtilities.frontRearObservatorGen(FL, RL, argument, sequenceResults)def HostCall(argument): """ Sents the results of the current RTT sequence via a host call to the host PC (sequenceResults = deque([UBattery, failureTimer, Result])). """ # If the test state is still in the "Undefined" state, the observer # function has not found an error. In this case, the test has been passed # and the corresponding values still need to be written to the deque. if sequenceResults[2] == testUndefined: sequenceResults[0] = argument sequenceResults[1] = "n/a" sequenceResults[2] = testSuccess yield myUtilities.executeHostCallGen(sequenceResults, SequenceName)# ---------------------------------------------------------------------------- # 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 starting the test. 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 function has # detected a failure. yield scheduler.ParallelRace( stimulateWarningLightSwitchGen(), stimulateBatteryVoltageGen(args[0]), ObserverGen(args[0]), utilities.Wait(numberOfSeconds)) yield None # Send the results via host call to the host PC. yield HostCall(args[0]) yield None # Set default values after the test. yield resetGen()
Save the file as: …\Lesson3Step5\SimulationPlatform\RTTSequence.py.
You have written an RTT sequence. Results are exchanged between the RTT sequences and the host PC via host calls. Continue with the next part to write the Python module EventHandler.py.
Create a new Python script.
Copy the following code to the Python editor:
""" File: EventHandler.py Destination: Host PC Description: To implement an event handling. """ import rttmanagerlib import LoaderTools # 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", } # Possible test states: testSuccess = 1 testUndefined = 0 testFailure = -1#----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class RTTMSequencesEvents(rttmanagerlib._IRTSequencesEvents): """ Event class to attach to RTT sequences events. Description: Class to implement a sequence event handling. """ 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))class RTTMHostCallEvents(rttmanagerlib._IRTSequenceEvents): """ Event class to attach to RTT host call events. Description: Class to implement a host call event handling. """ def __init__(self, sequence, boardName): """ Base class constructor """ rttmanagerlib._IRTSequenceEvents.__init__(self, sequence) self.currentBoardName = boardNamedef OnHostCall(self, *data): """ Method OnHostCall Parameters : *data: Tuple with diffent Python objects. The tuple is filled in an RTT sequence. Description: This method is called if you use yield hostcall.Hostcall(result, *data) in your RTT sequence. Return Value: ReturnResultToRT: List of different Python objects which are sent back to the RTT sequence. """# Initialize return value. returnResultToRT = [] # The data from the simulation platform is received as a tuple with # the content: # data = (deque([UBattery, failureTimer, Result]), sequenceName) # Get the battery voltage. UBattery = data[0][0] # Get the failure timer. FailureTimer = data[0][1] # Get the test status. Result = data[0][2] # Get the name of the current sequence. sequenceName = data[1] # Add the results of the current RTT sequence to a dictionary. LoaderTools.addResult(UBattery, FailureTimer, Result, sequenceName) # The return value is used to send data back to the simulation # platform. In this case, the host PC confirms that the host call # has been evaluated successfully. returnResultToRT.append(testSuccess) return returnResultToRT
Save the file as: …\Lesson3Step5\HostPC\EventHandler.py.
You have adapted the Python module EventHandler.py to implement event handling for host calls. Continue with the next step to write the Python module LoaderTools.py.
Create a new Python script.
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 # Use deques instead of lists to make the data real-time capable. from collections import deque # Possible test states: testSuccess = 1 testUndefined = 0 testFailure = -1 AllSequencesReport = {} Summary = "Pass"#----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- def createDemoData(): """ Creates a double-ended queue to pass different battery voltages as sequence arguments. """ #Initialize testList testList = deque([12.0, 7.3, 10.0]) return testListdef 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, hostCallEvent): """ Function to clean up at the end of an RTT sequence. """ # Delete sequences event handler. if sequencesEvents: sequencesEvents.close() sequencesEvents = None # Delete host call event handler. if hostCallEvent: hostCallEvent.close() hostCallEvent = 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()def addResult(UBattery, FailureTimer, Result, sequenceName): """ Stores results of the RTT sequences. Parameters : UBattery : Battery voltage of the current RTT sequence. FailureTimer: Time after a failure has been detected. Result : Test status at the end of the RTT sequence. sequenceName: Name of the current RTT sequence. Description: Writes the results of the current RTT sequence to a dictionary. The results of all RTT sequences are stored in a nested dictionary with the form: {sequence_1: {"Battery Voltage": UBattery, "Timer": FailureTimer, "RESULT": Result}, ..., sequence_n: {"Battery Voltage": UBattery, "Timer": FailureTimer, "RESULT": Result}} """# Initialize a dictionary to save the results of the current # RTT sequence. CurrentSequenceReport = {} # Add the battery voltage of the RTT sequence to the dictionary. CurrentSequenceReport["Battery Voltage [V]"] = UBattery # Add the time at which the failure occurs to the dictionary. CurrentSequenceReport["Timer - sequence failed after [s]"] = \ FailureTimer # Add the result to the dictionary. if Result == testFailure and \ CurrentSequenceReport["Battery Voltage [V]"] < 8.0: CurrentSequenceReport["RESULT"] = "FAIL: Low voltage" elif Result == testSuccess: CurrentSequenceReport["RESULT"] = "PASS" else: CurrentSequenceReport["RESULT"] = "Undefined" # Create a nested dictionary. Add the dictionary with the results of # the current RTT sequence to the dictionary with the overall results. AllSequencesReport[sequenceName] = CurrentSequenceReportdef WriteReport(): """ 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 view all results. Create an own # paragraph for each RTT sequence. for runSequences, seqData in AllSequencesReport.items(): print("\n", runSequences) for key in seqData: print(" " + key + ":", seqData[key]) if seqData[key] == "FAIL: Low voltage": global Summary Summary = "FAIL" print("=" * 80) # Summary of the complete test. print("Summary: %s" % Summary)
Save the file as: …\Lesson3Step5\HostPC\LoaderTools.py.
You have adapted the Python module LoaderTools.py. You can use the tools, for example, to write a test report to the standard output. Continue with the next part to write a loader script.
Create a new Python script.
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 LoaderToolsdef executeDemo(boardName, argument): """ 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) # Connect to the sequence's host call event handle. hostCallEvent = EventHandler.RTTMHostCallEvents(sequence, boardName) # 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) # Delete sequences event handler and variables event handler and remove # current RTT sequence from the simulation platform. LoaderTools.cleanUp(sequence, sequencesEvents, hostCallEvent)# ---------------------------------------------------------------------------- # 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() # Subsequently run RTT sequences for each element in testList. for argument in (testList): executeDemo(boardName, argument) # Write a test report. LoaderTools.WriteReport() print("\nRTT test completed.")
Save the file as: …\Lesson3Step5\HostPC\RTTLoader.py.
You have written a loader script, which implements a host call event handler. Continue with the next part to start the RTT sequences.
Open ControlDesk.
On the Home ribbon, click Status Control – Start Measuring.
ControlDesk globally starts measurement for the platform in the current experiment.
Start your loader script located in: …\HostPC\RTTLoader.py.
You can compare your results with the following animated graphic:

In this step you have learned:
To implement a host call.
To use host calls to exchange data between RTT sequences and the host PC.
With this step, you finished the third lesson of this tutorial and you have learned how to transfer data between the simulation application and the host PC. For a summary of your working results and for further information, refer to the result of this lesson.