EuroSim Mk7.1 User’s Manual iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Summary EuroSim Mk7.1 is an engineering simulator framework to support the quick development of hard real- time simulators. EuroSim provides a reconfigurable real-time execution environment with the possibility of man-in-the-loop and/or hardware-in-the-loop additions. Extensive Graphical User Interfaces assist the user in constructing, using and analysing real-time simulations, resolving the user from the specialist software engineering knowledge required to built hard real-time systems.

EuroSim has been developed initially to support the verification of space (sub) systems defined by ESA programmes of various scales. It’s heritage lies in the development of the European Robotic Arm(ERA) project where EuroSim was essential in the development and verification of the large symmetrical arm that can move accross the International Space Station. Up to today, EuroSim installations are still used around the world to support ERA’s mission preparation, verification and training. After initial devel- opment and application for ERA, EuroSim has been succesfully used in the development, verification and training of the Autonomous Transfer Vehicle (ATV) with multiple installations worldwide. Other space programs where EuroSim has been applied since are Galileo, Herschel & Planck, Gaia to name a few major missions. Currently EuroSim has made its way in to other domains as well, with application in the F-35 Lightning-II Embedded Training program and simulations in support of road tunnel system verification. This document contains both the User Guide as well as the Reference Guide documentation and consists of five volumes. The User Guide volume provides overview and insight in the toolchain as well as intro- duction and guidance on the development and usage of real-time simulators. This User Guide volume is recommended reading material for new users of EuroSim. The four Reference Guide volumes provide in detail information on the GUIs, modelling languages, scripting languages and interface capabilities of EuroSim. Experienced users will find these Refence volumes more usefull. Facility administrators are advised to read [OM20], the EuroSim Owner’s Manual. More files and docu- ments that contain information related to EuroSim can be found in the bibliography.

c Copyright Airbus Defence and Space All rights reserved. Disclosure to third parties of this document or any part thereof, or the use of any information contained therein for purposes other than provided for by this document, is not permitted, except with the prior and express written permission of Airbus Defence and Space, PO Box 32070, 2303 DB, Leiden, The Netherlands. ii c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Table of Contents

c Airbus Defence and Space iii

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Table of Contentsv

I User Guide1

1 Introduction 3 1.1 Purpose...... 3 1.2 Scope...... 3 1.3 Where to start...... 4 1.4 Document conventions...... 4

2 Concepts 5 2.1 EuroSim simulation lifecycle...... 5 2.2 Simulator elements...... 6 2.2.1 Model...... 7 2.2.2 Data dictionary...... 7 2.2.3 Schedule...... 7 2.2.4 Simulator...... 7 2.2.5 Scenario...... 8 2.2.6 Simulation...... 8 2.2.7 Test Results...... 8 2.2.8 Project...... 8 2.3 Services and tools...... 9 2.3.1 Project Manager...... 9 2.3.2 Model Editor...... 9 2.3.3 Schedule Editor...... 10 2.3.4 Simulation Controller...... 10 2.3.5 Test Analyzer...... 10 2.4 Application Programmers Interface...... 10 2.5 Version management...... 12

3 Tutorial 13 3.1 The case study...... 13 3.2 Starting EuroSim...... 13 3.2.1 Linux...... 13 3.2.2 Windows...... 13 3.3 Creating a project yourself...... 14 3.4 Creating a shared project...... 14 3.5 Creating a model...... 14 3.5.1 Model...... 15 3.5.2 Adding the sub-models...... 16 3.5.3 Adding the source code...... 17 3.5.4 Adding the API headers...... 19 3.6 Building the simulator...... 21 3.7 Creating the schedule...... 22 3.7.1 Initializing schedule...... 22 3.7.2 Executing schedule...... 23 3.7.3 Closing the Schedule Editor...... 24 3.8 Creating a simulation definition...... 24 3.8.1 Creating a graphical monitor...... 24 3.8.2 Creating an intervening action...... 25 3.8.3 Creating a recorder...... 26 3.9 Executing a simulation run...... 28 3.10 Analyzing the simulation results...... 28

c Airbus Defence and Space v iss: 8 rev: 1 SUM NLR-EFO-SUM-2

3.11 Concluding remarks...... 30

4 Troubleshooting 31 4.1 Introduction...... 31 4.2 Daemon Log Inspection...... 31 4.3 Core file analysis...... 32 4.4 Symbolic Debugging...... 32 4.5 Scheduler Debugging...... 34 4.6 Tuning Memory options...... 34 4.7 Tuning Simulator Startup time-out...... 35 4.8 Execution Timing analysis...... 35 4.9 Coverage analysis...... 36 4.10 Profiling...... 37 4.11 Linux Capabilities...... 38

II GUI Reference Guide 39

5 Common GUI reference 41 5.1 GUI conventions in EuroSim...... 41 5.2 Mouse buttons...... 41 5.3 Keyboard shortcuts...... 42 5.4 Common dialog buttons...... 42 5.5 Common toolbar buttons...... 43 5.6 Common menu items...... 43 5.6.1 File menu...... 43 5.6.2 Edit menu...... 43 5.6.3 Tools menu...... 44 5.6.4 Tools:Version menu...... 44 5.6.5 Help menu...... 45 5.7 Dictionary Browser...... 45

6 Project Manager reference 49 6.1 Introduction...... 49 6.2 Starting the EuroSim Project Manager...... 49 6.3 Views in the Project Manager...... 50 6.4 Menu items...... 51 6.4.1 File menu...... 51 6.4.2 Edit menu...... 51 6.4.3 Insert menu...... 52 6.4.4 Tools menu...... 53 6.4.5 Help menu...... 54

7 Model Editor reference 55 7.1 Starting the Model Editor...... 55 7.2 Views in the Model Editor...... 55 7.2.1 The toolbar...... 56 7.2.2 The tab pane...... 56 7.2.3 The message pane...... 57 7.2.4 The status bar...... 57 7.3 Objects in the Model Editor...... 57 7.3.1 Root ...... 57 7.3.2 Org node...... 58 7.3.3 lib node...... 58 vi c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

7.3.4 File node...... 58 7.3.5 Entry nodes...... 60 7.3.6 Variable nodes...... 61 7.3.7 Object node...... 63 7.3.8 Model node...... 63 7.3.9 Device node...... 63 7.3.10 Port node...... 63 7.3.11 Channel node...... 63 7.3.12 Sequence node...... 63 7.4 API Selection...... 63 7.4.1 Selecting API Variables and Entrypoints...... 63 7.4.2 Selection within a sub-model...... 64 7.4.3 Selection from two or more sub-models...... 64 7.5 Menu items...... 64 7.5.1 File menu...... 64 7.5.2 Edit menu...... 64 7.5.3 View menu...... 65 7.5.4 Insert menu...... 65 7.5.5 API menu...... 67 7.5.6 Tools menu...... 67 7.5.7 Tools:SMP2 Tools menu...... 71 7.6 Environment editor and viewer...... 72 7.6.1 The environment viewer...... 72 7.6.2 The environment editor...... 73 7.7 Configuring File Associations...... 73

8 Model Description Editor reference 75 8.1 Introduction...... 75 8.2 Starting the Model Description Editor...... 76 8.3 Views in the Model Description Editor...... 77 8.4 Objects in the Model Description Editor...... 77 8.4.1 Root node...... 78 8.4.2 Model node...... 78 8.4.3 Entry point node...... 78 8.4.4 Inputs and Outputs group nodes...... 78 8.4.5 Input and output nodes...... 79 8.5 Menu items...... 79 8.5.1 File menu...... 79 8.5.2 Edit menu...... 79 8.5.3 Insert menu...... 80 8.5.4 Tools menu...... 80 8.6 Error Injection...... 80 8.7 Use case example...... 81 8.7.1 Model files...... 81 8.7.2 Model Description file...... 83 8.7.3 Datapool...... 84 8.8 Advanced topics...... 85 8.8.1 Scheduling MDE entrypoints...... 85 8.8.2 Overriding the default error injection function...... 85

c Airbus Defence and Space vii iss: 8 rev: 1 SUM NLR-EFO-SUM-2

9 Parameter Exchange Editor reference 89 9.1 Introduction...... 89 9.2 Starting the Parameter Exchange Editor...... 90 9.3 Views in the Parameter Exchange Editor...... 91 9.3.1 Source view...... 91 9.3.2 Destination view...... 91 9.3.3 Exchange view...... 91 9.4 Objects in the Parameter Exchange Editor...... 92 9.4.1 Exchange group node...... 92 9.4.2 Exchange parameter node...... 92 9.5 Menu items...... 92 9.5.1 File menu...... 92 9.5.2 Edit menu...... 93 9.5.3 Insert menu...... 93 9.5.4 Tools menu...... 93 9.6 Use Case example...... 93 9.6.1 Parameter Exchange file...... 93 9.6.2 Concluding remarks...... 96

10 Calibration Editor reference 99 10.1 Introduction...... 99 10.2 Starting the Calibration Editor...... 100 10.3 Views in the Calibration Editor...... 101 10.3.1 Calibration view...... 101 10.3.2 Data rows view...... 101 10.3.3 Graph view...... 101 10.4 Menu Items...... 101 10.4.1 Edit menu...... 101 10.4.2 Insert menu...... 102

11 Schedule Editor reference 103 11.1 Starting the Schedule Editor...... 103 11.2 Schedule Editor items...... 103 11.2.1 Tasks...... 104 11.2.2 Non real-time tasks...... 106 11.2.3 Mutual exclusions...... 107 11.2.4 Frequency changers...... 108 11.2.5 Internal and External events...... 109 11.2.6 Output events...... 109 11.2.7 Timers...... 109 11.2.8 Flows...... 110 11.3 Menu options...... 110 11.3.1 File menu...... 110 11.3.2 Edit menu...... 110 11.3.3 View menu...... 110 11.3.4 Insert menu...... 111 11.3.5 Tools menu...... 112 11.4 Advanced Scheduler topics...... 114 11.4.1 Scheduler mutual exclusion behavior...... 114 11.4.2 Dependencies, stores and frequency changers...... 115 11.4.3 Frequency changers and mutual exclusive execution of tasks...... 116 11.4.4 Timing the output frequency of a frequency changer...... 117 11.4.5 Example of using an output connector for I/O...... 117 11.4.6 State transitions...... 119 viii c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

11.4.7 Offsets...... 119 11.4.8 Scheduling the action manager (ACTION MGR)...... 120 11.4.9 Clock types...... 121

12 Simulation Controller reference 123 12.1 Starting the Simulation Controller...... 123 12.2 Input Files of the Simulation Controller...... 124 12.2.1 Initial Condition...... 125 12.2.2 Script Action...... 125 12.2.3 Stimulus Action...... 126 12.2.4 Recorder Action...... 126 12.2.5 Monitors...... 126 12.3 Windows of the Simulation Controller...... 127 12.3.1 The toolbar...... 127 12.3.2 The tab pane...... 128 12.3.3 The message pane...... 128 12.3.4 The status bar...... 129 12.4 Output files of the Simulation Controller...... 130 12.5 Dictionary Browser...... 130 12.6 Menu Items...... 130 12.6.1 Edit menu...... 131 12.6.2 View menu...... 131 12.6.3 Insert menu...... 131 12.6.4 Server menu...... 133 12.6.5 Control menu...... 134 12.6.6 Debug menu...... 137 12.6.7 Tools menu...... 137 12.7 Input Files tab page...... 140 12.7.1 Menu items...... 140 12.7.2 Context menus...... 141 12.7.3 Data Dictionary Aliases...... 142 12.7.4 Initial Condition Editor...... 142 12.8 Schedule tab page...... 143 12.8.1 Debugging Concepts...... 143 12.8.2 Debug Control objects...... 144 12.8.3 Menu items...... 145 12.8.4 External debugging facilities...... 146 12.8.5 Timing analysis...... 147 12.9 API tab page...... 149 12.10Scenario tab page...... 150 12.10.1 Menu items...... 151 12.10.2 Context menus...... 153 12.10.3 Action Editor...... 154 12.11MMI tab page...... 159 12.11.1 Menu items...... 160 12.11.2 Context menus...... 161 12.11.3 Action Button Editor...... 162 12.11.4 Monitor Editor...... 162 12.11.5 User-Defined Monitors (Plugins)...... 165 12.12Message tab pane...... 167 12.12.1 Editing message tab properties...... 167 12.12.2 Menu Items...... 168 12.12.3 Context menus...... 168

c Airbus Defence and Space ix iss: 8 rev: 1 SUM NLR-EFO-SUM-2

12.12.4 User defined message types...... 169

13 Test Analyzer reference 171 13.1 Starting the Test Analyzer...... 171 13.2 Using the Test Analyzer...... 171 13.3 Test Analyzer main window...... 171 13.3.1 Opening a plot file...... 172 13.3.2 Importing old plot definition files...... 173 13.3.3 Selecting the test results file...... 173 13.3.4 Using recorder files...... 173 13.3.5 Creating a new plot...... 173 13.3.6 Changing a plot...... 174 13.3.7 Showing and printing plots...... 174 13.4 Plot properties reference...... 174 13.4.1 General plot properties...... 175 13.4.2 Curve editor reference...... 175 13.4.3 Axes properties...... 176 13.5 Variable browser reference...... 177 13.6 Plot view reference...... 177 13.7 Menu items reference...... 178 13.7.1 File menu...... 178 13.7.2 Edit menu...... 179 13.7.3 View menu...... 179 13.7.4 Plot menu...... 179 13.7.5 Curve menu...... 180 13.7.6 Tools menu...... 180 13.7.7 Help menu...... 180 13.8 Toolbar reference...... 180 13.9 Using User Defined Functions...... 180 13.9.1 The function editor...... 181 13.9.2 Format and Validation...... 181 13.10PV-WAVE interface...... 182 13.10.1 PV-WAVE Operators and Functions...... 182 13.10.2 PV-WAVE Variables...... 183 13.10.3 Accessing recorded data...... 183 13.10.4 Examples of using PV-WAVE commands directly...... 183 13.10.5 User defined functions...... 185 13.10.6 PV-WAVE help...... 185 13.10.7 The PV-WAVE process...... 185 13.11gnuplot interface...... 185 13.11.1 gnuplot operators and functions...... 185 13.11.2 Accessing recorded data...... 186 13.11.3 gnuplot help...... 186

14 Dictionary Browser reference 187 14.1 Introduction...... 187 14.2 Starting the Dictionary Browser...... 187 14.3 Working with the Dictionary Browser...... 187

III Modelling Reference Guide 191

15 C, Fortran, Ada interface reference 193 15.1 Introduction...... 193 x c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

15.2 Setup procedure...... 193 15.3 Publication interface...... 194 15.3.1 API Header...... 194 15.3.2 Publication functions...... 196 15.4 Service interface...... 196 15.4.1 Usage in C...... 196 15.4.2 Usage in Fortran...... 199 15.4.3 Usage in Ada-95...... 201 15.4.4 Description of functions...... 203 15.5 Limitations...... 208 15.5.1 Generial limitations...... 208 15.5.2 C limitations...... 209 15.5.3 Fortran limitations...... 209 15.5.4 Ada-95 limitations...... 209 15.6 Example API header...... 210 15.6.1 C Example...... 210 15.6.2 Ada-95 Example...... 211

16 C++ interface reference 215 16.1 Introduction...... 215 16.2 Setup procedure...... 216 16.3 Publication interface...... 218 16.3.1 Standard publication interface...... 218 16.3.2 Adding publication details...... 221 16.3.3 Typed publication...... 222 16.3.4 Esim::Object...... 223 16.3.5 Publication configuration and debugging...... 224 16.4 Service interface...... 225 16.5 Supported data types...... 227 16.5.1 Basic types and arrays...... 227 16.5.2 Predefined structured types...... 227 16.5.3 Container Types...... 228 16.6 Exception handling...... 231 16.7 Simulator Integration...... 231 16.7.1 Identifying Root Models...... 232 16.7.2 Port-Channel...... 233 16.7.3 Channel...... 238 16.7.4 Link...... 240 16.7.5 Line...... 242 16.8 Error Injection interface...... 246 16.8.1 POD Error Injection...... 247 16.8.2 Class Error Injection Interface...... 249 16.9 UML support...... 249 16.9.1 Overview...... 249 16.9.2 Architecture and Transformation...... 250 16.9.3 Design and Generation...... 252 16.9.4 Simulator Building...... 254 16.9.5 Resources...... 255 16.10Tips, Tricks and Guidelines...... 255 16.10.1 Low level publication interface...... 255 16.10.2 Usage of Eclipse...... 257

c Airbus Defence and Space xi iss: 8 rev: 1 SUM NLR-EFO-SUM-2

17 Model Reuse Architecture reference 259 17.1 Introduction...... 259 17.2 Application Domain...... 259 17.3 Architecture...... 260 17.3.1 Overview...... 260 17.3.2 Structural view...... 262 17.3.3 Behavioral view...... 264 17.3.4 Time...... 267 17.3.5 Restrictions...... 267 17.4 Interfaces...... 268 17.4.1 Model Developer Interfaces...... 268 17.4.2 Simulator Developer Interfaces...... 270 17.4.3 End-User Interfaces...... 275 17.5 Getting started...... 276 17.6 Unit Model programming guidelines...... 278 17.7 Model documentation...... 279 17.7.1 System level documentation...... 279 17.7.2 Unit model documentation...... 279 17.7.3 Linking to the autogenerated EuroSim model documentation...... 280 17.7.4 Requirements and to-do’s...... 280 17.8 Snapshot Save and Restore...... 281

18 Simulation Model Portability 2 reference 285 18.1 Using SMP2 in the EuroSim Environment...... 286 18.2 SMP2 tools in the EuroSim Environment...... 287 18.3 Modelling scenarios...... 288 18.3.1 Importing an SMP2 catalogue...... 288 18.3.2 Importing an SMP2 catalogue, package, and assembly...... 290 18.3.3 Importing an SMP2 catalogue, package, assembly, and generated code...... 291 18.3.4 Importing an SMP2 catalogue, package, assembly, and library...... 292 18.4 SMP2 scheduling scenarios...... 293 18.4.1 Native scheduling...... 293 18.4.2 Importing an SMP2 schedule...... 293 18.4.3 Self scheduling SMP2 models...... 293

19 Java interface reference 295 19.1 Introduction...... 295 19.2 Setup procedure...... 295 19.3 Publication interface...... 296 19.4 Service interface...... 297 19.5 Supported data types...... 299

20 Matlab Simulink interface reference 303 20.1 Introduction...... 303 20.2 General considerations...... 304 20.2.1 Coder type...... 304 20.2.2 Parameters...... 304 20.2.3 Reusable functions...... 305 20.2.4 Memory allocation...... 305 20.2.5 Solver type...... 305 20.3 MOSAIC integration...... 305 20.4 Direct Integration...... 306 20.5 Model verification...... 308 20.5.1 Generating stimuli files...... 308 xii c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

20.5.2 Recording data...... 310 20.5.3 Verifying the output...... 311 20.5.4 Analyzing recordings in Matlab...... 311

21 Calibration Library reference 313 21.1 Introduction...... 313 21.2 Application Programmers Interface...... 313

22 PUS library reference 315 22.1 Introduction...... 315 22.2 Application Programmers Interface...... 316 22.2.1 Packet Header functions...... 316 22.2.2 Data Field functions...... 317 22.2.3 Checksum functions...... 317 22.2.4 Utility functions...... 318 22.3 PUS type specifiers...... 319 22.4 Example...... 320

IV Scripting Reference Guide 323

23 Mission Definition Language reference 325 23.1 MDL primer...... 325 23.2 MDL constants, types, variables, operators and expressions...... 327 23.3 Control Flow...... 328 23.4 Functions...... 329 23.5 Input/Output and Simulator Control...... 330 23.6 MDL Built-in functions and commands...... 331 23.7 MDL syntax...... 337

24 Perl batch reference 345 24.1 Introduction...... 345 24.2 Session module...... 345 24.2.1 Monitoring variables...... 347 24.2.2 Modifying variables...... 347 24.2.3 Method reference...... 347 24.2.4 Session Hash reference...... 356 24.3 SimDef module...... 358 24.3.1 Method reference...... 359 24.4 MDL module...... 360 24.4.1 Method reference...... 361 24.5 Dict module...... 361 24.5.1 Method reference...... 362 24.6 InitCond module...... 362 24.6.1 Method reference...... 363 24.7 Link module...... 364 24.7.1 Method reference...... 364 24.8 Connection module...... 364 24.8.1 Method reference...... 365 24.9 The interactive batch shell...... 365 24.10Example...... 366 24.11Extending the perl batch utility...... 367 24.12Command line utilities...... 368 24.12.1 efoList...... 368

c Airbus Defence and Space xiii iss: 8 rev: 1 SUM NLR-EFO-SUM-2

24.12.2 efoKill...... 368

25 Java batch reference 369 25.1 Introduction...... 369 25.2 Session class...... 370 25.2.1 Monitoring variables...... 371 25.2.2 Modifying variables...... 371 25.2.3 Method reference...... 371 25.3 EventHandler class...... 394 25.3.1 Method reference...... 395 25.4 eurosim class...... 405 25.4.1 Method reference...... 405 25.5 EventInfo class...... 406 25.5.1 Method reference...... 406 25.6 WhereInfo class...... 407 25.6.1 Method reference...... 407 25.7 EntryInfo class...... 407 25.7.1 Method reference...... 407 25.8 TaskInfo class...... 407 25.8.1 Method reference...... 408 25.9 EventTypeInfo class...... 408 25.9.1 Method reference...... 408 25.10SessionInfo class...... 409 25.10.1 Method reference...... 409 25.11TmTcLink class...... 412 25.11.1 Constructors...... 412 25.11.2 Method reference...... 412 25.12InitCond class...... 412 25.12.1 Constructors...... 413 25.12.2 Method reference...... 413 25.13ExtSimView class...... 415 25.13.1 Constructors...... 415 25.13.2 Method reference...... 415 25.14ExtSimVar class...... 416 25.14.1 Method reference...... 416 25.15ExtSimVar* classes...... 417 25.15.1 Constructors...... 418 25.15.2 Method reference...... 418

26 Python batch reference 419 26.1 Introduction...... 419 26.2 Session class...... 419 26.2.1 Monitoring variables...... 420 26.2.2 Modifying variables...... 421 26.2.3 Method reference...... 421 26.3 EventHandler class...... 443 26.3.1 Method reference...... 443 26.4 eurosim class...... 453 26.4.1 Method reference...... 453 26.5 EventInfo class...... 454 26.5.1 Method reference...... 454 26.6 WhereInfo class...... 455 26.6.1 Method reference...... 455 26.7 EntryInfo class...... 455 xiv c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

26.7.1 Method reference...... 456 26.8 TaskInfo class...... 456 26.8.1 Method reference...... 456 26.9 EventTypeInfo class...... 457 26.9.1 Method reference...... 457 26.10SessionInfo class...... 457 26.10.1 Method reference...... 458 26.11TmTcLink class...... 460 26.11.1 Constructors...... 460 26.11.2 Method reference...... 461 26.12InitCond class...... 461 26.12.1 Constructors...... 461 26.12.2 Method reference...... 461 26.13ExtSimView class...... 463 26.13.1 Constructors...... 463 26.13.2 Method reference...... 464 26.14ExtSimVar class...... 465 26.14.1 Method reference...... 465 26.15ExtSimVar* classes...... 466 26.15.1 Constructors...... 466 26.15.2 Method reference...... 466

27 Tcl batch reference 469 27.1 Introduction...... 469 27.2 Session class...... 469 27.2.1 Event Handling details...... 470 27.2.2 Monitoring variables...... 470 27.2.3 Modifying variables...... 471 27.2.4 Method reference...... 471 27.3 Event handler callbacks...... 493 27.3.1 Message reference...... 494 27.4 eurosim class...... 503 27.4.1 Method reference...... 503 27.5 EventInfo class...... 504 27.5.1 Method reference...... 504 27.6 WhereInfo class...... 505 27.6.1 Method reference...... 505 27.7 EntryInfo class...... 505 27.7.1 Method reference...... 506 27.8 TaskInfo class...... 506 27.8.1 Method reference...... 506 27.9 EventTypeInfo class...... 507 27.9.1 Method reference...... 507 27.10SessionInfo class...... 507 27.10.1 Method reference...... 508 27.11TmTcLink class...... 510 27.11.1 Constructors...... 510 27.11.2 Method reference...... 511 27.12InitCond class...... 511 27.12.1 Constructors...... 511 27.12.2 Method reference...... 512 27.13ExtSimView class...... 514 27.13.1 Constructors...... 514

c Airbus Defence and Space xv iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.13.2 Method reference...... 514 27.14ExtSimVar class...... 515 27.14.1 Method reference...... 515 27.15ExtSimVar* classes...... 516 27.15.1 Constructors...... 516 27.15.2 Method reference...... 517

V Interface Reference Guide 519

28 Hardware Interface reference 521 28.1 Introduction...... 521 28.2 External Clock Interface...... 522 28.2.1 Introduction...... 522 28.2.2 External Clock Selection...... 522 28.2.3 External Clock Plugin...... 523 28.2.4 NTP Synchronized clock...... 524 28.2.5 Irig-B (deprecated)...... 524 28.3 External Event Handler...... 525 28.3.1 Introduction...... 525 28.3.2 ScheduleEditor Event Handler usage...... 526 28.3.3 Programming User Defined Event Handlers...... 527 28.3.4 Programming Event Handler Plugins and Devices...... 529 28.4 External Interface libraries...... 532 28.4.1 Introduction...... 532 28.4.2 Serial interface...... 533 28.4.3 Mil1553 interface...... 533 28.4.4 VMICVEM6000 1553 interface (deprecated)...... 535

29 Front-End Model Interface Reference 537 29.1 Introduction...... 537 29.2 Use Case description...... 538 29.3 Architecture...... 540 29.4 Common features...... 541 29.4.1 Model Mode and State...... 541 29.4.2 Filtered logging support...... 542 29.4.3 Scheduling...... 542 29.4.4 Configuration...... 543 29.4.5 Protection...... 543 29.4.6 Device Plugins...... 543 29.5 Discrete Front-End model...... 544 29.5.1 Introduction...... 544 29.5.2 Setup...... 545 29.5.3 Configuration...... 546 29.5.4 Mode Connection interface...... 548 29.5.5 Dictionary interface...... 549 29.5.6 Simulation model interface...... 550 29.5.7 Front-end interface...... 552 29.5.8 Device interface...... 554 29.5.9 Error Injection...... 555 29.5.10 Supported Discrete Devices...... 557 29.6 Mil1553 Front-End model...... 560 29.6.1 Introduction...... 560 29.6.2 Setup...... 561 xvi c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

29.6.3 Configuration...... 562 29.6.4 Sync interface...... 564 29.6.5 Dictionary interface...... 565 29.6.6 Simulation model interface...... 568 29.6.7 Front-end interface...... 570 29.6.8 Device interface...... 571 29.6.9 Bus monitoring...... 577 29.6.10 Error injection...... 579 29.6.11 Utility functions...... 581 29.6.12 Tests...... 584 29.6.13 Supported Mil1553 Devices...... 584 29.7 Timekeeper Front-End model...... 586 29.7.1 Introduction...... 586 29.7.2 Setup...... 587 29.7.3 Configuration...... 590 29.7.4 Dictionary interface...... 590 29.7.5 Front-end interface...... 590 29.7.6 Device interface...... 590 29.8 Front-End Model Stub...... 591 29.8.1 Introduction...... 591 29.8.2 Architecture...... 592 29.8.3 Commander Usage...... 593 29.8.4 Sequencer usage...... 595 29.8.5 Executer usage...... 597 29.8.6 Test Scripting...... 599

30 C++ Interface reference 609 30.1 Introduction...... 609 30.2 Session class...... 609 30.2.1 Monitoring variables...... 610 30.2.2 Modifying variables...... 610 30.2.3 Method reference...... 611 30.3 EventHandler class...... 634 30.3.1 Method reference...... 634 30.4 eurosim class...... 644 30.4.1 Method reference...... 644 30.5 EventInfo class...... 646 30.5.1 Method reference...... 646 30.6 WhereInfo class...... 646 30.6.1 Method reference...... 646 30.7 EntryInfo class...... 647 30.7.1 Method reference...... 647 30.8 TaskInfo class...... 647 30.8.1 Method reference...... 647 30.9 EventTypeInfo class...... 648 30.9.1 Method reference...... 648 30.10SessionInfo class...... 649 30.10.1 Method reference...... 649 30.11TmTcLink class...... 651 30.11.1 Constructors...... 651 30.11.2 Method reference...... 652 30.12InitCond class...... 652 30.12.1 Constructors...... 652

c Airbus Defence and Space xvii iss: 8 rev: 1 SUM NLR-EFO-SUM-2

30.12.2 Method reference...... 652 30.13ExtSimView class...... 654 30.13.1 Constructors...... 655 30.13.2 Method reference...... 655 30.14ExtSimVar class...... 656 30.14.1 Method reference...... 656 30.15ExtSimVar* classes...... 657 30.15.1 Constructors...... 657 30.15.2 Method reference...... 658

31 C Cient Interface reference 659 31.1 Introduction...... 659 31.2 Simulator start-up...... 659 31.3 Subscribing to channels...... 665 31.4 Real time control channel...... 665 31.5 Mission channel...... 667 31.6 Monitor channel...... 670 31.7 Scheduler control channel...... 672 31.8 Simulator shutdown...... 675 31.9 Manual pages...... 675

32 External Simulator Access reference 677 32.1 Introduction...... 677 32.2 Selection of shared data items...... 677 32.3 Exports file...... 678 32.4 Creating multiple local data views...... 679 32.5 Synchronization...... 679 32.6 Summary of procedure...... 680 32.7 Case study: setting up shared data to another simulator...... 681 32.7.1 Create an exports file...... 681 32.7.2 Link the external simulator as a EuroSim client...... 681 32.7.3 Determine host byte order...... 682 32.7.4 Set up local data view with links to EuroSim data...... 682 32.7.5 Receiving and sending shared data at runtime...... 684 32.7.6 Close the connection...... 684 32.8 Performance...... 685 32.8.1 Maximum throughput...... 685 32.9 Building the client...... 685 32.9.1 Unix and Linux...... 685 32.9.2 Windows...... 685

33 TM/TC Link reference 687 33.1 Introduction...... 687 33.2 Characteristics of the TM/TC Link...... 688 33.3 Summary of procedure...... 688 33.4 Case study: setting up a TM/TC link...... 688 33.4.1 Set up the external simulator as a EuroSim client...... 689 33.4.2 Create and customize a link between the two TM/TC clients...... 689 33.4.3 Sending packets...... 690 33.4.4 Receiving packets...... 690 33.4.5 Close down link...... 692

xviii c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

34 COM Interface reference 693 34.1 Introduction...... 693 34.2 Installation...... 693 34.2.1 VBA...... 693 34.2.2 C++...... 693 34.3 Programmers reference...... 693 34.4 Use case – Excel example...... 694 34.4.1 The simulator...... 694 34.4.2 The MS Excel client application...... 694 34.4.3 Adding a View...... 696 34.4.4 Receiving updates from the simulator...... 697 34.4.5 Creating an event handler in VBA...... 698 34.4.6 Sending updates to the simulator...... 699

VI Embedding Reference Guide 703

35 Loadable EuroSim 705 35.1 Introduction...... 705 35.2 Interface...... 705

36 Embedded EuroSim 707 36.1 Introduction...... 707 36.2 Architecture...... 708 36.2.1 Embed Data Files...... 709 36.2.2 IO Adaptor: Shared Memory...... 709 36.3 Configuration File Settings...... 710 36.3.1 Heap Size...... 710 36.3.2 Partition Idle Time...... 710 36.4 Initialization...... 711 36.5 Error and Message handling...... 711 36.6 Embedded API...... 711 36.7 Compilation and Linking of Embedded Applications...... 711

VII Appendices 713

A Files and formats 715 A.1 EuroSim project files...... 715 A.2 EuroSim Configuration file format...... 716 A.2.1 Keys...... 717 A.2.2 File types...... 717 A.3 Recorder file format...... 718 A.4 The test results file...... 719 A.5 Exports file format...... 719 A.6 Alias file format...... 720 A.7 Initial Condition file format...... 720 A.8 Simulation Definition file format...... 721 A.9 MMI file format...... 724 A.10 User Program Definition file format...... 727

B XML Schemas 729

C Simulator launch options 731

c Airbus Defence and Space xix iss: 8 rev: 1 SUM NLR-EFO-SUM-2

D As Fast As Possible (AFAP) simulation 733 D.1 Introduction...... 733 D.2 Deadlines and simulation time...... 733 D.3 Example 1: AFAP simulation with 2 independent tasks...... 733 D.4 Example 2: implicit mutual exclusion of two tasks...... 734 D.5 Example 3: A chain of tasks is a pipeline and has parallelism...... 735 D.6 Other effects...... 736 D.7 Performance...... 737 D.8 Example of performance computation...... 737

E Scheduler Errors 739 E.1 Schedule Editor errors...... 739 E.2 Scheduler run-time messages...... 740 E.3 Low level errors...... 742

F Introduction to CVS 745 F.1 Introduction...... 745 F.2 Initializing the repository root...... 745 F.3 Setting up a CVS repository...... 745 F.4 Using CVS under Windows...... 746 F.5 More information...... 746

G Software Problem Reports 747

H Abbreviations 749

I Definitions 751

RevisionRecord 759

Bibliography 761

Index 762

xx c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part I

User Guide

c Airbus Defence and Space 1

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 1

Introduction

1.1 Purpose

The purpose of this document is to provide a user of the EuroSim facility with an understanding of the functions available and the logical order in which they should be used in order to achieve the objective of developing and executing a simulation model for a particular application.

It is expected that the user has some basic UNIX knowledge and familiarity with simulation in general. This manual is also available on-line, including hypertext.

1.2 Scope

This document describes the use of the EuroSim Mk7.1.3 facility. It provides details of the functions that are available for the user, and relates these functions to a typical operational scenario. It also provides guidance on the development of the application model itself, including the recommended structure of the model, and the library routines provided by the facility. In this manual the main functions of the EuroSim facility are described from the user’s point of view. The document is divided in five volumes and an appendix:

• Volume 1: User Guide: An introduction into the concepts and features of EuroSim, followed by a Tutorial and Troubleshooting guide to get familiar with the toolset.

• Volume 2: GUI Reference Guide: A detailed description of every GUI in EuroSim to find specific GUI operation details when working with the tool.

• Volume 3: Modelling Reference Guide: A detailed description of the APIs for every supported modelling language, including service libraries in support of model integration.

• Volume 4: Scripting Reference Guide: A detailed description of the languages available for real- time scripting inside the simulation, as well as batch scripting to automate the execution of the simulator.

• Volume5: Interface Reference Guide: An in depth description of the interfaces provided to connect EuroSim with other applications and integrate hardware in the loop.

Finally, a number of appendices contain the remaining information, generally consisting of reference details only required in special circumstances, such as file formats of the EuroSim configuration files. Furhtermore, abbreviations and terms are defined in Appendix H and Appendix I respectively. The remaining appendices go into more detail on some of the features of EuroSim.

c Airbus Defence and Space 3 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

1.3 Where to start

Novice users should start with Chapter 2, and then follow (and possibly re-create) the case study from Chapter 3. The GUIs will generally be self explanatory with tooltips, but it might be necessary to read Chapter 5 to get acquainted with some of EuroSim’s user interface aspects. Users who already have knowledge of EuroSim can immediately proceed to the reference chapters, where each of the EuroSim tools is described in detail. The table of contents and the index can be used to find certain subjects in the user manual. Facility managers are advised to read also [OM20], the EuroSim Owner’s Manual. More files and docu- ments that contain information related to EuroSim can be found in the bibliography.

1.4 Document conventions

The selection of a menu option from the GUI is referred to as for example ‘Select the menu option File:Close’, which means to select from the menu with the name File the option Close. Key combinations are shown as ‘Alt+Backspace’, which means to hold down the key labeled Alt and then simultaneously pressing the Backspace key. Computer input and output is shown as a fixed pitch font. Buttons are referenced with their label in bold face.

4 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 2

Concepts

This chapter introduces the concepts and elements which are common to EuroSim. These include version management and the API interface. Concepts and elements specific to an EuroSim tool or editor are described in the reference chapters for these tools and editors. First the EuroSim simulation lifecycle concept is introduced, which defines the phases of usage of a EuroSim simulator and thereby provides a first introduction into the work flow of EuroSim. Subsequently the elements in the simulation lifecycle are further elaborated. These elements are then mapped on the tools and services contained in EuroSim. Thereafter more detailed concepts are described such as the API headers, dataflow approach and built in versioning.

2.1 EuroSim simulation lifecycle

EuroSim is a simulator framework which allows the user to construct a real-time simulator by combin- ing model code with the EuroSim libraries into a simulator. This simulator can then be subsequently combined with simulation scenarios into simulations. The results of these simulations can be recorded, which allows the user to analyse these in post processing. This process is called the EuroSim simula- tion licecycle and is supported with EuroSim tools and services. Figure 2.1 illustrates the phases in this process and the associated Graphical User Interfaces that EuroSim provides to the user.

Figure 2.1: EuroSim simulation life cycle

c Airbus Defence and Space 5 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

In Figure 2.1 the following phases are shown: Development In the Development phase the simulator is constructed in the steps. First model code is im- ported. It is assumed that model code exists, although it is very well possible to construct model code or elaborate with the EuroSim tools. Model code is assumed to be source code in a variety of languages, and depending on the language different mechanisms exist to define the functions and variables that are of interest within EuroSim. After import, the models need to be integrated. Because EuroSim focusses on hard realtime execution this is achieved via the creation of dataflows between variables of of models. The timing of execution and data transfer is then finally specified with an exection schedule which definines the real-time execution of the simulator. Preparation During the Preparation phase, scenarios for a particular simulation are defined. These scenar- ios including initial conditions, stimuli, recording and on-line monitoring requirements. The scenarios are written in the EuroSim Mission Definition Language, a C-style real-time script- ing language. These scripts can be written offline in advance or online during the simulation. The latter is most practicalas writing scripts is an iterarive process. For this reason the Test Preparation and Test Execution phases use the same integrated GUI. Execution During the Execution phase the simulator is being executed with the defined scenario. The execution of such simulation is monitored while data is recorded to disk for post analysis. The execution can be performed using a dedicated EuroSim GUI or from batch scripting in a variety of scripting languages such as Tcl, Perl, Python and even from other tools built in for instance Java or C++. Because the execution of EuroSim simulators follows the client-server it is possible to start from a batch script and connect with the GUI in parallel for monitoring purpose. It is even possible to have multiple users connecting simultaneously to the same simulator, one being the operator in charge, the others being observers that can only monitor the simulator execution. Analysis During Analysis phase the data recorded during the simulation run can be processed and ana- lyzed. A dedicated GUI allows the user to select the variables to be analayzed from the recorded data and plot the results according to predefined plot definitions. It is also possible to convert data in formats that support analysis with other tools. During all phases Project Management tools allow the user quick access to the tools and all files in a project.

2.2 Simulator elements

During this life-cycle, a number of objects are used to represent various parts of the simulation. These are: • A model. • A schedule. • A data dictionary. • The simulator. • A scenario. • A simulation definition. • The test results. Each of these objects is described in more detail in the following sections.

6 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

2.2.1 Model The model (or ‘application model’) contains all the information needed to describe a real-world system for the purpose of simulation. Using a hierarchical structure, this information comprises of (sub)system descriptions (using any of the languages supported by EuroSim: C, C++, Fortran, Ada-95 and Java1, and information on parameters and variables which can be modified or monitored during a simulation. The model hierarchy can be used to group common elements together. To this end, the model hierarchy is a tree-like structure (with the model itself at the top), with the various (sub)system descriptions grouped together by nodes in the tree. The model hierarchy itself is created with the Model Editor (see Chapter 7). For model integration, the Model Editor supports several sub editors to assist the user in model interface definition, data exchange between the models, error injection and calibration. The products of these sub editors are included as files in the model hierarchy.

2.2.2 Data dictionary During a simulation, data can be monitored and/or recorded, and parameters can be set. The data ele- ments which should be accessible during the simulation have to be defined in the data dictionary for this purpose. This is done through the use of so-called API headers (see also Section 2.4). The data dictionary is defined using the Model Editor (see Chapter 7). Browsing the data dictionary can be done using the Dictionary Browser (see Section 5.7) which is available in several of the editors and tools.

2.2.3 Schedule The timing information of a model is defined through one or more tasks and their execution timing, tied together in a schedule definition. A task is a sequential list of operations provided by the (sub)systems of the model. These operations have to be executed consecutively, starting with the first operation, and ending with the last one. Within a task, there are no timing constraints and/or synchronization points. The schedule contains information on when and how tasks should be activated in order to:

• achieve real-time, parallel, simulation when executing the simulation, and

• realize a requested change in simulator state (e.g. from executing to standby); see Section 2.2.4 for more information on simulator states.

The tasks and schedule are defined using the Schedule Editor (see Chapter 11), which is available through the Project Manager. Note that a single model could be defined with alternative schedules, each combi- nation creates a different simulator as the schedule defines the activation of model code over time.

2.2.4 Simulator A simulator is one or both of a hardware device and a computer program built out of model-dependent software (i.e. the model code itself, the schedule and the data dictionary) and the model-independent software for the performance and control of the simulation (i.e. the EuroSim provided software). A simulator together with a simulation definition can be used to start a simulation run. The simulator is always in one of 5 predefined states (see Figure 2.2). These states determine the current phase in the general process of simulation. These same states (except the unconfigured state) are also used within the Schedule Editor to define the schedule. 1Java interface is not realtime

c Airbus Defence and Space 7 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

init Unconfigured Initializing

(automatic) abort Standby stop (automatic)

Exiting go pause

abort Executing

Figure 2.2: Simulator states

State transitions can be triggered by issuing a state transition command, either from the Simulation Controller, the model, or the schedule. The labels in Figure 2.2 correspond to the buttons available in the Simulation Controller (see Section 12.3.1) as well as the MDL commands (see Chapter 23). The only missing state transition is the reset as it is too complicated to put in the drawing. Reset can be issued from standby state and is a combination of a stop and an init command where the simulation is not completely stopped and restarted. The simulator can be run in one of two modes: real time or non-real time. When a simulation is started in non-real time, the simulation server will try to run the simulation as close to real time as possible. This means that task timing overruns in the simulation will not generate real-time errors. Also, a simulation running non-real time will not claim a whole simulation server: other simulations can also be running (also non-real time). In non-real time mode, it is also possible to instruct EuroSim to run the simulation as fast as possible (see Section 12.6.5 for more information).

2.2.5 Scenario Scenarios are lists of scripts functions that can be activated on time or data conditions. The scenario scripts interact in real-time with the model code through the Model API as defined in the data dictionary. Stimuli and Recording definitions are scripts as well in EuroSim, although there creation is supported by dedicated editors to make create of the scrips easier.

2.2.6 Simulation A simulation definition contains all information required during a simulation: this combines the simulator with initial conditions, scenarios (monitors, simulators, scripts) and MMI definitions. More than one simulation definition can be defined for a particular model, each resulting in a different simulation result. Simulation definitions are created using the Simulation Controller, which is described in Chapter 12.

2.2.7 Test Results When recorders are defined in a simulation definition, the simulation produces teh recorderfile during execution as well as an index file which allows the EuroSim analysis GUI to easily detect which variables are available for plotting

2.2.8 Project A EuroSim project file contains the references to all files used in the Simulation lifecycle. It consists of:

• a description

• a directory where the files reside (also called the project root)

8 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• a repository where the versioned files reside • a version control system name All this information is stored in the project database.

2.3 Services and tools

EuroSim offers users two levels of support: • The first level of support is through a number of tools which can be used to define the simulation. These tools all have an (often graphical) user interface and include editors such as the Model Editor and the Schedule Editor. • The second level of support is through a number of services which are available to the model developer. Services are functions in the EuroSim software that can be called from within model code. See Section 2.4 and the services sections of each supported modelling language in the Modelling reference volume. In the next sections, an overview is given of the available tools.

2.3.1 Project Manager The Project Manager is used to define new projects. The Project Manager is the main EuroSim window, and is described in detail in Chapter 6. The list of projects displayed in the project manager is maintained by the user. The projects file is located by default in the .eurosim directory in the home directory of the user. The location can be changed by defining the $EFO_HOME variable. To use a shared project file, a user has to set the $EFO_HOME environment variable to point to a shared projects file.

2.3.2 Model Editor The Model Editor is used to define a model and its hierarchy together with the definition of the variables and parameters that are available for monitoring, recording, etc. during the simulation run. The Model Editor is described in detail in Chapter 7. Several sub editors are available to further define the model integration and publication.

2.3.2.1 Model Description Editor The Model Description Editor is used when integrating several independent models into one simulator without wanting to do the integration explicitly in (model) source code. It is used to describe which model variables should appear in the so called “datapool”. The Model Description Editor is described in detail in Chapter 8.

2.3.2.2 Parameter Exchange Editor The Parameter Exchange Editor is used when integrating several independent models into one simulator without wanting to do the integration explicitly in (model) source code. It is used to describe which output variables in the datapool should be copied to which input variables in the datapool. The Parameter Exchange Editor is described in detail in Chapter 9.

2.3.2.3 Calibration Editor The Calibration Editor is used to define calibration curves. The calibration curve files can be referenced in the simulation definition file. The calibration definitions can be used using a run-time API. The Calibration editor is described in detail in Chapter 10.

c Airbus Defence and Space 9 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

2.3.3 Schedule Editor The Schedule Editor is used to define the tasks and the schedule of a model. The Schedule Editor is described in detail in Chapter 11.

2.3.4 Simulation Controller The Simulation Controller is used to initially define various simulation definitions and also to execute those definitions during a simulation run. Through the Simulation Controller various Action Editors are available, as well as the Initial Condition Editor. The Simulation Controller is also used to control the actual simulation. It is described in detail in Chap- ter 12.

2.3.4.1 Action Editors To define various actions (stimuli, recorders, interventions, events), a number of Action Editors are available through the Simulation Controller. The editors are described in detail in Section 12.10.3.

2.3.4.2 Initial Condition Editor With the Initial Condition Editor, initial conditions can be created and modified. An initial condition is used to initialize the simulator, by providing the simulation variables with initial values. The Initial Condition Editor is described in Section 12.7.4.

2.3.5 Test Analyzer The Test Analyzer can be used to view and plot the results from a simulation run. Chapter 13 contains more information on the Test Analyzer.

2.4 Application Programmers Interface

The name Application Programmers Interface (API) is used within EuroSim to describe the interface between the model and the EuroSim software. This description includes the services available through EuroSim as well as the variables and functions from the simulation model which need to be accessed by EuroSim.

The API for the EuroSim services is relatively simple: it consists of a number of predefined function calls that can be used from within the user’s model code. The exact syntax depends on the languages in which the model is implemented, Section 15.4 shows this API for the classic languages (C, Fortran and Ada).

The API for the simulation model is a bit more complicated, as EuroSim does not know beforehand what the user’s model code will look like. Therefore, in order for the model code to be used in EuroSim, the user has to add API information to the model code: the API header. This API header consists of a number of lines at the top of the model code. As the information is stored as comments, the source code will still be usable outside of EuroSim. Using the Model Editor of EuroSim (see Chapter 7), the user can easily enter the functions and variables in the source code which need to be available to EuroSim.

The information from all the API headers in the model together forms the data dictionary of the model.

The API information required by EuroSim is defined using four keywords (the ’ is part of the keyword):

• ’Global_Input_Variables

• ’Global_Output_Variables

• ’Global_State_Variables

10 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• ’Entry_Point

The choice of these keywords stems from systems theory, a discipline closely related to the application areas of EuroSim. In systems theory, a classical way to look at systems is from a causal input/output point of view, often referred to as the ‘black box’ approach to modeling of systems. Inputs are converted to outputs via a so-called black box (Figure 2.3).

black box state input output

control

Figure 2.3: The black box approach

An example would be a heater: a current (in Amperes) goes in, a heat flow (in Joules/second) comes out. These inputs and outputs are mapped onto the API-header keywords ’Global_Input_Variables and ’Global_Output_Variables. The next step in the modeling process is to extract (i.e. to model) the memory function of the system. The memory at a certain time is known as the state of the system. The state of the system describes in detail how inputs are converted to outputs. Whereas inputs and outputs are the means with which a system communicates to the outside world, there does not exist something like a unique state: the notion of state is very much a mathematical modeling tool. However, as the system has to be implemented in software to be usable in EuroSim, some way has to be found to define this state. The memory portion of the state is defined using so-called state variables. These map onto the keyword ’Global_State_Variables. The part of the state that determines exactly how to transform input to output using the current state is defined by the functions (or subroutines, or procedures) in the source code. EuroSim assumes that one source code file (i.e. C, C++, Fortran, Ada-95, or Java file) contains one black box. Note: as far as EuroSim is concerned, it doesn’t really matter whether a variable is tagged input, output or state. Each tag will allow EuroSim to access the variable during the simulation. There’s only one case where it does make a difference, and that’s for the Schedule Editor. This editor can check for data overlap between two tasks, but it will only consider the input and output variables of the tasks’ entry points in this check. As EuroSim needs a way to “run” the black box (i.e. to trigger it at the right times) there is a need for a certain amount of control on the black box. This control is given to EuroSim by declaring a number of functions to be an ’Entry_Point, which means that these functions can be called by EuroSim when necessary. An additional bonus of specifying all the variables is that it allows the user define some additional attributes, such as description, unit, etc., which might be useful to the Test Conductor and Observer when running the simulator. Also, the variables can be monitored, recorded, or changed during a simulation run if they are defined in the API header.

There are a number of constraints on the model code in order for this API information to be used correctly. Within EuroSim C, Fortran, Ada-95, C++ and Java2 can be used as languages to build the model. Further, programming language specific constraints are described in the chapters on the specific programming language usage in the Modelling Reference volume.

2 Note that EuroSim currently only supports creation of the API headers for C and Fortran code. For Ada-95 code, the user should create the API header by hand. To publish C++ and Java variables and entrypoints, a different style of APIs is provided. See appendix G, API header layout for more information on the details of the API header. See Chapter 16 and Chapter 19 for more information on the C++ and Java APIs

c Airbus Defence and Space 11 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

For standalone development of models, stubs are provided in the etc directory of the EuroSim distribu- tion. These stubs are provided for C and C++ and are delivered in source code.

2.5 Version management

Developing a EuroSim simulation is a continuously moving process. Files are frequently being changed and updated. Especially when more than one person is involved at any one time, it can be difficult to keep track of different versions of a model. With modern tools, we find that most users prefer to apply versioning outside EuroSim. However, EuroSim also provides builtin versioning support from within its tools to identify the reproducability of a simulator. Each of the files used within a simulation can be versioned by the user. Each version of a file can be given an annotation (a short description of the file). Versions are identified by a version number. When a file is versioned, a requirement on that file can be specified: if EuroSim needs access to that file (i.e. when compiling a source file) it then requires a specific version of that file. This could mean that EuroSim needs a version of a file which has since been updated. Therefore a history of the file version is maintained by EuroSim (for versioned files only). For files which are still under development, no requirement should be set. On the other hand, for files that need to be in a stable or predictable state, a version requirement could be used. The repository is the top of a central directory tree where all versions of files for a project are stored3. This location is defined when creating a new project (see Section 6.4.4). The project root (which is also defined when creating a new project) contains the current (working) version of the files being used for the simulation. When a group of users is accessing the model through the same project directory, they are all working with the same current version. If each user has a project description file of his/her own, or if tilde expansion is used for the project root (using the ˜ in a path to represent the users home directory), more than one project root can be defined, which effectively gives each user a private version of the model files. A copy of any version can be modified at will (e.g. adding new files, or changing existing ones), and when it is decided that a specific file is as it should be, it can be brought under version management by creating a new version. This new version is then the new requirement for the file. Other users can either update their model (by changing the file requirement) or keep using an older version. Note that all files that can be saved from within EuroSim can be put under version management. This includes the simulation model itself, which contains the requirements on the other files. By versioning a model file, a simulation model can be baselined, i.e. it can be frozen as a “working simulation”. By versioning all files used for a simulation run, the simulation can be made traceable or reproducible: at any given point in time the simulation can be re-run to recreate simulation results, as the exact version of the model, schedule, initial condition, etc. are stored in the repository. Although the repository can be stored in the same location as the project root, when more than one person is working on a simulation, it is best to keep the repository separate from the project root, so that more than one person can the same repository, but also keep their own work version. All versioning actions are done through the Tools:Version menu (see Section 5.6.4).

If an existing software repository, created using the CVS tool, is to be used within EuroSim, this can be accomplished by setting the ‘Repository’ to the CVSROOT directory. The ‘Project root’ should point to an appropriate working directory, with the restriction that the CVS repository tree has the same structure as the project tree.

3Actually, storage is more efficient: only differences of a file with the previous version are stored.

12 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 3

Tutorial

In this chapter, a complete pass through the EuroSim life-cycle is described. An example is used to describe all steps necessary to create a successful simulation with EuroSim. The user is advised to check the reference part of the user manual (Chapter 6, and onwards) for more information on menu items and the various objects in the EuroSim environment.

3.1 The case study

Throughout this user guide, a complete ready-to-run simulator is developed. A simple model of a satellite that hovers above a planet, without having it in a geostationary orbit, is used. The altitude of the satellite decays by perturbations and by the gravity pulling it to the planet surface. The thruster is switched on when the altitude reaches a lower limit and is switched off when the satellite reaches an upper limit.

3.2 Starting EuroSim

3.2.1 Linux

To run EuroSim on a Linux platform, type esim at the command prompt.

3.2.2 Windows To run EuroSim on a Windows platform, select EuroSim from Start Menu:Programs, or double-click on the EuroSim icon on the desktop.

c Airbus Defence and Space 13 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 3.1: The main EuroSim window

After a short while, the main EuroSim window will appear (see Figure 3.1). This window will display the projects to which you have access. If no project is shown ask the EuroSim facility manager to create one for you, or alternatively, create your own project, as described in the next section.

3.3 Creating a project yourself

Press the Add Project button in the toolbar or select Insert:Add Project to start the Add Project dialog window . To create a new project, enter the project name, choose the project directory and version control system. The ‘Description’ and ‘Repository Root’ fields are optional. For the remainder of this chapter, the name ‘SUM’ is assumed.

3.4 Creating a shared project

Instead of using a project created by yourself, you can create shared project(s) and database managed by the EuroSim facility manager. This can be achieved by doing the following, before starting EuroSim as described in the previous section.

• The EuroSim Facility Manager creates a directory where the shared project database can be stored.

• Set the environment variable EFO_HOME1 to this directory.

• Start EuroSim (see Section 3.2).

3.5 Creating a model

In the main EuroSim window, select the project to be used for this case study from the Project combobox and press the Model Editor button to create a new model. The Model Editor will show. When creating a new model a basic model structure consisting of the root node will appear. When editing an existing model select File:New to create this basic model structure (see Figure 3.2).

1On a Windows platform, environment variables are defined in the file $EFOROOT/bin/esim.bashrc.

14 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 3.2: A new model

3.5.1 Model The model for this simulation is divided into four parts:

• a sub-model that decreases the altitude of the satellite;

• a sub-model that lifts the satellite to a higher altitude by usage of a thruster;

• a sub-model that initializes the altitude decay sub-model;

• a sub-model that initializes the thruster sub-model.

The two initialization sub-models will initialize all the variables of the model. The thruster sub-model will monitor the altitude and keep it within limits. These limits are between 210 km and 280 km respectively. When it is below the lower limit the thruster will increase the altitude until it reaches the upper limit. At that point it will wait until the altitude has decayed to the lower limit and the process starts all over again. In Figure 3.3 the flowcharts of the two main sub-models are shown. These flowcharts could be compared to a first version of the design. Later on in the case study, more optimized code will be used.

c Airbus Defence and Space 15 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

decrease altitude increase altitude

no yes altitude < altitude > 0? upper limit? yes no

yes altitude > lower limit?

no

Figure 3.3: The altitude (left) and thruster models

3.5.2 Adding the sub-models In order to add the four sub-models to the model, select the root node (the left-most node), and choose Edit:Add Org Node from the menu. In the window that appears, enter as name Altitude. Add another org node (after first selecting the root node again, if necessary), and this time use the name Thruster. The next level of the model hierarchy will consist of four source files, each corresponding to one of the four sub-models. Start by selecting the ‘Altitude’ node and then do an Edit:Add File Node. In the window that appears, enter as file name Initialize_Altitude.f, or use the file selection dialog if you already have the tutorial source files. EuroSim will recognize this file as a Fortran source file. A new file node will be added to the model hierarchy. Repeat the process for the three other file nodes: attach a file node with file name Altitude.f to the Altitude node, and add two file nodes with names Initialize_Thruster and Thruster respectively to the Thruster node (using files Initialize_Thruster.c and Thruster.c). By now, the model should look like Figure 3.4. Notice that after making changes to the new model, as asterisk (*) is shown in the title bar of the window to indicate that there are changes to be saved.

16 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 3.4: Model with the file nodes

Save the model by selecting File:Save. As model name, enter SUM.model in the file selection window. This file selection is shown because the new model has not been saved before. The next time the model is saved, no file selection window is shown.

3.5.3 Adding the source code

Next, the actual source files have to be created2. Do this by selecting the Altitude file node, and choosing Edit:Edit Source from the menu. An editor3 will show, in which the following source code should be entered. Beware that Fortran wants to have 6 spaces before the first character on the line (except for the comment lines starting with ‘C’ in column 1). This is a left-over from the times that programs were entered using punch cards.

Listing 3.1: Source Altitude.f C------C File: Altitude.f C C Contents: The Fortran routines that simulate the gravity C pull of a planet. C C------SUBROUTINE DECAYALTITUDE

C Global Variable definition. INTEGER ALTITUDE INTEGER DECAYSPEED, DECAYCOUNTER

C COMMON Block Definition. COMMON /ALTDATA/ ALTITUDE, DECAYSPEED, DECAYCOUNTER

2If the files have already been selected with the file selection dialog, this step can be skipped. 3Set teh EDITOR environment before launching EuroSim to yoru favorite editor if you don’t like the standard editor

c Airbus Defence and Space 17 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

DECAYCOUNTER = DECAYCOUNTER + 1 IF (DECAYCOUNTER .GT. DECAYSPEED) THEN DECAYCOUNTER = 0 IF (ALTITUDE .GT. 0) THEN ALTITUDE = ALTITUDE - 1 ENDIF ENDIF

RETURN END

Save the source file, and close the editor. Repeat the process for Initialize_Altitude with the source file:

Listing 3.2: Source Initialize Altitude.f C------C File: Initialize_Altitude.f C C Contents: Initialize the altitude decay simulation model. C C------SUBROUTINE INITIALIZEALTITUDE

C Global Variable definition. INTEGER ALTITUDE INTEGER DECAYSPEED, DECAYCOUNTER

C COMMON Block Definition. COMMON /ALTDATA/ ALTITUDE, DECAYSPEED, DECAYCOUNTER

C Parameter Definition. PARAMETER (DECAYSPEEDDEFAULT = 100)

ALTITUDE = 0 DECAYCOUNTER = 0 DECAYSPEED = DECAYSPEEDDEFAULT

RETURN END

Listing 3.3: The C source code for the Thruster file node /* File: Thruster.c

Contents: The C routines that simulate the thruster module of the satellite. */

#define On 1 #define Off 0

extern int altitude; int thrusterOnOff; int speedCounter = 0; int satelliteAscentSpeed; int lowerAltitudeLimit; int upperAltitudeLimit;

void Thruster(void)

18 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

{ if (thrusterOnOff == On) { if (speedCounter++ > satelliteAscentSpeed) { speedCounter = 0; altitude++; thrusterOnOff = (altitude < upperAltitudeLimit); } } else { thrusterOnOff = (altitude < lowerAltitudeLimit); } }

Listing 3.4: The source file for the Initialize Thruster node /* File: Initialize_Thruster. Contents: Initialize the thruster simulation model. */

#define SPEED_DEFAULT 10 #define On 1 #define Off 0 extern int speedCounter; extern int satelliteAscentSpeed; extern int thrusterOnOff; extern int lowerAltitudeLimit; extern int upperAltitudeLimit; void Initialize_Thruster(void) { satelliteAscentSpeed = SPEED_DEFAULT; speedCounter = 0; thrusterOnOff = On; lowerAltitudeLimit = 210; upperAltitudeLimit = 280; }

3.5.4 Adding the API headers 3.5.4.1 The Altitude sub-model

The next step is to add the API headers to the model. Expand the Altitude file node by pressing the ‘+’ symbol, or use View:Expand All. EuroSim will parse the expanded file(s) and display the available entries and variables in the code. First, the decayaltitude entry point will be added to the API header. Click the checkbox left to decayaltitude to add this entry point to the API header.

We will also add two of the variables from this entry point to the API header: tick the checkboxes in front of the altdata$altitude and altdata$decayspeed variables under the decayaltitude entry point.

When added to the API header (checkmark used), additional information on entry points and variables can be entered (such as a description). Select the decayaltitude entry point and click the ‘Description’ field on the right. Enter the description The altitude decay operation. Select the altdata$altitude variable. The ‘Type’ and ‘Init Source’ fields cannot be changed, as they are extracted from the source file. Enter a description of The altitude of the satellite. Enter as ‘Unit’ the string [km], as ‘Min’ the value 0 and as ‘Max’ the value 1000. Repeat this for the altdata$decayspeed variable, using the values:

c Airbus Defence and Space 19 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description The speed with which the altitude decays Unit [km/s] Min 1 Max 200

The model should now look like Figure 3.5. Repeat the above steps for the three remaining sub-models, using the values from the next sections.

Figure 3.5: The expanded Altitude node

3.5.4.2 The Initialize Altitude sub-model

Add the entry point in initializealtitude with a description Initialize the altitude decay operations.

3.5.4.3 The Thruster sub-model

Add the entry point Thruster with a description The thruster brings the satellite to the correct altitude. Add the following variables by selecting them from the list to the right of the Thruster entry point:

Variable Min Max Unit Description lowerAltitudeLimit 0 1000 [km] Below this limit, thruster must be turned on satelliteAscendSpeed 1 200 [km/s] The ascent speed of the satellite thrusterOnOff 0 1 [1=On/0=Off] Thruster on/off indicator upperAltitudeLimit 0 1000 [km] Above this limit,thruster must be turned off

20 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

3.5.4.4 The Initialize Thruster sub-model

Add the entry point Initialize_Thruster with a description Initialize the thruster.

3.6 Building the simulator

Select Tools:Build All from the menu in the Model Editor. In the output window, all commands executed are echoed, as well as their outputs. Things to look out for are lines starting with *** Error, which indicate that an error has occurred during building. Usually directly above a more descriptive error message is given. You can ignore the file version warnings, but there should be an error message like:

Satellite.Linux/Thruster.pub.o: In function ‘Thruster’: Satellite.Linux/Thruster.pub.o(.text+0x2b): undefined reference to ‘altitude’ Satellite.Linux/Thruster.pub.o(.text+0x31): undefined reference to ‘altitude’ Satellite.Linux/Thruster.pub.o(.text+0x4e): undefined reference to ‘altitude’ collect2: ld returned 1 exit status gmake: Leaving directory ‘/home/jv75763/work/Satellite’ gmake: *** [Satellite.Linux/Satellite.exe] Error 1 *** Errors during build ***

The meaning of this message is that the compiler can not find a declaration with the name altitude. Inspection of the source files indicates that the C function Thruster uses an external declaration of a variable with the name altitude. Although the Fortran source has a variable with the name ALTITUDE it is not possible to connect these two variables in the way the current satellite model has been written. This is a general problem with linking Fortran and C code. It arises from compiler conventions, not from the EuroSim tools. To solve the problem, change the altitude variable in the file Thruster.c to the following struct declaration: extern struct altitudeDataStruct { int ALTITUDE; int DECAYSPEED; int DECAYCOUNTER; } altdata_;

And change the use of the variable altitude to: altdata_.ALTITUDE

Note that the altitude variable is used in three places. Be sure to change them all. The Thruster.c source file should now look like: /* File: Thruster.c

Contents: The C routines that simulate the thruster module of the satellite. */

#define On 1 #define Off 0 extern struct altitudeDataStruct { int ALTITUDE; int DECAYSPEED; int DECAYCOUNTER; } altdata_;

c Airbus Defence and Space 21 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

int thrusterOnOff; int speedCounter = 0; int satelliteAscentSpeed; int lowerAltitudeLimit; int upperAltitudeLimit;

void Thruster(void) { if (thrusterOnOff == On) { if (speedCounter++ > satelliteAscentSpeed) { speedCounter = 0; altdata_.ALTITUDE++; thrusterOnOff = (altdata_.ALTITUDE < upperAltitudeLimit); } } else { thrusterOnOff = (altdata_.ALTITUDE < lowerAltitudeLimit); } }

When the changes to the source file have been made, try rebuilding the simulator. If the build was successful, the messages SUM.exe MADE and all DONE should be displayed in the status window. Save the model and exit the model editor. In the EuroSim main window choose Edit:Add Model and select SUM.model to add the created model to the project.

3.7 Creating the schedule

The schedule of a simulation defines which tasks need to be activated at which time. A task is a set of entry points which are executed sequentially. Task and schedule can be created using the Schedule Editor. Select the EuroSim main window and press the ‘Schedule Editor’ button. The schedule contains four tab pages, one for each of the simulator states initializing, executing, standby and exit. For the example, three of the four states will be used. In the initializing state, a schedule will be created which will be triggered by state entry, and which will then initialize the thruster and altitude model. After these have been executed, the schedule will put the simulator in standby state. For the executing state, a schedule will be created which triggers the thruster and altitude models using two timers, one at 20 Hz and one at 100 Hz. In the exit state, a schedule will be created which will close down the simulator.

3.7.1 Initializing schedule

Choose File:Select Model from the menu. Select the file SUM.model to be able to use the created API header. Select the circle symbol from the toolbar for a task4. The cursor changes into a circle. Put the circle on the schedule tab page. It will change color to red, indicating an error (in this case: the task has no input and output connectors attached). It will get a default name of New Task. Select the arrow tool from the toolbar on the left. Double click on the task, which causes the task properties dialog to open. In this dialog, select the Initialize_Thruster entry point on the left Data Dictionary view and press the Add button. This will copy the entry point to the entry points list, indicating that this entry point belongs to the task we are defining. Do the same with the Initialize_Altitude entry point.

4See Section 11.2 for a description of which icon belongs to which item.

22 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

When a task is executed, each of the entry points contained in the task will be executed sequentially. For this initializing task the order is not important, but if it is, the up and down arrow buttons can be used to re-order the entry points. Timing information can be entered for each entry point. As we don’t have such information at this moment, we will leave it empty. Later on, if the simulation has been executed successfully, it is possible to import a timings file created by the simulator, which contains the various data required here. Now change the name of the task to Initialize by entering the new name in the field Taskname below the Data Dictionary box. Press the OK button. The task on the Schedule Editor now also has the name Initialize. Next, from the Insert menu, select the menu item Internal Event. Select STATE_ENTRY from the submenu. Put it on the tab page. Next select a flow (curved arrow) from the tool button bar. Click the left mouse button on the internal event. Keep the left mouse button pressed and move the mouse to the task. Notice how the flow follows the cursor. Release the left mouse button again above the task. The two are now connected. Finally, add the PAUSE output connector to the tab page, and connect a flow from the task to the output connector. The initializing schedule should now look something like Figure 3.6.

Figure 3.6: The initializing schedule

3.7.2 Executing schedule First select the Executing tab to show the schedule for the executing state. On the tab page, create two more tasks, named Thruster and Altitude. The Thruster task should contain the Thruster entry point, and the Altitude task should contain the decayaltitude entry point. Next to each task, put a timer. Connect each timer to a task using a flow. As the Altitude task should be executed less often than the Thruster task, double-click on the timer connected to the Altitude task. A timer attribute window will show. In the window, change the frequency to 20 Hz. Close the window with the OK button. Change the frequency of the Thruster timer to 100 Hz. On some operating systems this is the default frequency. Other operating systems may have a different default frequency setting. The executing schedule should now look something like Figure 3.7. With this schedule, the Thruster task will be triggered with a frequency of 100 Hz, and the Altitude task with a frequency of 20 Hz.

c Airbus Defence and Space 23 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 3.7: The executing schedule

3.7.3 Closing the Schedule Editor After each of the schedules has been created, select File:Exit from the menu and select Save when a warning is given about unsaved changes. In the Model Editor, save the model.

3.8 Creating a simulation definition

Now that the model has been created and the simulator has been built, a simulation definition should be created. A simulation definition contains information on the initial values of the variables defined in the API headers, as well as stimuli, recorders and monitors, which can be used to monitor and influence the simulation. Select Simulation Controller from the main EuroSim window. The Simulation Controller will start (see Chapter 12). In order to create a simulation definition, the Simulation Controller needs to know which particular model and schedule the simulation is intended for (which indirectly gives access to the associated data dictionary). Choose File:New to create a new simulation definition. A wizard dialog appears where you can select all files that you want to use in a simulation. Initially you must select the SUM.model and the SUM.sched files. Use the Browse. . . button to select the model, press the Next button to go to the next page of the wizard. If the prefilled schedule file (guessed from the model file) is correct then press Finish, otherwise use the Browse. . . button to select the right schedule file and press Finish.

3.8.1 Creating a graphical monitor

Select Insert:New MMI ... from the menu. You are asked to choose a filename for the new Man-Machine Interface file. Save the file as Altitude.mmi. Now you will be asked for the caption of the new tab page. By default the name of the file without the suffix will be chosen. Accept the default. A blank tab page named Altitude appears where you can add monitors. Select this tab and choose Insert: New Monitor to add a new monitor. The Monitor Editor will appear (see Section 12.2.5 for more information). In the Monitor Editor, enter Altitude monitor as the caption. Now expand the decayaltitude node and double click the variable altdata$altitude on the Dictionary Browser. The variable appears in the Variables list and is now connected to the monitor.

24 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Change the style from ‘Alpha Numeric’ to ‘Plot against Simulation Time’. By default the X and Y axis will scale automatically when the plot is being created. Select ‘Manual Scaling’ to define the min/max range yourself. As you can see, the first time you select Manual Scaling the min and max values will be determined from the Variables list (if possible). The Monitor Editor should now look like Figure 3.8. Close the editor with the OK button. On the Altitude tab page, the new monitor is shown.

Figure 3.8: The Monitor Editor

3.8.2 Creating an intervening action In order to create an action which changes a variable during the simulation, you first have to create a scenario file where such actions are defined. Choose Insert:New Scenario from the menu. Save the file as SUM.mdl. Now you will be asked for the caption of the new tab page. By default the name of the file is used without the suffix. Accept the default. To add a script choose Insert:Script from the menu. Change the name of the action to Set decay speed to 20. Select the options ‘Initializing’ and ‘Standby’. Because this action should only be executed if the Test Conductor wants it, the ‘Condition’ field is left blank. Now the action has to be started explicitly by the Test Conductor. Select the variable altdata$decayspeed from the Dictionary Browser using the left mouse button. Whilst keeping the mouse button pressed, drag the name of the variable to the Action field. Release the button. The variable is now copied to the Action field. Add =20 to the same line as where the variable is shown. This statement means to set the variable to a value of 20. Optionally, press Check Script to see if any errors were made. The Script Editor should now look like Figure 3.9. Close the Script Editor with the OK button. The new action appears on the Scenario tab page.

c Airbus Defence and Space 25 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 3.9: The Script Editor

3.8.3 Creating a recorder In a recorder action, the values of one or more selected variables are saved to a file (in contrast with a monitor, where the values are shown on screen; another difference with monitors is the sample rate: monitors sample at a fixed rate of 2 Hz whereas recorders can sample at a user defined frequency up to the maximum schedule frequency, usually 200 Hz). Select Insert:New Recorder to create a new recorder. In the Recorder Editor, change the name to Record altitude. Double click on the altdata$altitude variable in the Dictionary Browser. It will be added to the Variables list. For a recorder, a number of extra attributes have to be filled in. Change the name of the recorder file by setting the edit field ‘Recorder File’ to altitude.rec. Optionally, the recording frequency and start/stop times can be entered here as well. The editor should now look like Figure 3.10.

26 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 3.10: The Recorder Editor

The Recorder Editor has two tab pages. Change to the Script tab page, and notice that now a ‘Condition’ has been filled in: at a frequency of 100 Hz, the ‘Action’ will be executed. Although not used here, the ‘Inactive’ setting can be useful for temporarily disabling a recording action (or others, e.g. a check on variable values). Active actions are represented by an ‘A’ in the status column. The Condition and Action fields are read only, but by checking the Manual checkbox you can customize these fields. Close the Recorder Editor with the OK button. A second icon is now visible on the Scenario tab page. The tab page should now look like Figure 3.11. Save the simulation definition by selecting File:Save. Requesting Save will cause the Save As. . . file selector to appear as this simulation definition has currently no filename. The simulation definition should be saved as SUM.sim.

c Airbus Defence and Space 27 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 3.11: The Scenario tab page

3.9 Executing a simulation run

Everything is now set to perform an actual simulation of the model. A simulation runs on a so-called simulation server, which is a machine running the EuroSim scheduler. Select Server:Select server from the menu, and select one of the servers shown in the list. Simulations can run either in real time or non-real time. In non-real time mode, the simulation server will try to be as real time as possible, but no real-time errors will be generated (see also Section 2.2.4). By default, non-real time mode is selected. Initialize the simulation by pressing the Init button from the tool bar or from the Control:Init menu. After the initialization is completed, the Init button will become inactive, and the other buttons will become active. Notice that the wall-clock time will start running. Now press the Go button to start the simulation. On the Scenario tab page, notice that an ‘X’ appears in the status column for the recorder. This indicates that data is being recorded (the recorder is eXecuting). Select the Altitude tab page and notice that the altitude of the satellite is plotted against time in the monitor window. During the simulation, it is possible to change attributes of the monitor (for example the X and Y ranges). When the satellite starts coming down, double-click on the ‘Set decay speed to 20’ intervention action. The satellite should now come down more rapidly. Directly after double clicking the intervention action, select Insert:Mark Journal. A mark with a number should now appear on the message pane. Afterwards, make a comment with Insert:Comment Journal Mark to explain that the mark indicates that the inter- vention action was executed. For example, enter as comment Mark 1-tc indicates activation of intervention action. After a while, stop the simulation by pressing the Pause button and then the Stop button. Close the Simulation Controller with the File:Exit menu item.

3.10 Analyzing the simulation results

In order to make some plots of the recorded variables, select Test Analyzer from the main EuroSim window. Make sure you have PV-Wave or gnuplot installed otherwise this tool will not work. An empty Test Analyzer window will appear.

28 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Now we will load the test results generated during the simulation. Select File:Select Test Results File. This will show a file selection window. Now find the recording file generated during the simulation. It will be in a directory like 2001-08-30/15:33:30. Select the Altitude.tr file, which contains a list of all recording files created during the simulation (in this case, just one). Right click on the variable browser window (on the left) and select Expand All Nodes. The window should now look like Figure 3.12.

Figure 3.12: The Test Analyzer with the simulation results loaded

Now select Plot:New Plot. The plot view (top right) now shows an icon representing the plot. The plot properties tabpages (bottom right) have also become available. Enter Altitude as the plot title and Plot of altitude against time as a description. Press the Apply button to commit the changes. The text under the plot icon in the plot view will be updated. The window should now look like Figure 3.13.

Figure 3.13: A new plot

c Airbus Defence and Space 29 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The next step is to create a curve of the altitude versus the simulation time. Select the variable altitude$altitude. Now click on the variables and curves tab of the plot properties tabpages. The curve editor appears. Drag the selected variable from the variable browser to the curve editor. A new curve is created and the window should look like Figure 3.14.

Figure 3.14: A completed plot

This completes the plot. Double clicking the plot icon in the plot view will show the plot.

3.11 Concluding remarks

In this chapter, a complete simulator has been built from scratch. The most important features of EuroSim have been used. However, as EuroSim offers many more functions than can be described in this tutorial, the reader is advised to proceed with the reference chapters, and experiment with the simulator from this chapter.

30 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 4

Troubleshooting

4.1 Introduction

Building EuroSim simulators requires programming and integrating models, and as consequence a vari- ety of problems that are normal to developing software can occur. Typical examples are:

• Simulation fails to start

• Simulator Controller time-out

• Simulator segmentation fault

• Unexpected model behaviour

• Scheduler event and sequence errors

• Memory allocation messages

When software engineers build their own programs, they know how to engage these problems and use tools like debuggers or print statements to files to get to the cause of the problem. More advanced methods are even to use memory checkers such as valgrind, coverage analysis tools as gcov and profilers such as gprof. Especially under Linux these tools are freely available and can aid to the quality of the software. In addition coverage analysis of the simulator can be used to demonstrate in verification that all code has been checked. (When models are loosely coupled it is possible to verify the models as integrated unit in the simulator by only scheduling the execution of the specific model code.) Similar features are also available to the Simulator Developer under EuroSim. This chapter explains how to find the cause of problems using the various facilities in EuroSim.

4.2 Daemon Log Inspection

The EuroSim daemon collects all standard error and standard output of simulators and stores these mes- sages in the EuroSim daemon log. Generally it should be in most cases be the first item to inspect in case of unexpected crashes. The EuroSim daemon log catches all messages from the starting simulator executable untill the simulator has set up its message handling services and has been able to log messages to clients and its own log file in its results directory. This includes any messages generated by model code through the esimReport (messasge, warning, error, fatal) service routines that were generated in such early stage. This could for instance be caused by model code activated from the CPP interface setup function. Besides catching messages in an early stage of the launching the simulator, all writing to stdout or stderr, for instance with printf, duing the simulation will also be caught in the daemon log.

c Airbus Defence and Space 31 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The location of the EuroSim daemon log depends on the operating system:

• On Linux systems, the daemon log is by default created at /var/log/esimd.log. Note that the file collects the messages of all simulators, hence it can grow considerably. It is recommended to use the tool less to view the file. Use the command Shift-G to jump to the end of the file and scroll back to find the messages of your simulator execution.

• On windows systems, the daemon log is created in the Windows system log. Open the Win- dows Control Panel. Select Administrative Tools and then Computer Management. In Computer Management, unfold Windows Log and then App[lication. Browse to the information items from esimd.

4.3 Core file analysis

If in the exection of the simulator a fatal code in the error is encountered, a segmentation fault is raised and a core file is generated. The latter may be dependent on ulimit settings (set this to unlimited) and potentially compilation with the -g flag that needs to be set in the Model Editor Build Options. Assuming that a core file is generated, loading this core file in a debugger can in most cases produce a stack trace that can identify in which function the crash occured.. If compiled with -g such that extra symbol information is included in the executable, the exact line in the code can be found. The core file is normally generated in the project directory where also the sim file is located. Using the GNU debugger, the following command will start the debugger with the core file:

gdb ./modelname.exe

where: = Name of the model = Linux or WINNT = typically core.

Note that we have not seen core files being generated on Windows machines yet. On Linux systems the popular GNU debugger front-end named ddd can be used instead of gdb. alternatively, eclipse users may use the gdb debugger from within eclipse which is also a GNU debugger front-end. After the GNU debugger has launched, use the where command to get the stack trace.

4.4 Symbolic Debugging

If the simulator is executing, but the model code is not behaving as expected, a first solution is to monitor variables using the monitors that can be made in the MMI tabs of the Simulation Controller. However, it is also possible to step through the code using a symbolig debugger. With ddd as a front-end of the debugger it is even possible to setup monitors in ddd and let the debugger show the data in an mmi form. The only preparation to do this is to set the -g flag in the Build Options of the Model Editor and rebuild the model such that it includes additional symbol tables:

32 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 4.1: Enable symbolic debugging of the simulator model code

The easiest approach to starting the debugger is to launch it from the Simulation Controller when the execution has achieved the point where inspection is desired. Pressing the F5 button the debugger that is selected in the Preferences dialog of the Tools menu of the Simulation Controller is started. The startup is such that the debugger automatically loads the appropriate executable and attaches to the running process. As soon as it is attached, the excution of the simulator freezes. The user now has complete control from the debugger. Figure Figure 4.2 shows the debugger hitting a breakpoint in the model code.

Figure 4.2: Symbolic debugging of simulator model code

It is of course also possible to start a symbolig debugger seperately from EuroSim if such is preferred by the user. Please note that if that debugger is the gdb (or ddd) debugger, it should be started using the command:

gdb -x $EFOROOT/etc/gdbinit >

c Airbus Defence and Space 33 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

where: = process id of process to attach to In the case of seperate startup it is important to pass some commands that surpress the reaction on signals by gdb due to their usage in EuroSim. The required commands are in the file $EFOROOT/etc/gdbinit . Either pass this file on startup or copy the commandfile to ˜/.gdbinit. Note that a known Software Problem exists on Windows where a console is started with the GNU debug- ger but the attachment does not occur automatically. Once the debugger is started, look up the process id via the Windows Task Manager (CTRL-ALT-DEL or right moue click on task bar). Select the Perfor- mance tab and then press the Resources button at the bottom. The dialog that then comes available has on the Overview tab a listing of os executables with process id’s. The EuroSim helpdesk is working on the problem.

4.5 Scheduler Debugging

EuroSim has built-in capabilities for schedule debugging. In the context of EuroSim the smallest unit of execution is the entry point. The debugger menu in the Simulation Controller and associated Schedule tab with context sensitive menu options provide a means to debug a the level of tasks and entrypoints. Using these options the user can put traces on the execution of tasks and entrypoints, disable the execution of tasks and step through the execution of tasks. The Scheduler Debugging features greatest value is in easy ways to get to the point where other means become helpfull. The Scheduler Debugging for instance can help the user to easily break at a specific scheduler entrypointk then hit the F5 button to launch the debugger, and then dismiss the Scheduler Debugger breakpoints and start using symbolig debugging.

4.6 Tuning Memory options

To assure hard realtime execution, EuroSim allocates memory on start-up from which itself and thereafter the user through esimMalloc can claim head memory. This mechanism assures that no page faults occur during simulation. The total amounbt of heap memory that becomes available is defined in the Model Editor via the Build Options dialog. It is not uncommon that large simulators require more heap memory and the default configured setting must be increased. Modern machines have considerable amounts of memory, and allocating large memory of multiple gigabytes is not a problem to EuroSim. Do consider however that on multi-user systems, multiple users can be active. To tune the amount of memory, the EuroSim service interface contains functions to report on heap memory usage and availability. This can also be used to detect memory leaks as the reported memory continues to increase.

Figure 4.3: Tuning the memory sizes of the simulator

EuroSim runs a watchdog at 0.5 Hz that monitors the heap memory usage of the simulator. If the heap memory usage grows above 80%, the watchdog prints an error message to the simulator journal: ”running out of memory: x% used (y bytes left)”.

34 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Besides the heap memory tuning, the Model Editor Build Options also allow the sizing of several inter- nal buffers. The most common cause of error messages related to memory problems is the ringbuffer overflow messages. This ringbuffer buffers the echange of message between the real-time domain where the tasks execute and the non real-time domain where for instance the communcation of sockets with clients is arranged. The communication to clients executes on 2Hz and completely drains the buffer of all messages. This however is no match for the real-time excuting processors when the generate high volumes of messages and data (from the Action Manager task to the non realtime domain). Increase the memory settings to allocate more buffer space if the fluctuations in the message volume are high.

4.7 Tuning Simulator Startup time-out

Quite often a Simulation Controller time-out error is related to a problem in the start-up of the Simulator. It is however possible that the start-up takes longer then expected. In particular this can occur with C++ based simulators. The time that the Simulation Controller will wait from launching the simulator until a connection to it becomes available is defined in the Preferences settings of the Simulation Controller in seconds. Enlarge the value if you think a larger time-out might be needed. Note that the setting is not specific to a simulation (.sim file), but rather is a user specific setting that is stored in the .eurosim directory in the users home directory.

4.8 Execution Timing analysis

EuroSim offers the user two methods of timing analysis: A statistical overview and a detailed event recording. The statistical overview is automatically collected in every simulator run and written to file at the end of a successful simulation run. The log file is called timings and can be found in the results directory, which by default is created in subdirectories that identify first the day of the simulation and in that the time of the simulation run. The Simulation Controller also loads the file automatically in the Schedule Tab and is presented to the user if the Statistics button is pressed.

Figure 4.4: Statistics tabs at end of successful simulation run

The file has the same format as a schedule file and clearly lists for every entrypoint in a task the minimum,

c Airbus Defence and Space 35 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

average and maximum execution time as well as the number of executions of the entrypoint. In addition it shows the number of events and CPU load for every state. The timebar approach can show the user the execution of the scheduler on a timeline. The scheduler records all events as well as task start-stop times and writes these to file. This log file is called trace and by default is written to the results directory as for the timings file. The scheduler however may stream a large amount of data at high rate to the file, hence the file is best located on a local drive (e.g. \tmp). You can specify an alternative directory for the trace files in the Simulation Controller Preferences dialog from the Tools menu. You can also specify in this dialog if the date and time should be in the filename such that simulation don’t overwrite the file or whether this should be left out to conserve storage space. Furhtermore you can define if the recording should be initiated from the start or whether it is to be start in suspended mode, and then should be resumed by you from either MDL script (trace on/off) or source code (esimTracePause, esimTraceResume). Furthermore it can be tuned what events are to be recorded via the esimTraceMask function or tracemask MDL command. (See the Simulation Controller reference sections). To enable the timebar recording, enable the recording from the Debug Menu of the SimulationController. The trace file is then created at startup and the simulation reports if it starts in active or suspended mode. After completion of a simulation with enabled timebar recording, the recording can be displayed in the SimulationController itself via the Schedule Tab. When the Timebar widget is visible and a timebar recording is ready to read it will automatically load the data.

Figure 4.5: Statistics tabs at end of successful simulation run

For more information, see the GUI Reference Schedule Editor section.

4.9 Coverage analysis

Coverage analysis tools count how often a program executes a segment of code. In debugging it is helpfull to find if code is executed. In formal verification it may be required to show that code is executed. The tool gcov comes as a standard utility with the GNU Compiler Collection (GCC) suite and can be used in combination with EuroSim. To instrument the simulation model code for collecting the coverage statistics, add --coverage to the Compile Options for your program language(s), as well as to the loader options. Figure Figure 4.6 shows the Build Options dialog in the Model Editor with the flags for coverage analysis support. Note that it is not recommended to add optimization flags with the compilation for coverage analysis. Additionally, the instrumentation of the code for coverage analysis data gathering may degrade to the realtime execution and add latency which can lead to different simulation results.

36 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 4.6: Enable coverage data collection on the simulator model code

The coverage data is collected in memory as counters per line and flushed to file from a program exit han- dler (atexit(3)). EuroSim however currently avoids the execution of exit handlers due to a conflict with open source software on the release of memory. The flushing of the gcov data by the program therefore requires an extra effort of the simulator developer. Anentry point must be created that is to be executed at the end of the simulation and which calls the hidden gcov function void __gcov_flush(void). The following C code snippet can be added to a simulator which delivers the entrypoint gcov_flush() in the dictionary which then can be scheduled in the exiting state.

/* ’Entry_Point gcovflush */ void __gcov_flush(void);

/* *\brief Force a flush to file of the data that gcov collected */ void gcovflush(void) { __gcov_flush(); }

The gcov flush function then flushes the data in memory to the data dump files in the Simulator. directory. This data needs to be post processed using the gcov tool which must be passed the location of these dump files as well as the collection of source files for which post processing is required. The .make file is equipped with a gcov target which makes this post processing considerably easier: make -f .make gcov The resulting output files (with extension .gcov) can be found in the Simulator. directory.

4.10 Profiling

Profiling tools assist the user in determining the parts in program code that are time consuming and need to be re-written. This can be accomplished by passing the -pg argument to the compileflags. After

c Airbus Defence and Space 37 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

execution the command gprof is then to be executed to extract the profiling information. Profiling in a EuroSim simulator however is not recommended. It will likely deliver incorrect results. The gprof profiler collects its information based on a regular frequent interrupt (signal) of the running simulator. In the handling of the interrupt the profiling software looks at the location of the program counter in the simulator code and increases the count for that location. The problem however is that the frequencies in EuroSim simulators are typically an order larger then the interrupting frequency which would then lead to a count that is an order lower then it actually is. Additionally wit respect to realtime behavior this approach will lead to a degraded and not realistic execution, and likely the signal will not get through as EuroSim masks signals on realtime executors.

4.11 Linux Capabilities

In exceptional cases a simulator may fail because it needs special privileges. Traditionally, one would then have to run the simulator as root (uid 0) to bypass all privilege checks. Nowadays, Linux provides a fine grained scheme with capabilities. For more information, see man capabilities. EuroSim is aware of Linux file capabilities, also in real-time mode1. To grant a simulator special privileges, add them to the file capability set of the simulator executable. The easiest way to add file capabilities to a simulator executable is via an extra Makefile that wraps the internal Makefile generated by EuroSim ModelMake. As an example, consider ThermoMra/Simula- /Numerical/Makefile in the EuroSim examples directory.

all: Version.h $(MODEL).make $(MAKE) -j$(PROCS) -f $(MODEL).make $@ sudo setcap ’cap_chown+pe’ rts.Linux/rts.exe

The extra line with setcap grants the CAP CHOWN privilege to the simulator executable. One extra point of concern is that setcap itself requires privileges. The easiest way is to grant the user that builds the simulator executable sudo rights on setcap. The permission is granted in the /etc/sudoers file, which can be edited (as root!) with the visudo command. The following line shows how to grant user john the permission to run setcap:

Cmnd_Alias SETCAP = /usr/sbin/setcap, /sbin/setcap john ALL=(root) NOPASSWD:SETENV: SETCAP

This way, the user can just run setcap with root permissions and does not need full root access.

1This is not self-evident because the daemon execve’s a real-time simulator as root, which then calls setuid to drop all privileges

38 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part II

GUI Reference Guide

c Airbus Defence and Space 39

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 5

Common GUI reference

EuroSim uses a graphical user interface (GUI) for all tools available to the user. This chapter describes the following elements of the user interface:

• Some of the conventions used throughout the user interface. • The keyboard shortcuts which can be used to quickly access functions from the menus. • The menu items that are available in every tool. • User Interface elements that are used in many EuroSim tools.

5.1 GUI conventions in EuroSim

• An ellipsis is shown after a menu item description when a dialog box is shown to request more information from the user, before an action is performed. E.g. File:Save As. . . • Menu items and buttons that can not be selected (either due to the context, or because they are currently not implemented in EuroSim) are shown grayed out. • Where applicable, keyboard shortcuts are shown next to the item. For more information, refer to Section 5.3.

As the EuroSimGUI’s are based upon the Qt toolkit, the following elements are used for user input: • Checkboxes (little squares) which can be selected by pressing the box. • Radiobuttons (circles) which behave the same as checkboxes, with the exception that of a group of related radiobuttons, only one can be active. • Normal buttons (rectangles), which have a descriptive label such as ‘Save’ on top of the button. Pushing the button performs an action. • Textfields (large rectangular areas, sometimes with sliders alongside it), which can be used to enter text. If the field has sliders, they can be used to reveal parts of the field which are not shown on screen.

5.2 Mouse buttons

An item in a window is selected by placing the mouse pointer over it and clicking the left mouse button (MB1). More objects can be selected by holding down the Control or Shift key when clicking MB1. Double-clicking an item with MB1 will activate it (i.e. do the thing the icon represents, e.g. drawing a plot) or fold/unfold it, in case it is an icon in a tree structure. Pressing the left mouse button over a selected icon allows one to drag the icon and drop it somewhere else (e.g. in a monitor definition, that will then be extended with the new variable name).

c Airbus Defence and Space 41 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

5.3 Keyboard shortcuts

The menu items can also be accessed using the keyboard. There are two methods:

• The Alt key can be used to access the menubar. Once selected, menu options can be selected by using the cursor keys followed by Return or by typing the underlined letter for a particular menu option. Escape aborts from the menu traversal.

• Specific, often used, menu items can also be selected directly using a short cut. These shortcuts are usually combinations of the Ctrl and Alt keys and a character key, and are shown next to the menu item.

In textfields, the usual editing keys such as Tab, Enter, arrow keys, Home and End are available. Besides these keys, the following keys have special meaning:

• Prior (or PageUp) scrolls down a page

• Next (or PageDown) scrolls up a page

• Ctrl+a moves to the beginning of the line

• Ctrl+b moves the cursor backwards a character

• Ctrl+c copies the selected text to the clipboard

• Ctrl+d deletes a character

• Ctrl+e goes to the end of the line

• Ctrl+f moves the cursor forward a character

• Ctrl+h backspace a characters

• Ctrl+k deletes to the end of the line, or removes an empty line

• Ctrl+n moves to the next line

• Ctrl+p moves to the previous line

• Ctrl+v inserts text previously cut or copied

• Ctrl+x cuts selected text from the field

• F2 starts editing a selected label in a tree view

On systems running the X Window System (UNIX platforms), the second mousebutton inserts the Xbuffer selection at the cursor location.

5.4 Common dialog buttons

There are a number of buttons that are used throughout EuroSim.

OK Acknowledges the question, or accept the changes made in a window and close the window.

Cancel Abort the operation and all entered data is ignored.

Apply Accept the changes made in a window, but do not close the window.

Dismiss Close the dialog window.

Browse Open a dialog to select an item from a list. Often used to select a file.

42 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

5.5 Common toolbar buttons

There are a number of toolbar buttons that are used throughout EuroSim.

Undo Undo the last action.

Redo AbRedo the last undone action.

Cut Cut the selected item(s).

Copy Copy the selected item(s).

Paste Paste the cut item(s).

Delete Delete the selected item(s).

5.6 Common menu items

Throughout EuroSim, a number of menus appear with every tool. These menus have a number of ‘stan- dard’ items, which are described in this section. Note that each tool can add a number of tool-specific items to these menus - these tool-specific items are described in the sections on these tools.

5.6.1 File menu New A new file will be created. If there are any unsaved changes in the current file, a warning dialog box will pop up and ask whether you want to save the changes first.

Open Pop-up a file selection dialog box in which a file to be opened can be selected. If there are any unsaved changes to the current file, first a warning dialog box will appear (see New).

Save Save the current file without closing it. If the current file has never been saved before (an ‘Untitled’ file), a file selection dialog box will pop-up asking the user to enter the name of the file. Note that this item cannot be selected if there are no unsaved changes. Note that a window title will have an asterisk appended to the name of the file in the title if the file needs to be saved.

Save As Save the current file with a different name. The newly created file will become the current file.

Print Print the current file in an appropriate form.

Exit Close the tool and all windows associated with it. If there are any unsaved changes, a warning dialog box will pop up.

5.6.2 Edit menu Undo Undo the last action performed by the user.

Redo Redo the last undone action.

Cut Move the selected portion of data from the tool window to the clipboard.

Copy Copy the selected portion of data from the tool window to the clipboard.

Paste Move the contents of the clipboard to the tool window. Depending on the tool, the location where to paste can be selected.

Delete Remove the selected portion of data from the tool window.

c Airbus Defence and Space 43 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

5.6.3 Tools menu

Shell Start a command line session (also known as ‘xterm’ on X Window Systems (UNIX platforms), or ‘Command Prompt’ on Windows platforms).

5.6.4 Tools:Version menu Add. . . Add the selected file to the repository. A dialog appears where you can enter a text describing the change. See Figure 5.1 for an example.

Figure 5.1: The Log Message

Update Update the selected file with the latest version from the repository. Get. . . Get a specific version of the selected file from the repository. If the checkbox Remove file before update is checked, then before the selected version is retrieved, the old file is removed. Otherwise the selected version is merged with the current version. The version with a check- mark in front is the required version.

Figure 5.2: Get Version

Detailed. . . Show the detailed version history of the selected file. The version with a checkmark in front is the required version.

Figure 5.3: Detailed Information

Set Required. . . Select a required version of the selected file. The version with a checkmark in front is the current required version.

44 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 5.4: Set Required Version

Diff with. . . Show the differences of the selected file with another version of that file. The version with a checkmark in front is the required version.

Figure 5.5: Difference With

5.6.5 Help menu Online Help. . . Provide a short description of the tool. About EuroSim Show the version of EuroSim.

5.7 Dictionary Browser

The Dictionary Browser is used in many EuroSim programs to look at the data dictionary of variables and entry points that have been defined in the simulation. The Dictionary Browser shows a tree hierarchy of the entry points and variables.

Figure 5.6: Dictionary Browser

The following functions are supported in the Dictionary Browser (Note: not all EuroSim application provide all of these functions):

• Selected items can be dragged and dropped to a destination (e.g. in the Simulation Controller a plot can be configured by dragging a variable to the list of plot variables).

c Airbus Defence and Space 45 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• Double clicking on a single item will add the item to the destination (e.g. when configuring a task, double clcking an entry point will add it to the task).

• Pressing F9 on an item will copy the path of the item to the clipboard, such that you can paste it in other applications.

• You can switch between a full view and a condensed view where all unnecessary nodes are left out by pressing the F3 key or by choosing Condensed View or Full View from the context menu that you get when pressing the right mouse button in the Dictionary Browser. If you try to expand a very large array, then you will be asked for a confirmation first.

• If you want to find a variable you can use the Filter-field at the bottom of browser: just type the name or part of it you are interested in, press the Search-button and the dictionary expands to show matching items. The filter uses a case-insensitive substring search. So any variable name that contains the text without regard to upper or lower case will match. When no variables match, the browser is empty. Use backspace to delete characters from the search string until the search string is empty, press the Search-button and then you return to the original state of the browser. Note that filtering is only supported for variables, not for entrypoints (which makes sense con- sidering that the number of variables in a dictionary is much larger compared to the number of entrypoints. If the Dictionary Browser is used to display entry points, the filter widgets at the bot- tom of the browser are not shown (e.g. as can be seen when comparing the layout of the Dictionary Browser in Figure 5.6 with that shown in sections describing scheduling of tasks Section 11.2.1 and Section 11.2.2).

• The context menu contains a Expand All item to expand all nodes and a Collapse All item to collapse all nodes in the tree.

• The context menu also contains a Copy To Clipboard item to which has the shortcut F9 to copy the path of the item to the clipboard.

• Finally, there is a Info menu item in the context menu that appears when you click with the right mouse button on a node in the dictionary. Selecting this menu item will pop up a window that shows type information about the selected node. Figure 5.7 shows the information displayed when the info is requested on a complex variable node. Note that the Sizeof line shows the syze of the complex type as calculated by the parser and stored in the dictionary and includes padding.

46 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 5.7: Dictionary Info on variable node

c Airbus Defence and Space 47 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

48 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 6

Project Manager reference

This chapter describes the top-level interface of EuroSim (esim), the Project Manager. For a description of the various EuroSim components, such as the Model Editor and Schedule Editor, refer to the next chapters.

6.1 Introduction

The project Manager provides a quick access to EuroSim projects and the files contained in these projects. For this purpose the Project Manager maintains a list of projects in a file called projects.sdb which is located in the the .eurosim directory of the user. It is also possible to share this list with other users by setting the environment variable EFO_HOME, in which case Project Manager will maintain the projects.sdb in the location that this environment variable points to. The projects database contains a reference to a directory for each project. In this directory the Project Manager stores a project specific database with the name project.sdb. This project specific database contains relative files for all the files in the project. The project.sdb file can thus be shifted to other locations or handed over the other users and reconnected to their list of projects. The project.sdb database organises the files per model file. Every file depends on the .model file, and thus a project consists of multiple file trees with the .model files as root of each tree, if multiple .model files occur. When you start one of the EuroSim editors from the Project Manager to create a new file (f.i. a new schedule file), the Project Manager will automatically add the new file to the current project when you save it to disk. Depending on the settings in the preferences dialog, you will be prompted with a question if the file should be added to the project or not. In the preferences dialog you can also disable this feature. Note that files other than model files are always added in the context of the currently active model file in the current project. Each project can have multiple model files. If you have not yet selected a model file for the current project, the automatic addition of other files is disabled.

6.2 Starting the EuroSim Project Manager

The EuroSim environment is started with the esim command. This will pop-up the Project Manager window of EuroSim (see Figure 6.1).

c Airbus Defence and Space 49 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 6.1: EuroSim start-up window

With the Project Manager the various editors can be started. Before starting EuroSim, make sure that the environment variables PATH, DISPLAY1, EFOROOT and EFO_HOME 2 are set correctly. On the RedHat Enterprise Linux platform these environment variables are set automat- ically. On Windows platform environment variables are defined in the file $EFOROOT/bin/esim.bashrc. See also Section 3.2. The Project Manager will use the global project database file projects.sdb in the directory pointed to by the EFO_HOME environment variable. If EFO_HOME has not been set before starting EuroSim, EuroSim will use the subdirectory .eurosim in your home directory. The file projects.sdb contains all project references. If projects.sdb does not exist, EuroSim will create a new file. EuroSim can be terminated by selecting the File:Exit menu option.

6.3 Views in the Project Manager

When the Project Manager has been started, a window similar to the one in Figure 6.1 is shown. This window is divided into three parts:

Selection pane This pane contains two drop down boxes allowing the user to select the project and model for which the files will be displayed in the Files pane. Files pane The files pane shows the files for the selected Project and Model, categorized into the various types of files for the EuroSim specific file types. Button pane The Button pane provides quick access to the main editors. If the user prefers direct access to additional editors then this can be configured as part of the Preferences in the Tools menu. If an editor is started it will load with the selected file in the Files pane, or with a new file if no selection is made.

1On the Windows platform, the DISPLAY environment variable will not be used by EuroSim 2This variable only needs to be set to override the default value ($HOME/.eurosim)

50 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

In addition the toolbar provides quick access to the functions of the Insert menu ((see Section 6.4.3)), and the status bar displays the project location for the project selected under Select Project.

6.4 Menu items

6.4.1 File menu There is only a single projects.sdb file that is automatically loaded and updated, hence no file menu items apply.

6.4.2 Edit menu Set Description. . . Adds a file description to a selected file. Edit File. . . Opens the associated editor for the currently selected file. This is the same as double-clicking a file in the files list. Project Settings. . . Opens a dialog for changing various project description items. A project description contains a number of elements, each of which can be set in this dialog (see Figure 6.2).

Figure 6.2: Project Settings dialog

Name The project name is the name that appears in the project list of the Project Manager, as well as in various other places, such as the name of the root node of the model hierarchy in the Model Editor. Description The project description is a free-text field that can be used for a more precise descrip- tion of the project. Directory The project directory is the top of the directory tree in which all project related files will be stored. The Browse button can be used to search for an existing directory. Use the operating system file protections to protect project files against unauthorized use. Under UNIX one could for example create a UNIX group for each EuroSim project and make the project files writable by group members only. Depending on the security level required, the project files can be made world readable or not3.

3 Making UNIX groups and assigning members requires ‘root’ privileges and hence is a system administrators/facility man- agers job. Implementing a good protection strategy is not easy, but is assumed to be within the knowledge of the system administrator.

c Airbus Defence and Space 51 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Version Control System Defines which version control system will be used for this project. Currently EuroSim supports the CVS and Cadese4 version control systems. Repository Root The repository root is the top of the directory tree in which the version management of the various model files will be stored. Refer to Section 2.5, for a discussion whether the repository can best be kept separate from the project root or not. The Browse button can be used to search for an existing directory. If an existing CVS repository is to be used within EuroSim, make sure that the tree under the project root has the same structure as the repository tree. The repository root field is optional and can be left empty. See Appendix F on how to set-up a repository root.

6.4.3 Insert menu Add Project. . . Opens a dialog for adding an existing project or for creating a new project (see Figure 6.3).

Figure 6.3: Add Project dialog

Fill in the various project description items of the window. For the dialog field descriptions refer to Section 6.4.4, item “Project Settings. . . ”. Remove Project Use this option to remove the current project from the projects list. The actual project files (such as the model file, the schedule, etc.) are not deleted. Add Model. . . Opens a dialog for selecting the model to add to displayed project (see Figure 6.4).

4Not supported in the Windows version.

52 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 6.4: Add Model dialog

The model will appear in the drop down list under Selected Model. Remove Model Use this option to remove the model from the current selected project. The actual model file will not be deleted from disk by this action. Add File(s). . . Allows opening a dialog for selecting a file to add to the selected project and model combina- tion. A list of different types can be selected, the difference being the setup of the filter of the file selection dialog that will be popped-up. Remove File Use this option to remove the selected file in the Files list from the project for the specified model. The dialog that follows will allow the user to choose between cleaning the file from disk or only removing the reference to the file.

6.4.4 Tools menu Shell. . . Opens a new command shell (e.g. xterm or a DOS command prompt). Model Editor. . . Starts the Model Editor. Model Description Editor. . . Starts the Model Description Editor. Parameter Exchange Editor. . . Starts the Parameter Exchange Editor. Calibration Editor. . . Starts the Calibration Editor. Schedule Editor. . . Starts the Schedule Editor. Simulation Controller. . . Starts the Simulation Controller. Test Analyzer. . . Starts the Test Analyzer. Observer. . . Starts the Simulation Controller in Observer mode.

c Airbus Defence and Space 53 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Preferences. . . Opens a dialog to set the preferences. The following items can be set. Do not prompt to add files automatically When you start one of the EuroSim editors from the Project Manager and create a new file, you are prompted whether the new file should be added to the current project. If you check this item, you will not be prompted and the decision whether to add the file to the current project depends on the value of the next item. Never add files automatically If this option is checked, new files that are created by one of the EuroSim editors will not be added to the current project automatically. If you want to add a newly created file afterward, then use the appropriate menu command. Show additional editor buttons If this option is checked, buttons are displayed for sub-editors that are normally con- trolled from within the main editors. In particular this applies to the Model Description Editor, the Parameter Exhange Editor and the Calibration editor.

6.4.5 Help menu Online Help This menu option will start the ‘Netscape’ HTML-browser for UNIX and the ‘Internet Explorer’ for Windows which will load the on-line version of the user manual. About EuroSim This will pop-up a window displaying the copyright information for EuroSim.

54 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 7

Model Editor reference

This chapter provides details on the Model Editor. The various objects which can be added to the model tree, the menu items of the editor and their options are described. For menu items not described in this chapter, refer to Section 5.6.

7.1 Starting the Model Editor

The Model Editor can be started by selecting the Model Editor button in the EuroSim start-up window (see Figure 6.1). Alternatively, the Model Editor can be started by typing ModelEditor < filename.model> on the command line. This will pop-up the Model Editor window of EuroSim (see Figure 7.1.

Figure 7.1: Example Dictionary view

7.2 Views in the Model Editor

When the Model Editor has been started, a window similar to the one in Section 12.12 is shown. This window is divided into two main parts, separated by a splitter: Tab pane This pane contains two tab pages that are used for selecting and parsing files to be included in the simulator and the dictionary after building a simulator. Message pane Shows the output from the build process for creating a simulator executable. At the top is the menu bar and a tool bar. At the bottom a status bar provides additional state information.

c Airbus Defence and Space 55 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

7.2.1 The toolbar The tool bar provides easy access to the following functions, beyond the standard buttons already de- scribed in Section 5.5

New Create a new Model definition. The same as the File:New menu item. Open Open an existing Model Definition. The same as the File:Open menu item.

Save Save the current Model Definition. The same as the File:Save menu item. Build All Build the simulator (executable, dictionary). The same as Tools:Build All. Cleanup Cleanup the simulator and all files generated in the build process. The same as Tools:Cleanup. Build Cancel Cancel the ongoing build of the simulator. The same as Tools:Cancel. Build Doc Build the simulator documentation. The same as Tools:Build Doc. Show Doc Show the simulator documentation. The same as Tools:Show Doc.

7.2.2 The tab pane The tab pane consists of the following tab pages:

Files In the Model Editor tree view the structure of the model is created using a hierarchical, tree structure. Elements in the tree are called nodes and have a specific function. The API (properties of variables and entry points available to the rest of EuroSim) can be edited in the Model Editor. In Figure 7.2 an example model tree is shown.

Figure 7.2: Example model tree

Note that only org nodes and file nodes can be directly added to the model hierarchy (using the menu options Edit:Add Org Node, Edit:Add File Node or Edit:Add Directory). The other nodes are put into the model hierarchy indirectly, e.g. by parsing the files. Informational messages are written to the logging window while parsing the files.

56 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Dictionary The Dictionary tab displays the EuroSim Dictionary after a complete EuroSim build. For clas- sical EuroSim usage, this tab will be the same as the import tab after building the dictionary. For the Object Oriented language interfaces such as the EuroSim native C++, and Java API and SMP2 standard support, this tab will show all the objects and their child nodes in the hierarchy dictated by their ownership relations. In Figure 7.3 an example model tree is shown.

Figure 7.3: Example Dictionary view

7.2.3 The message pane The message pane displays the output of the make process, either as a consequence of pressing Build (make all) or Clean all (make clean). The Build process generates a makefile .make by running the ModelMake tool as: ModelMake After generation of the make file it executes the make file using gmake (mingw32-make on Windows). Note that gmake -jN modelname. make is also allowed and considerably speed sup the simulator build process.

7.2.4 The status bar The status bar displays the model that is loaded and the status of the model. The latter refers to the versioning of files using the build in versioning capability fo the Model Editor to assure Traceable Simu- tions. It is not required to use this feature to have traceable models. Many users find it preferable to apply versioning of files outside the Model Editor. If no version control system was selected for internal versioning, the status bar will display Ne versionig.

7.3 Objects in the Model Editor

This section describes each of the nodes that can occur in the Import and Dictionary tabs of the Mod- elEditor. The default icon for the node is shown in the left margin. If more than one icon is used, all are shown.

7.3.1 Root node The root node represents the complete model. It is a special type of org node (see next section) and therefore shares the same attributes of org nodes. The name of the root node in the attributes window

c Airbus Defence and Space 57 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

is the name of the model file. The name displayed on the Model Editor window is the (file)name of the model, or Untitled.model if a new model is started and has not been saved yet. Double-clicking the root node folds or unfolds the node.

7.3.2 Org node Org nodes are used to structure the model. By using org nodes, two or more related sub-models can be grouped together by connecting them to the same org node. Both other org nodes as well as file nodes (representing the sub-models) can be attached to an org node. The name of the org node can be changed by clicking a selected node. A description can be entered in the description field.

7.3.3 SMP2 lib node SMP2 lib nodes organise the files that compile into an SMP2 library. SMP2 catalogues, a package, and a folder containing generated C++ code and a Makefile can be attached to an SMP2 lib node. Refer to Chapter 18 for more information.

7.3.4 File node There are various types of file nodes. They will be discussed in the sections below. The name of the file node can be changed by clicking a selected node. The filename cannot be changed. A description can be entered in the description field. The file attached to a file node can be viewed and edited through the menu options Edit:View Source and Edit:Edit Source respectively. Depending on the type of file, the correct viewer or editor is started. When a file is being edited or viewed the file icon with lock is shown. The viewer/editor of SMP2 Artefact file nodes (catalogues, packages, and Assemblies) can be defined by the user in the SMP2EDITOR environment variable. If that variable is not set by the user, EuroSim falls back to the EDITOR environment variable. If no SMP2 modelling environment is available on the user’s system, it is recommended to use an XML viewer as SMP2 Artefact file node viewer/editor. The properties of a filenode can be shown with Edit:Properties (see Figure 7.4). You can select another file using the Browse button. For non-source files the type of the file can also be modified. As different file types have different attributes and functions, it is important to correctly enter the file type.

Figure 7.4: File Properties

See Section 5.6.4 for information on how to change the version requirement.

58 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

7.3.4.1 Environment file node The environment node of a model is used to store information on the current development environment and the required target environment. It is used during build to check whether the current environment matches the required environment. The options Edit:View Source and Edit:Edit Source start the environ- ment viewer and editor respectively. Refer to Section 7.6 for more information.

7.3.4.2 Source file node Currently supported source file nodes are for the classic languages C , FORTRAN and Ada-95, as well as the Object Oriented languages C++ and Java. For more information on the restrictions on those lan- guages, refer to the Limitations sections for each specific language in the Modelling Reference volume. Note that it is not possible to have more than one file node referring to the same source filename, even if these files are in different directories. Double-clicking on a source file node will start the source code editor defined by the EDITOR environ- ment variable, or the editor defined in the esim conf file. For the classical languages, the files whil have the option to unfold or fold. Unfolding C and Fortran files will start the EuroSim parser to show the API information of a source file. For Ada there is no code parser, but if the user writes the API manually the unfolding will show the API defined by the user. If the source

file cannot be parsed, due to a syntax error, the broken file icon is shown. If the API information is changed, i.e. attributes of variables or entry points are changed, and the file is not yet saved the file icon gets an asterisk .

A variable or entry point is part of the API if its checkbox is checked. See the decayaltitude entry node in Figure 7.2.

Use the mouse or the space bar to change the state of the API check box on the current selection, which can contain multiple items. Interface:Save API writes this information to the source file. For C++, Java and SMP2 files there are no parsers as there is not a direct relation between the file that implements a class and the creation of objects. For these languages the simulator is build and executed, but instead of activating the scheduler, the dictionary is written to file. The dictionary for each of the languages and interfaces are then merged with the dictionaries created for the classical languages and the result is displayed in the Dictionary tab. For the OO languages, there is thus no unfold capability on a single file, but its published items should be looked up in the Dictionary tab.

For more information on how to add SMP source code see Chapter 18. For more information on the use of the native C++ API see Chapter 16. For More information on the Java API see Chapter 19 Note that warnings and errors that occur during parsing and saving of files are shown in the logging window at the bottom of the Model Editor.

7.3.4.3 Model Description file node Model Description files together with Parameter Exchange files and Calibration files togheter specify the integration of models using the EuroSim SimInt library. Model Description file nodes can be added to the model file to generate a so called “datapool”. See Chapter 8 for a description on the datapool and how to create a Model Description file. During the build process (make), which can be started from the Model Editor, Model Description files that are part of the model will be read to generate the variables and entry points for the datapool.

c Airbus Defence and Space 59 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

7.3.4.4 Parameter Exchange file node Paremeter Exhange files use the ModelDescription files and calibration file scontained in the ModelEditor as input and can be used to interconnect models via their datapool variables. Parameter Exchange file nodes can be added to interconnect Model Description output nodes with Model Description input nodes. See Chapter 8 for a description on the datapool and how to create a Model Description file. During the build process (make), which can be started from the Model Editor, Parameter Exchange files that are part of the model will be processed into code that performs the code with option calibration.

7.3.4.5 Calibration file node The calibration editor allows the user to define their calibration curves based on values and possible interpolation or polygon definitions. The curves can be associated with a parameter exchange in the Parmameter Exchange editor. See Chap- ter 10 for more information.

7.3.4.6 Makefile node Custom makefile nodes can be added to the ModelEditor tree to activate build or clean activities as a result of activating a Build All or Clean All action, either from the GUI or via a ModelMake generated makefile. These makefiles typically are ued to build external libraries that must exist before the EuroSim build actions can take place.

7.3.4.7 SMP2 Assembly file node SMP2 Assembly file nodes can be added to the model file to generate a file that creates instances of the models and data flows between them, according to the SMP2 Assembly specification. Refer to Chapter 18 for more information.

7.3.5 Entry nodes An entry node represents a schedulable function or method. In the classical API (C,Fortran) the entry point is a function that has no parameters and no return value. In the Object Oriented API the entry point can be either a published method or function that has no arguments or return value. Some system generated entry points exist in thenew OO API to support dataflow scheduling.

7.3.5.1 Entry node

An entry node represents an entry point in a source file. For the classical API, it is part of the API of the model if its checkbox is checked (see Section 7.3.4.2). The description is the only attribute of an entry point.

If the API information in the file contains entry points that are no longer available in the source code, a red cross is drawn through the icon. In the OO API, an entry node represents a published method or function in the API. These entry nodes only appear in the Dictionary tab after a succesfull build. The description is the only attribute of an entry point.

60 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

7.3.5.2 Transfer node In the OO API, a Transfer (xfer) node represents a schedulable entry node that performs the transfer of data from an Output put port to an Input port. A dataflow transfer is thus controller by schedulig this node. Transfer nodes only appear in the Dictionary tab after a succesfull build. The description of a transfer node is generated and contains the output and input port path.

7.3.5.3 TransferGroup node In the OO API, a TransferGroup node represents a schedulable entry node that performs the transfers that are listed as its direct child nodes in the dictionary. The TransferGroup node thus allows the user to group a list of tranfers in a single schedulable entry point, reducing the amount of work to specify the scheduling of the individual transfer nodes. The description is the only user definable attribute of a transfer group point.

7.3.6 Variable nodes A variable node represents a variable in a source file. It is listed under the file where it is used and also under every entry point that uses it. It is part of the API of the model if its checkbox is checked. (See Section 7.3.4.2 above on API editing.) The initial value and type of a variable are determined by parsing the source code. Compound variables, such as arrays and structures, are shown as children of the variable node. Some attributes of the variable node can be edited at variable node level in the tree view of the Model Editor, while others must be edited at the variable base level (f.i. min and max). You can only edit attributes of variables when the API flag on the left of the variable is checked. Use the mouse or the space bar to change the state of the API check box on the current selection, which can contain multiple items. A grey box around an attribute indicates that it is editable. Start editing by clicking in the box with the mouse or press the F2 key to start editing the first editable attribute in the current selection. The Tab key moves to the next editable attribute in the current selection, while the Enter key finishes editing without moving to another attribute. The Esc key lets you leave edit mode without making any changes. The user can specify:

• parameter: a variable set as a parameter may only be changed at initialization time by an initial condition.

• unit: the unit of the variable, e.g. km. It is for informational purposes only and written to the dictionary for use by other EuroSim tools, such as the API tab of the Simulation Controller.

• min: the minimum value of the variable.

• max: the maximum value of the variable.

The latter two (min and max) are checked at run-time when f.i. a user changes the value through the API tab of the Simulation Controller.

If the API information in the file contains variables that are not available in the source code a red cross is drawn through the icon. Note that the entry point and variable information is extracted from the file after the language specific pre-processor has processed the file. In particular, if compile flags determine which entry points are available the API may show conflicts when compile flags change. In order to avoid problems with globals that only have a local ‘extern’ declaration in entry points, the extern keyword will be emitted by EuroSim when creating the data dictionary. In particular this means that for externals with function scope no API information can be generated.

c Airbus Defence and Space 61 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

7.3.6.1 State variable For the classical APIs (C, Fortran) these nodes refer to variables which have filescope and are read and written by entry points in the file. For Object Oriented APIs (C++) this is the default for member variables that are published to the dictio- nary.

7.3.6.2 Read Access variable For the classical APIs (C,Fortran), these nodes refer to variables that are read by the entrypoints. When using the classical APIs ( C, Fortran) the parser detects whether entrypoints read the variables and set the input state accordingly. The icon shows that the data is read by an entrypoint from the variable. At global (file) scope, the sum of all access is shown. A variable that is read in one entrypoint and written in another entrypoint thus shows up as read access variable in the first entrypoint, write access variable in the second entrypoint and combined read write access at filescope level.

7.3.6.3 Write Access variable For the classical APIs (C,Fortran), these nodes refer to variables that are written by one or more en- trypoints. When using the classical APIs ( C, Fortran) the parser detects whether entrypoints read the variables and set the output state accordingly. The icon shows that the data is written by an entrypoint into the variable. At global (file) scope, the sum of all access is shown. A variable that is read in one entrypoint and written in another entrypoint thus shows up as read access variable in the first entrypoint, write access variable in the second entrypoint and combined read write access at filescope level.

7.3.6.4 Read/Write Access variable For the classical APIs (C,Fortran), these nodes refer to variables that are read and written by entrypoints. When using the classical APIs ( C, Fortran) the parser detects whether entrypoints read or write the variable and set the input, output or input/output state accordingly. The icon shows that the data is read and written by an entrypoint when occuring inside an entrypoint. At global (file) scope, the sum of all access is shown. A variable that is read in one entrypoint and written in another entrypoint thus shows up as read access variable in the first entrypoint, write access variable in the second entrypoint and combined read write access at filescope level.

7.3.6.5 Input variable For the Object Oriented C++ API the developer sets the input state explicitly via an API call instead of access detection via Parsers. In the context of C++ objects the icon therefore has a different meaning then the access denotation of the classical API. Setting the input state of a variable denotes visually that this is a variable that the user may set. An example is a thermostat temperature setting. The default variable notation is then used for an internal variable that is relevant for a simulation developer, but not for a simulation user (simulation controller). This is a suggested usage for the C++ API, it has no further effect.

7.3.6.6 Output variable For the Object Oriented C++ API the developer sets the output state explicitly via an API call instead of access detection via Parsers. In the context of C++ objects the icon therefore has a different meaning then the access denotation of the classical API. Setting the output state on a variable denotes visually that this is a monitor node, a variable that the user may want to monitor or record. An example is the temperature that is measured by a sensor. The default (State) variable notation is used for an internal

62 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

variable that is relevant for a simulation developer, but not for a simulation user (simulation controller). This is a suggested usage for the C++ API, it has no further effect.

7.3.6.7 Input/output variable For the Object Oriented C++ API the combined input/ouput variable node visualises that the developer considers this node to be both an input that the user may change via initial conditions or even during the simulation, as well as suggest to the user that this variable is suitable to monitoring or recorinding.

7.3.7 Object node The object nodes are introduced in EuroSim Mk5 and appear only in the Dictionary Tab of the editor where they reflect an instance of a class. The entry nodes and variables that are children of the object node are to be viewed as methods and member variables of the instances. Object nodes can have other object nodes as child nodes. This reflects an ownership relation, where the parent node created the child node. However, please beware that in the CPP API there is a lot of flexibility in shaping the dictionary. The visual presentation may be constructed by the user even if when it is not actually present in any class definition.

7.3.8 Model node 7.3.9 Device node 7.3.10 Port node The In- and Out ports are introduced with the C++ API in Mk5. The C++ API contains functions to create dataflows that connect outports to inports. The port nodes only appear in the Dictionary Tab of the ModelEditor.

7.3.10.1 Inport node Inport nodes can have other object, entrypoint or variable nodes as children in teh tree. These child nodes reflect properties of the inport related to the value in the port that is filled by a dataflow, the possible scheduling of data transfer from the port variable to its associated instance variable, and error injection control variables. See the C++ API reference documentation for more information.

7.3.10.2 Outport node Outport nodes can have other object, entrypoint or variable nodes as children in the dictionary tree. These child nodes reflect properties of the outport related to the value in the port that is extracted by a dataflow, the possible scheduling of data transfer from the instance variable to the port variable and error injection control variables. See the C++ API reference documentation for more information.

7.3.11 Channel node 7.3.12 Sequence node 7.4 API Selection

7.4.1 Selecting API Variables and Entrypoints The File tab of the Model Editor provides the user the capability to parse model files using the EuroSim model parsers for C and Fortran. These parsers provide an easy method to identify to EuroSim which elements in the source code are relevant in the context of building and using the simulator and simula- tions. The parser analyzes the code and shows what could be included in the EuroSim dictionary. The

c Airbus Defence and Space 63 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

EuroSim user selects from these available resources which are relevant. On Save EuroSim then writes this selection in a so called API header as comment at the top of original source file.

7.4.2 Selection within a sub-model

When selecting a variable for inclusion within the API header, a variable can sometimes appear twice, because the parser sees the variable being used not only at file level, but also at the level of the function that uses it. See for example altdata$altitude in Figure 7.2. In principle, there is no difference between selecting one or the other: both variable nodes are different representations of the same variable and hence point to the same memory address. The default situation can be taken as tagging variables at the level of their file scope. However, there can be sometimes reasons for tagging the variables beneath ‘their’ entry point:

• if there are a lot of API variables within a particular sub-model (source code file), then selecting variables which appear below their relevant entry points gives you an additional level of hierarchy which can ease identification and manipulation of API variables later on

• if there is a significant amount of data dependency between entry points which needs to be taken into account during scheduling, then again, the variables beneath entry points should be selected, as this relationship is used when determining tasks which share data (see also Section 11.3.5, on intersection)

7.4.3 Selection from two or more sub-models Where variables are used by two or more functions, they will appear in more than one sub-model. An ex- ample is the altdata$altitude variable seen in Figure 7.2, which also appears in the listing of variables for the Initialise_Altitude source file. Again, there is no difference between selecting one or the other, as both representations point to the same memory address. The general guideline is to tag (and annotate) the variable belonging to the code which will be active during the executing scheduling state. In the example given above, this means that altdata$altitude would be tagged for the Altitude source rather than for its one-off use in the Initialise_Altitude source.

7.5 Menu items

7.5.1 File menu New Creates a new empty model.

Open Opens a model.

Save Save the current model.

Save As If the model file is saved to a different directory, the file nodes are updated so that the newly saved model file shares its files with the original model file. If you want a copy of the model file with the relative pathnames of file nodes unchanged, thus possibly referring to non-existing files, use the UNIX cp or DOS copy command from the command line of a shell.

Exit Exit the Model Editor.

7.5.2 Edit menu Undo/Redo Undo/redo actions.

64 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Cut/Copy When cutting or copying an org node, the whole subtree, including the selected org node, will be copied for later pasting.

Paste Paste cut or copied data. Nodes are pasted into the currently selected node.

Delete Delete the current selection. Edit Source For file nodes, this option will start an editor with which the file attached to the node can be modified. For program source files by default the ‘vi’ editor will be started on UNIX platforms and NotePad on Windows platforms. If the environment variable EDITOR is set, that editor will be used. For environment file nodes, the environment editor (see Section 7.6) will be started. View Source For file nodes, this option will start (if applicable) an external program to view the contents of the file attached to the node. Rename Node Rename the currently selected file or org node. Properties Shows the properties of a file node (see Figure 7.4) and allows specifying another file name for this file node.

7.5.3 View menu Expand To Files This menu option will show file nodes. Expand All This menu option will show all nodes of the tree. All source files will be parsed and entry points and variables will be shown. Collapse All This menu option will close all nodes of the tree.

7.5.4 Insert menu New Org Node. . . When an org-node is selected in the model hierarchy, this menu item can used to attach a new org node as a child to the selected node. The name and description of the new node can be entered. New SMP2 Lib node. . . When an org-node is select in the model When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used to attach a new SMP2 lib node as a child to the selected node. The name of the new node can be entered. This will be the name of the SMP2 library that is produced by the files that will be attached to the SMP2 lib node. Refer to Chapter 18 for more information. New Source Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new C, Fortran, Ada, C++, or Java source or header file node from the EuroSim template and insert it in the model hierarchy. New Model Description Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Model Description file and insert it in the model hierarchy.

c Airbus Defence and Space 65 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

New Parameter Exchange Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Parameter Exchange file and insert it in the model hierarchy. New Calibration Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Calibration file and insert it in the model hierarchy. New Text Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new flat text file and insert it in the model hierarchy with a suitable template. New Make Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new make file with a suitbale template and insert it in the model hierarchy. These files are first called in the Build All and Clean All actions in the ModelEditor prior to the EuroSim specific build actions to allow custom build preparations New Doxygen Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Doxygen compliant text file and insert it in the model hierarchy with a suitable template. The dox files are used in the Build Documentation capability found in the toolbar to generate custom documentation of the code. New Document Node. . . When an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Document file and insert it in the model hierarchy. New Environment Node. . . hen an org-node is selected in the model hierarchy, or when the root node is selected, this menu item can be used create a new Environment file and insert it in the model hierarchy. Add Directory. . . When an org-node is selected in the model hierarchy, this menu item can be used to recursively add a complete directory tree to the selected node. The directory can be selected using a direc- tory selector. Each directory found in the selected directory will be added as an org-node. The files that are found will be added as children to their respective parent node. This command automatically filters out the CVS and .svn directories, if any. Add File Node. . . When an org-node is selected in the model hierarchy, this menu item can be used to attach a new file node as a child to the selected node. The file can be selected using a file selector. The name of the node can be changed into a more descriptive name by clicking in the selected node name after the file node has been added to the node tree. When adding a non-existing file, a dialog box will pop-up asking whether to create a new file or not. Templates for new files can be found in the lib/templates sub-directory of the EuroSim installation directory. Add SMP2 catalogue. . . When an SMP2 lib node is selected, this menu option can be used to attach an SMP2 catalogue file to the SMP2 lib node. Refer to Chapter 18 for more information. Add SMP2 package. . . When an SMP2 lib node is selected and no SMP2 package file has yet been attached to it, this menu option allows to attach an SMP2 package file to the SMP2 lib node. The SMP2 package file is required to have the same name as the SMP2 lib node, which is the name of the library that is the target of the SMP2 lib node. Refer to Chapter 18 for more information.

66 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Add Generated C++ Code If an SMP2 package file node is selected or if an SMP2 lib node is selected and a package file node is present in the SMP2 lib node, this menu option allows the user to attach a tree of files and folders that has been generated from the package and is present on the file system. The files and folders making up the tree of generated code will be attached to the SMP2 lib node in a hierarchy. Refer to Chapter 18 for more information.

7.5.5 API menu Parse File(s) Parse the selected file(s) to discover it’s API and/or find items that can be added to the API of the sub-model. Save API Writes the API information to the sub-model source file. Clear API Removes the API information from the sub-model source file.

Include Add variable or entry point to the API. Exclude Remove a variable or entry point from the API Exclude all undefined. . . Remove all variables and/or entry points that are still in the API but no longer available in the sub-model source code. Clear Min Clears the minimum value(s) of a variable node. Clear Max Clears the maximum value(s) of a variable node.

7.5.6 Tools menu Build All Build the simulator and data dictionary. Build Clean This menu option will remove all generated files from the model directory. This includes the data dictionary, and compiler generated object files. Use this option to force a rebuild of the model. This option is generally used when a new version of EuroSim has been installed, when the filesystem has had integrity problems, or when EuroSim does not behave as expected.

One specific case where a clean up is required is when you add a new file to the model hierarchy (e.g. a C source file) which is older than the already existing target file (e.g. add a file file.c whilst there still is a newer file.o). The make which is used to build the simulator will then not know that the target should be recreated. The same applies when deleting a file node from the model tree. Set Build Options. . . When in source files external functions are used (such as arithmetic or string functions), the libraries containing these functions can be specified in the options dialog shown by this menu option (see Figure 7.5).

c Airbus Defence and Space 67 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 7.5: Model Build Options dialog: Options tab page

Also, specific compiler options can be specified, including directories where the compilers should look for include files. In the libraries field, libraries which need to be linked to the simulator should specified in the form -llibraryname. One of the more often used libraries is ‘m’, the math library.

The Makefile field allows you to define the Makefile that is executed by the ModelEditor when you push the Build All and Cleanup buttons. This option is for instance usefull if you have to assure that libraries are rebuild before the EuroSim build links them to the simula- tor. When nothing is specified in the Makefile field, the ModelEditor will issue the command gmake -f .make -C -j where is either ’all’ or ’clean’ based on the button you pressed. The Processor field allows you to execute the build on multiple processors. This parallel build is considerably faster. When leaving the field blank, the -j tag will be omitted. When set- ting it to ”auto”, all processors in your system will be used. The name of the file specified in the Makefile field will replace the .make part in this command. Your user defined Makefile should accept the all and clean targets, and execute the original EuroSim make command at the appropriate time. This enables the user to do some actions prior to running the EuroSim makefile. See the ThermoMra example on how to do this.

68 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 7.6: Model Build Options dialog: Support tab page

Figure 7.6 shows the available pre-defined build support options for the simulator. Selecting one or more of these options causes libraries such as ‘external simulator’ or ‘telemetry and telecommand’ to be linked in, augmenting the simulator with extra runtime functions. Usage of Ada-95 runtime libraries requires explicit selection of the appropriate options. The provide simulator as dll option creates both a dll and exe, where the dll can be loaded and used via the esimMain() function call to embed a simulator in another application. The Options are defined in the EuroSim.capabilities file in the etc dierctory of the EuroSim distribution, and can be listed using the esimcapability command.

c Airbus Defence and Space 69 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 7.7: Model Build Options dialog: Configuration tab page

Figure 7.7 shows the available configuration options for the simulator. Selecting one of the options allows you to change the default value. It is possible that during run-time you exceed one of the buffer sizes or need more heap or stack memory. In that case change the appropriate size so that the simulator runs without exceeding the sizes.

Figure 7.8: Model Build Options dialog: Compilers tab page

The Compilers tab page (see Figure 7.8) allows you to specify which compiler(s) and related

70 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

utilities to use to build the simulator. When specifying a command, the default used by the build command will be overruled. Leaving a field blank in the dialog will cause the build command to use the default command. You can specify just the command (provided its directory can be found in the PATH environment variable) or the full path, for example:

/usr/bin/gcc

You can also specify additional command line options for a specific command, for example:

g77 --no-second-underscore

The commands specified on this tab page dialog are not stored in the model file, but in a global resource1. Therefore, the command specifications are model independent. The specifications are read by the ModelMake utility when generating the makefile that is used to build the simu- lator executable. They are effective after the Tools:Cleanup command. Build Doc Builds the doxygen model documentation of the simulator. The Tools:Build All command must be executed before building documentation. The Doxyfile placed in the model source root will determine the main layout. Note, an example can be found in the EuroSim distribution under $EFOROOT/lib/templates/template.dox. Show Doc Opens a browser and shows the HTML output of the simulator documentation. Clear Logging Clears the logging window at the bottom of the Model Editor. Save Logging Opens a file dialog where you can select or specify the name of the file to save the contents of the logging window. Preferences Shows a dialog where you can specify Model Editor specific preferences. Examples are saving API information to files and saving the changes to the .model file or automatically clearing the logging window, before starting a build. Note that the system wide preferences can be found in the $EFOROOT/etc/esim conf file. See Section 7.7

7.5.7 Tools:SMP2 Tools menu Install SMP2 Library If an SMP2 lib node is selected, this menu options builds a library for the files attached to the SMP2 lib node and installs it in the directory where EuroSim will install its executable simulator. The SMP2 lib node must contain an org node with the same name as the SMP2 lib node and an SMP2 package lib node with the same name. The org node contains the generated C++ code and it must contain a Makefile. It is not required to use this menu option, as the SMP2 Library will also be build when selecting the Build All command. It may however be useful to build an SMP2 library in isolation of the rest of the model tree if the model tree is not yet completely finished and the user is editing the generated C++ code of the SMP2 library. Moreover, if a change is made in the generated C++ code for the SMP2 library, the user must apply this function to install an updated version of the library. Refer to Chapter 18 for more information.

1Located in the .eurosim sub-dicrectory of your home directory (Unix systems) or in the registry (Windows systems)

c Airbus Defence and Space 71 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Cleanup SMP2 Library Under the conditions described above, this menu options removes all generated binary files from the directory containing the generated C++ code. If a library was installed, it is removed as well. Use this option to force a rebuild of the model, e.g. when the source code of the library has been modified, when a new version of EuroSim has been installed, when the filesystem has had integrity problems, or when EuroSim does not behave as expected. Refer to Chapter 18 for more information. Validate SMP2 Artefact If an SMP2 file node is selected (catalogue, Assembly or package), this menu option validates the SMP2 artefact and reports the result. Refer to Chapter 18 for more information. Generate Default package If an SMP2 catalogue file node is selected that has the same name as the SMP2 lib node that it is attached to, or if an SMP2 lib node is selected that has a catalogue attached to it with the same name, this menu option generates an SMP2 package and attaches it to the SMP2 lib node. The SMP2 package contains an implementation for all types in the catalogue that need an implementation. Refer to Chapter 18 for more information. Generate C++ Code If an SMP2 package file node is selected, or an SMP2 lib node with a package attached to it, this menu options allows the user to generate C++ code from the package. The generated code is a hierarchy of files that is attached to the SMP2 lib node inside an org node with the same name as the SMP2 lib node. If generated C++ code was already attached, this menu options generates the code and integrates any existing implementation by the user in the new version of the code. Refer to Chapter 18 for more information. Generate Makefile Template If an SMP2 package file node is selected, or an SMP2 lib node with a package attached to it, and a Makefile is not yet present on the file system in the directory associated with the SMP2 library, generate a Makefile template that can be completed by the user to contain the correct installation command for an imported SMP2 library. The ”install” target of the Makefile should install the shared object that is the result of SMP2 library building in the central installation directory of the EuroSim simulator. The ”clean” target of the Makefile should remove an installed shared library. Refer to Chapter 18 for more information.

7.6 Environment editor and viewer

The environment editor is started by selecting the environment node in the model tree and selecting the Node:Edit Source menu option. The viewer is started using the menu option Node:View Source when the environment node is selected.

7.6.1 The environment viewer The environment contains information on the target hardware required for the simulator being developed. The environment viewer (see Figure 7.9) shows at the right the current environment, and at the left the target environment, as it is stored in the environment file. If there are any differences between the two, these are indicated with unequal signs (<>). If a field from the environment is too long to fit in the text area, the middle mouse button can be used to scroll the text area to reveal the remainder of the field.

72 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 7.9: The environment viewer

7.6.2 The environment editor The environment editor allows the user to retrieve the current environment and save it to the environ- ment description file, as well as adding a comment to the environment file. Use the button Get Current Environment in the Environment Editor to retrieve the current environment. To put the file under configuration control use the same procedure as for source code files.

Figure 7.10: The environment editor

7.7 Configuring File Associations

The Model Editor allows the user to define which editor to start when double clicking a file in the File tab, or selecting Edit or View source from the context menu after a right click. These file associations are configured in the file esim conf that can be found in the etc directory of the EuroSim installation tree. The file shows that by default the editor that is named in the EDITOR environment variable is started. If that is empty the ModelEditor defaults to vi for Linux and notepad for Windows. The easiest approach to configure a different editor is to set the EDITOR environment variable to your favorite editor. For instance on Linux gedit is a good candidate and for Windows we advise notepad++. You should then also assure that the path up to the directory that the executable is located at is in your PATH variable. You may need your system administrator to handle this. The alternative approach to configuring different editors is to modify esim conf. Note that changing this file in the ets directory of the EuroSim installation will affect all EuroSim users. To make personal customizations, one can overrule any setting with an esim_conf file in your home directory. The esim conf file currently does not accept spaces in path names, thus assure that the PATH variable for the system is amended with the directory where your editor is stored rather than writing out the complete path.

c Airbus Defence and Space 73 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

74 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 8

Model Description Editor reference

This chapter provides details on the Model Description Editor (MDE). The menu items that are specific to the MDE will be described in separate subsections of this chapter. For menu items not described in this chapter, refer to Section 5.6.

8.1 Introduction

The MDE creates a datapool to support model integration without needing to explicitly extend the models. Its usage is optional and is most useful for models written in C/Fortran, although it works with any language. The concept of creating and using a datapool to integrate two models is shown in Figure 8.1.

Figure 8.1: Datapool Model Integration concept

Shown in Figure 8.1 are two models A and B that have an input variable X, and output variable Y and some other internal variables a, b and c. Let’s assume that the intent is that these two models connect their input X to the output Y of the other model. Using the model description editor this is not performed directly between models but rather through a datapool. The concept of a datapool allows the definition of an interface for model integration in which the datapool variables are then the defined interface of models. Parameter exchanges (copies between variables, see Chapter 9) are then used to interconnect the models indirectly. By performing the model integration through a datapool it becomes easy to use models in different configurations. Additionally the mdcopy() routines are the ideal place to support generic error injection in support of fault detection, isolation and recovery functionality in the product under test. The Model Description Editor allows the user to describe the contents of the datapool in relation to model api variables. 1 These descriptions are processed during the simulator build and result in a datapool node

1 An API variable is a model variable that is marked in the Model Editor to be exported to the data dictionary.

c Airbus Defence and Space 75 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

in the dictionary containing the defined nodes and variables in the dictionary as well as the entrypoints to copy data from the variables in the model to their counterpart in the datapool and vice versa. If error injection is switched on for such copy in the model description the error injection variables that control this error injection will show up as well.

Figure 8.2: Datapool in the dictionary

The MDE also supports creation of user defined variables in the datapool. User defined variables are variables that do not have a relation with a model API variable. Typical use of user defined datapool variables is with EuroSim External Simulator Access, see Chapter 32. The user defined variables in the datapool are f.i. updated by an external client. Note that for an Object Oriented language user the datapool approach may be less useful as the OO language can differentiate much easier between internal and external variables and our OO APIs have a means for error injection in a more OO approach. When using C/Fortran however it is less obvious what the inputs and outputs are, in particular when the model is distributed over multiple files where API variables will show up as input or output because they are internally read and written, potentially by different files. Hence the Model Description Editor is most useful for C/Fortran users that want to integrate their models without any programming effort.

8.2 Starting the Model Description Editor

The Model Description Editor (MDE) can be started from the Model Editor. When the model tree contains a file with the appropriate extension (see Appendix A), then the MDE is automatically started when the Edit command is selected on the model description file node in the Model Editor or when the file is double clicked.

The MDE needs a data dictionary as input. When the MDE is started from the Model Editor, the Model Editor first runs the build process (make) in order to ensure that the data dictionary is up to date. This means that there may be some delay when starting the MDE if there are a lot of outstanding changes since the last build command was given. It is also possible to start the MDE directly from the Project Manager GUI by double clicking a model description file in the tree view, or to start the MDE from the commandline (type ModelDescriptionEditor).

76 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

8.3 Views in the Model Description Editor

The Model Description Editor features a single view in which the user constructs a leave of the datapool tree in the dictionary. The main functions that operate on the view are included in the Insert menu and are also conveniently available via the tool bar buttons and context sensitive menus that appear on a right click on tree nodes. The Model Description Editor tree view starts with an empty tree with root node ”datapool”. Below this root node the user can add models. A model description file can cover a single model or multiple models. This is entirely up to the user’s preference. The advantage of multiple files is that it is easier to re-use models in different simulator configurations. An example could be that the onboard software is first executed as a model in EuroSim and removed at a later stage when the onboard computer is connected as HIL In this case a split in two model description files could be usefull. It could also be argumented that every model should have its own model description file to allow each different model developer to maintain his own model description file. The choice is related to the needed flexibility in the project, weighed against the higher complexity of multiple files. Below the model node the user has the choice of creating an Input- or Output group, or an Entrypoint. In the introduction an approach has been taken where the user would choose an Input or Output group node. This is the leat complex approach that is based on a model oriented view on the dictionary. However, it is possible to make the variables in the datapool entrypoint specific in which case the Entrypoint node is created and below that the inputs and outputs are specified. This makes the variables in the datapool then entrypoint specific and constitutes a more function oriented view on the model. The latter approach is more complex and likely best avoided untill a specific need to differentiate the variables per entrypoint arises. Underneath the group (Input/Output/Entrypoint) the variables can be selected for input or output. Whether a variable is input or output in the datapool is determined solely at this point. The input- and output group division is required to deconflict variables that are both input- and output.

8.4 Objects in the Model Description Editor

In the Model Description Editor tree view the model description is created using a hierarchical tree structure. Elements in the tree are called nodes and have a specific function. In Figure 8.3 an example model description tree is shown.

c Airbus Defence and Space 77 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 8.3: Example model description tree

8.4.1 Root node Each model description has one root node. It represents the complete model description and it has the base name of the model description file. The root node can hold one or more Model nodes.

8.4.2 Model node Model nodes are used to structure the model description and will usually (but not necessarily) refer to the model(s) as specified in the Model Editor. Model nodes are children of the root node and can hold one or more entry point nodes.

8.4.3 Entry point node Entry point nodes are also used to structure the model description and refer to an entry point in the model code. Entry point nodes are children of a model node and can hold inputs and outputs group nodes. When you create a new entry point node, you are presented with a dialog box to select an entry point from the data dictionary.

8.4.4 Inputs and Outputs group nodes Inputs and Outputs group nodes are used to logically group the input and output variables of an entry point. Inputs and outputs group nodes are children of an entry point node. An inputs group node can hold input nodes and an outputs group node can hold output nodes.

78 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

8.4.5 Input and output nodes

Input and output nodes refer to API variables of the model code (i.e. variables in the data dictionary) or they are user defined (i.e. the node holds an ANSI-C variable declaration). Input and output nodes cannot have children, i.e. they are the leaves of the model description tree.

When you create a new input or output node, you are presented with a dialog box to select the API variable from the data dictionary or enter an ANSI-C variable declaration when defining a user defined variable. In the latter case, the name of the node is derived from the entered variable name.

8.5 Menu items

Note that most common commands are also available in context sensitive menus that pop-up when click- ing the right mouse button. Some commands also have keyboard short-cuts and are available via the tool bar.

8.5.1 File menu Select model Select the model file that will be used to get the data dictionary. The model file (and hence the data dictionary) defines which entry points and variables you can choose from in the dialogs when adding and entry point node or a variable node.

8.5.2 Edit menu Toggle Error Injection Toggle the error injection flag for the selected input and/or output nodes to enable error injection on the variables, see ??. Properties This pops up the the properties dialog box, see Figure 8.4, which is used to edit the properties of entry point, input and output nodes. Depending on the type of the node, some of the elements in the dialog box are shown.

Figure 8.4: Properties Dialog Box

The Name field contains the name of the entry point or variable. In case of a variable node, the fields Unit and Description are shown. The Unit defines the physical unit of the variable. The Description is the textual description of the variable. The Data Dictionary field allows you to

c Airbus Defence and Space 79 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

select the Dictionary path of an entry point or variable. In case of a variable two check boxes are available for User defined type and Error injection. If you check the User defined type box, the dictionary path field is changed to User defined variable declaration. That declaration must be a valid variable declaration in C syntax. The type can be any basic C type or array. If you check the error injection box the error injection function is enabled for that variable.

8.5.3 Insert menu Model Node Add a model node to the root node, see Section 8.4.2. Entry Point Node Add an entry point node to a model node, see Section 8.4.3. Inputs Group Node Add an inputs group node to an entry point node, see Section 8.4.4. Input Node Add an input node to an inputs group node, see Section 8.4.5. Outputs Group Node Add an outputs group node to an entry point node, see Section 8.4.4. Output Node Add an output node to an outputs group node, see Section 8.4.5

8.5.4 Tools menu Check Model Description for errors Checks the model description for any errors. The model description is also automatically checked on each save to disk. This feature can be disabled through the Tools:Preferences menu.

8.6 Error Injection

This section will illustrate the effect and usage of enabling error injection using the default error injector. The default error injection functionality has been established in the Gaia space program. In general this default error injection function will be sufficient for most users and then no programming is needed to inject errors in the data flow. However, in the Advanced section in this chapter it is shown how the default error injection functionality can be replaced. The default error injector forces the introduction of an error variable in the datapool with the same name as the variable on which the error is to be injected, extended with err. This variable is of a type struct which fields are the parameters of the default error injectin function. Through these fields the user can, at runtime, configure the error injection, for instance via an mdl script.

80 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 8.5: Default error injection

The example shows that there are 6 parameters that control the error injection:

• enable: Enable the error

• type: Type of the error,lock=1,linear=2,ramp=3,mask=4

• a: error function parameter

• b: error function parameter

• n: error function parameter

• reps: number of times the error is counted

Through these parameters the following type of errors (configured in the field type) can be injected for reps number of times:

• lock: y=a

• linear: y=a*x+b • ramp: if (n>0) y=(b-a)/n else b

• mask: y=(x & a) | b

• n: error function parameter

The default error injector can work on boolean (lock only), integer, unsigned integer and double variables, including arrays thereof.

8.7 Use case example

8.7.1 Model files

Suppose we have two sub-models modelA.c and modelB.c as listed below.

Listing 8.1: The C source code for the modelA file node #include static double x; static double y;

c Airbus Defence and Space 81 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

void calc_sin(void) { y = sin(x); }

82 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Listing 8.2: The C source code for the modelB file node static double counter; void update_counter(void) { counter = counter + 0.1; }

The complete source code, including the other files discussed in this section, can be found in the src subdirectory of the directory where EuroSim is installed. ModelA takes variable x as input to the sin function and stores the result in variable y. The entry point for the update of modelA is calc_sin. ModelB takes variable counter as input, increments it and writes the result back to the same variable. The entry point for the update of modelB is update_counter. When we want to use modelB to update the input variable of modelA, we would need to modify the source code of modelB to perform its update on variable x instead of using variable counter. We would also need to change modelA to remove the static keyword from variable x so that it can be accessed from modelB (global scope). When using the Simulator Integration Support library, we do not have to modify the source of the sub models as will be explained in the following sub-sections. Figure 8.6 shows a screen shot of what the Model Editor looks like with the two sub-models modelA and modelB. The sub-models have been parsed and check marks are placed in front of the entry points and variables that have to be available in the data dictionary.

Figure 8.6: Model Editor

8.7.2 Model Description file The philosophy behind the Model Description file is that each model has one or more input variables, one or more update functions (entry points) and one or more output variables. The Model Description Editor can be used to select the input and output variables and the entry points from the data dictionary and logically group them together, see for example the calc_sin node in Figure 8.7. This describes a model at a higher abstraction level even if the original model source code is rather unstructured or actually contains more than one sub-model. In the latter case, the Model Description file can be used to organize the model by defining multiple model nodes with entry points and variables that refer to a single

c Airbus Defence and Space 83 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

model source code file. Each model variable that is described as a variable in the Model Description file will be available for exchange with other variable(s). It is possible to add one or more Model Description file nodes to a model using the EuroSim Model Editor, see Section 7.3.4.3. When you select the Edit command on a Model Description file node in the Model Editor, the Model Description Editor will be started. After specifying which variables from the example models should be available for model to model ex- changes, the Model Description Editor looks like Figure 8.7. We have created two model nodes ModelA and ModelB that contain references to the entry points in the respective models. Since this is a very simple example, the screen shot shows an almost one to one copy of the original model tree in the Model Editor. Notice that the counter variable in the Model Description file has been duplicated to serve as an input variable as well as an output variable for ModelB.

Figure 8.7: Model Description Editor

8.7.3 Datapool Once you have finished editing a Model Description file, select the Tools:Build All menu command in the Model Editor, which generates the so called “datapool” in the dictionary (see also ??). The datapool contains the variables described in the Model Description file(s). It also contains automatically generated entry points to exchange the data between model variables and datapool variables, possibly with error injection when enabled. These entrypoints can be scheduled using the Schedule Editor just as normal user entrypoints. This setup then has to be completed with parameter exchange entrypoints that transfer data between the variables in the datapool to complete the process as depicted in Figure 8.1. These parameter exchange entrypoints can be generated using the Parameter Exchange Editor. Secion Chapter 9 describes the usage of the Parameter Exchange Editor including the continuation of this use case.

84 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

8.8 Advanced topics

8.8.1 Scheduling MDE entrypoints The automatically generated entry points must be called by the scheduler at the appropriate time steps, see Figure 8.8 for a very simple example of a datapool and model source code. At step 1 the automatically generated entry point takes care of copying the value of the X variable in the datapool to the X variable of the model code. Step 2 calls the actual entry point in the model to update the X variable. At last, step 3 copies the updated model variable X back to the datapool. This last step is also performed by automatically generated code. Use the Schedule Editor to specify when the generated entry points should be called. The generated entry points are also placed under the datapool node in the data dictionary. The names of the entry points are based on the names of the input and output group nodes.

Figure 8.8: Example of data transfer between datapool and model

The Model Description Editor leaves it up to the user to decide at what constitutes a model and whether step1 and step3 apply to a single or multiple entrypoints of the model. For instance if the above ex- ample would have had two entrypoints foo1 and foo2, the datapool could contain foo1/input/x, foo1/output/x and foo2/input/x, and foo2/output/x. The entrypoint is then viewed as a submodel by itself and it state must be stored in the datapool. The user would schedule the step1 and step3 around the execution of foo1, and a similar step4 and step6 around foo2. Conceptually the commu- nication between foo1 and foo2 if needed would pass through the datapool. This gives great flexibility and power in terms of timing, but can often be overcomplicating and surpassing the users goal. Alternatively the user can prefer to see the datapool reflecting the model. The model/input/x and = model/output/x are the counterparts in the datapool of the model variable x. Step1 and step3 transfer data from the datapool into the model and vice versa, but they don’t have the specific relation to the entrypoints foo1 and foo2. If in this approach there would be multiple variables, say x1 and x2, where x1 is only used by foo1 and x2 is only used by foo2, the step1 and step2 would have to transfer both x1 and x2. There is thus a trade-off between conceptual ease of use against performance and timing requirements.

8.8.2 Overriding the default error injection function The error injection function can be user defined through including error injection code in C. An example is shown in the listing below. #include #include #include static int enable_id; /* boolean */ static int counter_id; /* unsigned integer */ static int offset_id; /* integer */ static int history_id; /* double */ static esimErrInjDataValue_t error_injection_function(esimErrInj_t *error, esimErrInjDataValue_t input) { bool *enable;

c Airbus Defence and Space 85 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

unsigned int *counter; int *offset; double *history; esimErrInjDataValue_t output; double value; double prev_value;

int res;

res = esimErrInjGetBooleanValue(error, enable_id, &enable); assert(res == 0); /* illegal id, type mismatch */ res = esimErrInjGetUnsignedIntegerValue(error, counter_id, &counter); assert(res == 0); /* illegal id, type mismatch */ res = esimErrInjGetIntegerValue(error, offset_id, &offset); assert(res == 0); /* illegal id, type mismatch */ res = esimErrInjGetDoubleValue(error, history_id, &history); assert(res == 0); /* illegal id, type mismatch */

if (!*enable) { return input; }

if (*counter == 0) { return input; } (*counter)--;

switch (input.type) { case ESIM_ERROR_INJECTION_BOOLEAN: value = input.val_b; break; case ESIM_ERROR_INJECTION_INTEGER: value = input.val_i; break; case ESIM_ERROR_INJECTION_UNSIGNED_INTEGER: value = input.val_u; break; case ESIM_ERROR_INJECTION_DOUBLE: value = input.val_d; break; default: assert(0); }

prev_value = *history; *history = value;

value = prev_value + *offset;

output.type = input.type;

switch (input.type) { case ESIM_ERROR_INJECTION_BOOLEAN: output.val_b = value; break; case ESIM_ERROR_INJECTION_INTEGER: output.val_i = value; break; case ESIM_ERROR_INJECTION_UNSIGNED_INTEGER: output.val_u = value;

86 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

break; case ESIM_ERROR_INJECTION_DOUBLE: output.val_d = value; break; }

return output; } int userErrInjPublish(esimErrInjPublish_t *pub) { esimErrInjDataValue_t value;

value.type = ESIM_ERROR_INJECTION_BOOLEAN; value.val_b = false; enable_id = esimErrInjPublishParameter(pub, "enable", "enable error injection", NULL, value, false); if (enable_id == -1) return -1;

value.type = ESIM_ERROR_INJECTION_INTEGER; value.val_i = -10; offset_id = esimErrInjPublishParameter(pub, "offset", "offset to add to output value", "m", value, false); if (offset_id == -1) return -1;

value.type = ESIM_ERROR_INJECTION_UNSIGNED_INTEGER; value.val_u = 20; counter_id = esimErrInjPublishParameter(pub, "counter", "number of times to repeat error", NULL, value, false); if (counter_id == -1) return -1;

value.type = ESIM_ERROR_INJECTION_DOUBLE; value.val_d = 0.123e2; history_id = esimErrInjPublishParameter(pub, "history", "history of variable", NULL, value, true); if (history_id == -1) return -1;

esimErrInjPublishFunction(pub, error_injection_function); esimErrInjSetPostFix("_test_1_2_3_4"); return 0; }

The error injection function is called error_injection_function. The function must have this precise name in order to override the weak symbol name of the default injector. The function first retrieves

c Airbus Defence and Space 87 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

pointers to the error injection parameters. The pointers allow the user to modify the error injection parameter values. This example shows four parameters, one of each data type. The input value of the error injection function is modified to perform the error injection. The result is returned. The type of the result variable must always be identical to the type of the input variable. The error injection publication function must be called userErrInjPublish. The function is called at build time and at run time. At build time the publication is used in the process to generate the data dictionary. At run time it is used to pass the error injection function pointer and to retrieve the parameter id’s. The parameter id’s are needed to retrieve the pointers to the error injection parameters in the error injection function. More information can be found in the esimErrInj(3) manual page.

88 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 9

Parameter Exchange Editor reference

This chapter provides details on the Parameter Exchange Editor (PXE). The menu items that are specific to the PXE will be described in separate subsections. For menu items not described in this chapter, refer to Section 5.6.

9.1 Introduction

The PXE is a sub-editor of the Model Editor and allows the user to interconnect models by specifying the desired connections from model output variables to the input variables of other models. The generated specifications are taken along in the EuroSim build process to create entrypoints in the dictionary as well as in the simulator executable that perform a copy of a specified output variable to a specified input variable. Because models often exchange multiple variables, for example position and speed, a grouping of parameter exchanges is created in so called transfer groups.

Figure 9.1: Parameter Exchange design

The Parameter Exhange Editor explained in this chapter supports the definition of parameter exchange groups and their contained parameter exchanges. The result after a simulator build of such specification is shown in Figure 9.2.

c Airbus Defence and Space 89 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 9.2: Entrypoints from transfer

Shown in Figure 9.2 is that a parameter exchange group is transformed to an entrypoint with each in- dividual parameter exchange represented as child. Scheduling the group entrypoint will activate all the parameter exchange entrypoints in the order of the definition in the Parameter Exchange Editor. Alter- nativly if the order of exchanges is relevant it is possible to schedule the individual exchanges instead of the group parameter exchange entrypoint. Note that the Parameter Exchange Editor currently does not check types when creating a parameter exchange. The developer can now include these entrypoints in the schedule for precise timing of the parameter exchanges. The major benefit of the copy entrypoint approach is that it allows the models to be indepen- dent of each other and even run in parallel, except for the short timeframe where the copy is executed. Additionally the user can now graphically interconnect the models in a simulator without each model having knowlede of the interface of other models and without the need to write software. While integrating models by dataflow in this manner, the timing of such copy still needs to be specified and that is accomplished via the Schedule Editor. In the schedule a choice then has to be made whether to invoke the parameter exchange entrypoint to copy model inputs to a model prior to the model setp entrypoint execution or whether to follow a paradigm to distribute outputs after the model. The most common approach is the first, but its optional and sometimes mixed. Note that the parameter exchanges were also shown in the introduction of the Model Description Editor (MDE) (see Chapter 8). The parameter exchange completes the Model Description Editor with the capa- bility to exchange the parameter data between the variables in the datapool that is generated by the Model Description Editor. However, since EuroSim Mk7 the Parameter Exchange Editor is no longer limited to such datapool variables, it can operate between any variable in the EuroSim dictionary. This allows the PXE to specify the exchange of data between models expressed in any language, even between different languages. Parameter Exchange files from versions prior to EuroSim Mk7.1 can still be used and seen referring to the variables in the model description files (note the md preceding the variable path instead of var), however all new exchanges must follow the new parameter exchange approach. The result of the Model Description Editor is the creation of a datapool folder in the dictionary. The variables can be selected from this folder for usage in parameter descriptions rather then from the Model Description files. Subsequent sections in this chapter explain in detail the usage of the Parameter Exchange Editor

9.2 Starting the Parameter Exchange Editor

The Parameter Exchange Editor (PXE) is used from within the Model Editor. Because it requires the data dictionary, the Model Editor first will attempt to rebuild the dictionary if there are changed files. To get useful data in the Parameter Exchange Editor the build must be successful. The result of starting the Parameter Exchange Editor is shown in Figure 9.3)

90 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 9.3: Example of Parameter Exhange Editor usage

Alternatively, the (PXE) can be started by double clicking a parameter exchange file in the Project Man- ager or by typing ParameterExchangeEditor on the command line.

9.3 Views in the Parameter Exchange Editor

The Parameter Exchange Editor features three views from which items are selected as input to the Param- eter Exchange definition. The main functions to create such definitions are located in the Insert menu. These items are also available via the tool bar and context sensitve menus. The toolbar buttons are en- abled depending on whether the user selects the paramexchg root in the Exhanges view (allowing the creating of a group entry) or whether a group node is selected (allowing the creation of exchanges).

9.3.1 Source view

The Source pane in the PXE is a dictionary pane, with the abilities to filter for searching variables. In this pane the use can select the variable that provides the input to the parameter exchange.

9.3.2 Destination view

The Destination pane in the PXE shows also a dictionary pane, with the abilities to filter for searching variables. In this pane the use can select the variable that provides the storage that the parameter exchange copies the data into.

9.3.3 Exchange view The Exchanges pane shows the defined Parameter Exchange Groups and the Parameter Exchanges con- tained in those groups. An Exchange Group is an entrypoint that can be scheduled in the Schedule Editor. When activated the Exchange Group entrypoint performs the data exchanges that it contains. The root node of the Exchange group is named paramexchg, this is also the node where the parameter exchange group entrypoints can be found in the data dictionary as is visible in scheduling and simulation definition.

c Airbus Defence and Space 91 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

9.4 Objects in the Parameter Exchange Editor

The Source and Destination panes are read-only and show the contents of the data dictionary. For more information on the contained nodes, see Chapter 8. This section focusses on the Parameter Echange specific nodes that are constructed with the Parameter Exchange Editor as shown in Figure 9.4.

Figure 9.4: Example of parameter exchange definition

9.4.1 Exchange group node An exchange group is used to organize a logical group of exchanges for which the exchange (copy) of variables can be scheduled as one step. For each exchange group an entry point will be generated with the same name as the exchange group under the “paramexchg” node in the data dictionary. An exchange group node contains the actual exchange parameters.

9.4.2 Exchange parameter node An exchange parameter specifies which (output) variable from the dictionary should be copied to which (input) variable in the dictionary. Currently the Parameter Exhange Editor does not check if a variable is defined as input or output as quite often the user did not add such marking yet. The value of the output variable is copied to the specified input variable by an automatically generated entry point that has the name of the parameter exchange, which is wrapped inside an entrypoint that reflects the parameter exchange group which can activate all its children in a sequence. You must specify when to schedule this entry point using the EuroSim Schedule Editor. An exchange parameter is a child of an exchange group node and it cannot have children, i.e. it is the leaf of the parameter exchange tree.

9.5 Menu items

Note that most common commands are also available in context sensitive menus that pop-up when click- ing the right mouse button. Some commands also have keyboard short-cuts and are avialable via the tool bar.

9.5.1 File menu Select model Select the model file that will be used to get the data dictionary. The data dictionary is used to check if a parameter exchange is valid, i.e. it checks the type and size of the source and destination variable. This is only required when the PXE is started from outside the Model Editor.

92 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

9.5.2 Edit menu Exchange Update Update an exchange parameter with currently selected input and output variables in the desti- nation, source and optionally calibration views, respectively.

9.5.3 Insert menu Add Exchange Group Add a Parameter Exchange Group node to the root node in the Exchanges pane. This is the same as the tool bar button Exchange Group. The item is only enabled when the root node in the Exhanges pane is selected. The result of the action is an exchange group entrypoint that can be scheduled in the schedule editor. Add Exchange Parameter Add an exchange parameter to an exchange group node, see Section 9.4.2. You will be prompted with a dialog box to enter a name (a sensible default is provided). The name is purely infor- mational. In order to add an exchange parameter you must first select an output variable in the source view and an input variable in the destination view. Then select the appropriate exchange group and select the Add Exchange Parameter command in the Edit menu.

9.5.4 Tools menu Check Parameter Exchange for errors Checks the parameter exchange for any errors. The parameter exchange is also automatically checked on each save to disk. This feature can be disabled through the Tools:Preferences menu.

9.6 Use Case example

This use case example is the continuation of the use case example started in the Model Description Editor chapter Section 8.7. At the start of this use case it is assumed that a datapool is created as a result of processing the model description file and therefore the data pool now contains the input and output variables as well as the entrypoints for transferring the data between the model variables and the datapool variables. This section then illustrates the usage of parameter exchanges to transfer data between dictionary vari- ables. As this example is the continuation of the example that started with Model Desscriptions the parameter exchanges are used to exchange data between datapool variables. Note however that the Pa- rameter Exchange Editor in EuroSim Mk7.1 can transfer data between any two variables in the data dictionary, it is no longer limited to datapool variables as applicable in previous EuroSim versions. For a more extensive example we recommend trying ThermoSimInt. This example also uses Model Descriptions and Parameter exchanges to implement the default Thermo example in EuroSim.

9.6.1 Parameter Exchange file For our use case example a screen shot of the Parameter Exchange Editor looks like Figure 9.5. Each time the parameter exchange entry point is scheduled, the value of output variable counter of Mod- elB is copied to input variable x of ModelA. The parameter exchange entry point receives the same name as name the exchange group node. Thus, in our example the entry point will be available as “Model B to model A”.

c Airbus Defence and Space 93 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 9.5: Parameter Exchange Editor

When this file is in the file tree in the model editor and gets processed as part of the simulator build, a “paramexchg” folder is generated in the dictionary in which the parameter exchange entrypoints that result from the parameter exchange definition are displayed. Figure 9.6

94 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 9.6: Parameter Exchange Editor

The name of the entry point is the same as the name of the parameter exchange group node in the Param- eter Exchange file. Each parameter exchange group entrypoint can be expanded to show the individual parameter exhange entrypoints that it contains. Note that the Dictionary is shown in alphabetical order, hence the displayed list of individual parameter exchange entrypoints inside a group entry point does not reflect the order of transfer execution, but order is rarely relevant within the context of a parameter exchange group. The parameter exchange group entrypoints can now simply be scheduled to perform the list of data transfers. In exceptional cases with specific timing dependencies there is also the escape to schedule the transfers inside the parameter exchange group in case there is more then one, as these are entrypoints too. Task ModelA update contains three entry points:

• /datapool/SimIntExample/ModelA/input/set input variables

• /modelA/calc sin

• /datapool/SimIntExample/ModelA/output/set output variables

The first entry point is generated by the Model Editor build process when the Model Description file was read. It copies variable x from the datapool to variable x of model A (step 1 in Figure 9.7). The second entry point is the one from model A and uses variable x in model A to calculate the sine value and store the result in variable y (step 2). The last entry point is also generated and copies variable y from model A to variable y in the datapool (step 3).

c Airbus Defence and Space 95 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 9.7: Datapool exchanges and update for model A

Task ModelB update contains three entry points: • /datapool/SimIntExample/ModelB/input/set input variables • /modelB/update counter • /datapool/SimIntExample/ModelB/set output variables The first entry point is generated by the Model Editor build process when the Model Description file was read. It copies variable counter from the datapool to variable counter of model B (step 4 in Figure 9.8). The second entry point is the one from model B and uses variable counter in model B to increment itself (step 5). The last entry point is also generated and copies variable counter from model B to variable counter in the datapool (step 6).

Figure 9.8: Datapool exchanges and update for model B

Task ParameterExchange contains one entry point: • /paramexchg/Model A to Model B This entry point copies the updated counter output variable in the datapool to the counter input variable and the x input variable (step 7 in Figure 9.9). After this parameter exchange the schedule starts again at step 1. This time model A uses the updated x variable to perform its model update.

Figure 9.9: Parameter exchange

Note that in the above illustration the connections are made between variables in the dictionary (vari- ables in the transfer have prefix var). In earlier versions of EuroSim, the connection was made between variables identified in the Model Description Editor files (prefix filename.md in the parameter exchange editor). Connections on the basis of the Model Description (.md) are still supported, but new connections must be performed via the variables in the dictionary.

9.6.2 Concluding remarks During the use case example in the previous sub-sections and in Section 8.7 it has been demonstrated that we can integrate models without having to write or modify a single line of source code. Of course, in practice model source code may have to be modified in order to match variable types (in the example we used doubles for all variables).

96 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Note that the parameter exchanges determine the interconnection between the models to establish a simulator. To support alternative configurations in one simulator the user can create different schedule files that contain different entrypoints from the parameter exchange folder.

c Airbus Defence and Space 97 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

98 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 10

Calibration Editor reference

This chapter provides details on the Calibration Editor (CE). The menu items that are specific to the CE will be described in separate subsections. For menu items not described in this chapter, refer to Section 5.6.

10.1 Introduction

The use of the CE is optional, but you would typically use Calibration files when you need to interface with external hardware such as electrical front-ends. Calibration files serve as input to functions of the Calibration library. There are two methods in which Calibrations can be applied. First, the calibration library provides an Application Programmers Interface which allows the user to calibrate values based on a calibration curve that is defined using the Calibration Editor. The calibation library is described in detail in Chapter 21. Second, the calibrations can be automatically applied on a parameter exchange defined with the Param- eterExchange editor. In this case the calibration occurs automatically after copying of the value from the source and before writing it to the destination of the exchange. In this case there is no need for performing the calibrations in the code, but the calibration file should be included in the ModelEditor.

The CE can be used to create one or more Calibration files that describe the transformation from engi- neering values to raw values and vice versa. There are three types of calibration:

• polynomial equation

• interpolation

• lookup table

The polynomial equation is a continuous function of the format

y = ax4 + bx3 + cx2 + dx + e (10.1)

The constants a,b,c,d,e are coefficients which, when correctly chosen, approximate any correlation func- tion closely enough for the intended purpose. The interpolation method uses point pairs to create a continuous function by performing a linear interpo- lation between these points. The lookup table method creates a discrete correlation function using a lookup table to convert the input to the output value. If the input value is not present in the lookup table, an error condition is raised. (Thus similar to point pairs, but without linear interpolation).

c Airbus Defence and Space 99 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 10.1 shows the different calibration types in a plot:

Figure 10.1: Calibration types

The following restrictions are applicable to data elements in each curve:

• No duplicate In/Power/Index values

• The lookup table must contain at least one entry

• The polynom must have at least one coefficient

• The interpolation must have at least two point pairs

10.2 Starting the Calibration Editor

The Calibration Editor (CE) can be started either from the Model Editor, or by selecting the Calibration Editor button in the EuroSim start-up window (see Figure 6.1 as it may require enabling this button to become visible), or by typing calibrationEditor on the commandline. The preferred solution is to include the Calibration files in the ModelEditor, specifically if the Parame- terExchange files are also included in the model tree and calibration are applied on parameter exchanges. In this case the Calibration Editor can be started by double clicking the calibration file or execute it via the (context) menu items. If the Calibration files are not included in the ModelEditor, the calibration files must be included in the Simulation Controller to force their loading at the start of the simulation. If the files are included in the ModelEditor it is still allowed to also incude them in the Simulation Controller GUI for quick access to users of the Simulator. The result of starting the CalibrationEditor is shown in Figure 10.2:

100 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 10.2: Calibration Editor

10.3 Views in the Calibration Editor

The calibration Editor contains three views, which are elaborated in the following sections. Context sensitve menus and tool bar buttons provide easy access to the functions in the menus that operate on these views.

10.3.1 Calibration view The calibration pane provides an overview of the calibrations in the opened Calibration file.

10.3.2 Data rows view The table view shows the data for a single calibration curve in tabular form. Each row is a data point that defines the Calibration curve according to the selected curve type.

10.3.3 Graph view The graph view shows the data for a single calibration curve in a graphical form as a 2D curve.

10.4 Menu Items

Note that most common commands are also available in context sensitive menus that pop-up when click- ing the right mouse button. Some commands also have keyboard short-cuts and tool bar buttons.

10.4.1 Edit menu Delete Delete the selected rows in the currently active view. This can be either the Calibration view or the Data row view. Select All Select all rows of the currently active view.

c Airbus Defence and Space 101 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

10.4.2 Insert menu New Calibration... Add a new calibration curve. This will show a dialog box to enter the name, type and min/max values of the new calibration curve.

Figure 10.3: New Calibration dialog box

Add Data Row Add a new data row to the currently active calibration curve. Rename Rename/start editing the first column of the row which has focus.

102 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 11

Schedule Editor reference

This chapter provides details on the Schedule Editor. The various items which can be placed on the schedule tab pages, all menu items of the editor and their options are described. For menu items not described in this chapter, refer to Section 5.6.

11.1 Starting the Schedule Editor

The Schedule Editor can be started by selecting the ‘Schedule Editor’ button in the Project Manager window or by choosing the Tools:Schedule Editor menu item. If no schedule file is selected in the Project Manager tree view, the Schedule Editor starts with a new schedule. It is recommended to use a filename of the form modelname.sched. The Schedule Editor can also be started by double clicking a schedule file in the ‘Files’ list of the Project Manager. When creating a new schedule, the Schedule Editor automatically uses the name of the model file that is currently selected in the Project Manager.

Figure 11.1: Schedule Editor window

11.2 Schedule Editor items

In the Schedule Editor tab pages, a schedule can be created by positioning schedule items (tasks, mu- tual exclusions, frequency changers, internal and external events, output events, timers) and connecting them with flows. A schedule is a set of attributed tasks, timers, scheduling events and their respective dependencies. The overall behavior of a schedule is deterministic, whereas that of a single task need not be.

c Airbus Defence and Space 103 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

When an item is placed in the tab page, it is given some default values for the properties of the item. These can be changed by double-clicking the item, or by selecting the item and activating the menu item Edit:Properties (or pressing Alt-Enter on the keyboard). When the item is shown in a color other than yellow, there is an error for the item. The error message can be viewed alongside the properties of the item. For a list of possible error messages, refer to Appendix E. Items in the tab page can be repositioned by selecting the item with the left mouse button and, whilst holding the button pressed down, moving the item to another location on the tab page. All flows to and from the item will remain connected. Labels can also be repositioned in the same way. This allows you to move the label out of the way if a flow passes through the label. The position of the label remains relative to the item it belongs to. In the next sections, each of the items is described, together with the properties which can be modified. The graphic representation of the item in the tab page of the Schedule Editor is shown on the left.

11.2.1 Tasks A task item represents a list of one or more entry points. Each task represents a single execution unit during the simulation. Grouping entry points within a task will ensure that the operations (represented by the entry points) are executed sequentially. In a schedule, tasks can be activated by: • a simulator execution state transition (STATE ENTRY connector on entering and STATE EXIT connector on leaving a state) • completion of another task • periodically, using a timer which triggers the task at a given frequency • through an input connector that is triggered from an operation that has ended execution • a frequency changer Tasks have an AND relation on their input flows. Only after all connected inputs have been activated will the task become active.

Figure 11.2: Task dialog

104 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The following properties can be modified in the Edit Task Properties window (see Figure 11.2): Entry Points This list shows all entry points that are associated with the task. The ‘Data Dictionary’ list contains all known entry points, the ‘Entry Points’ list shows the entry points selected for the current task. The list can be modified by pressing the buttons in-between the two listboxes. An entry point can be copied from the ‘Data Dictionary’ list to the ‘Entry Points’ list (right arrow), or removed from the task list (the ‘Delete’ button). The up and down arrow buttons can be used to re-order the entry points. For editing the entry point list a model file should be selected, so a data dictionary will be loaded into memory (see also Section 11.3.1): the data dictionary file of the model must have been build, otherwise the list will be empty and no entry points can be selected.

Note that the ‘Data Dictionary’ list is a Dictionary Browser (see Section 5.7). In this case the functionality to search and filter is not visible, as searching the entrypoints is not suported.

Timing information for the selected entry point is shown next to the ‘Entry Points’ list. Timing information can be modified by clicking on the entry point timing values. Timing information can also be imported into the scheduler using the File:Import timings. . . menu item. The latter is only possible if you have already performed a simulation run with this schedule, which produces the timings file.

Beneath the entry point values the total timings for the current task are displayed. Entry points in a task are executed sequentially, so the timing information is calculated by adding the values for the individual entry points in the task. Taskname The name of the task. Processor The processor on which the task should be executed. The default is ‘Any’.

Priority The priority with which the task should run. Default is ‘Moderate’. Preemptable Set this to ‘No’ if the task may not be interrupted by another task. Allowed Execution The maximum allowed task execution in milliseconds, with microsecond resolution. The ex- ecution time is the total time that the CPU was actively used, this excludes any blocking or preemption. The allowed execution is checked after task completion and results in a warning in the EuroSim journal when the set value is exceeded. By default the execution time is unchecked (zero). The allowed execution is often used to guard a budget assigned to a developer of the contained entrypoints. Allowed Duration The maximum allowed task duration in milliseconds, with microsecond resolution. The dura- tion is the total time from the moment the time becomes runnable (is inserted in the task queue) upt to completion and thus includes blocking and preemption. The duration is checked after task completion and results in a warning in the EuroSim journal when exceeded. By default the duration is unchecked (zero). For Periodic tasks the maximum is the tasks’ input period. For Non Periodic tasks the maximum is unlimited. The allowed duration is often used in debug- ging the timing in a simulator. When a task is consuming more time then expected it may not yet violate a deadline, but it may cause successive tasks to do so. The statistics are usefull in finding which task is using more time then expected but the allowed duration can flag the exact occurence with simulation time and wallclock time of such violation.

c Airbus Defence and Space 105 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Deadline The time period after which the task must have finished. The deadline is relative to the start of task insertion in the taskpool and can be specified with a ’basic cycle’ period resolution. For Periodic tasks the default and maximum deadline values are equal to the tasks’ input period. For Non Periodic tasks the deadline is unchecked by default. The maximum is the main cycle period. As soon as a deadline is exceeded a real-time error is raised and the scheduler inserts basic cycles until the task finishes (in the ’Executing’ state this means the Simulation time is effectively halted).

The time for the Deadline) is in multiples of the basic clock cycle (see Figure 11.8) as the deadline check is performed by the master clock of the scheduler. Task statistics are shown in the window below the entry points: Executing The time that the code in the entry points was actually consuming cpu cycles. Blocked The time between task insertion (runnable) and start of execution. Preempted The time the task was preempted by a higher priority task.

Active The time the task started its execution up to completion (includes preemption). Duration The total time from insertion to completion (includes blocking and preemption).

Offset The start of execution measured from the start of the current cycle. Finished The end of execution measured from the start of the current cycle (Offset + Duration).

The last item, Error, shows the status of the item. Initially the status is blank as the entrypoints all have a min,mean and max of zero. When data is read from the timings file, the items are showing status measured. As soon as the user overrides a max value of an entrypoint, the status switches to estimated.

11.2.2 Non real-time tasks Non real-time tasks are the links between the real-time domain and the non real-time domain. A non- real-time task can be raised by a completed task, by an internal event or by an external event. When the schedule is executed by the scheduler, all tasks (seen as a set of entry points) connected to a non real-time task will be executed in the non-real time domain. For each activation of the non real-time task this will be done once, unless the buffer overflows because tasks in the non-real time domain can not be executed fast enough. Non-real-time tasks have an OR relation on their input flows. As soon as one of the connected inputs has fired, the non-real-time task is activated. If an AND relation is needed, this can be easily created by inserting a real-time task between the connected input items and the non-real-time tasks. The real-time task then assures the AND relation on the input flows, and subsequently activates its output flow to the non-real-time task.

106 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 11.3: Non Real-time Task Dialog

The following properties can be modified in the properties dialog (see Figure 11.3) Entry Points This field indicates the entry points that will be triggered by this non real-time task. This list can be modified just like real-time tasks (see Section 11.2.1). Taskname The name of the non real-time task. Buffer Capacity This indicates the buffering capacity of the non real-time task.

As for the Task dialog the Non Realtime task dialog can display timings. The max field of entrypoint can be set, switching the status to estimated, or measurements can be read from file using the File::import timings menu item, which will switch the status of the entrypoints to measured. Below the entrypoints are a list of task statistics displayed. These statistics initially have no status, but will switch to estimated when the user manually sets the max field of an entrypoint. The values are then calculated based on the user’s estimate. If a timings file was imported the status will switch to measured and display actual values. See the Task dialog description in section 11.2.1 for more details. The Period field is inherited from the schedule. Timingsfile shows the selected timingsfile. Error shows the status of the non real-time task.

11.2.3 Mutual exclusions Mutual exclusions are used for asynchronous stores. Independently of the direction of a connected flow, only one task (of those connected to the store) will be executed at a time. The sequence of execution is done on a first-come first-serve basis.

c Airbus Defence and Space 107 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 11.4: Mutual Exclusion Dialog

The following properties are shown in the properties window (see Figure 11.4): Tasks This list shows all tasks currently connected to the mutual exclusion. Shared Task Variables The Shared Task variables box shows a list of the variables that are shared by the listed task(s). The last item, Error, shows the status of the item.

11.2.4 Frequency changers Frequency changers, or synchronous stores, are used for multiple frequency dependencies, meaning that they transform the frequency of the incoming triggers into the store to another frequency going out of the store. Only one input connector is allowed for a frequency changer.

Figure 11.5: Frequency Change Dialog

The following properties can be modified in the properties window (see Figure 11.5): Input Ratio and Output Ratio show the ratio between the input and output frequencies. Only M:1 or 1:N ratios are allowed. An 1:N store (e.g. 10Hz/50Hz) means that upon activation of the frequency changer the output flows of the store are activated N times (5 in the example) directly one after another. To achieve a more regular task activation (50 Hz in the example), the task after the output flow should also be connected to a 50Hz timer. An M:1 store will activate the output flow only once every M input activations. Offset The delay of the output activation in milliseconds. Only valid for M:1 ratios. It must be a multiple of the basic clock cycle (see Section 11.4.7). A value of zero (0) means that the output will be activated on the first input activation. The default activates the output after M input activations.

Note that the output side of the synchronous store runs mutually exclusive with the input side. See also Section 11.4.3 and Section 11.4.4. The Output Frequency and Output Period are updated when the ratio changes. The last item, Error, shows the status of the item.

108 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

11.2.5 Internal and External events Internal and external events, both input connectors, represent events in the non-real time domain. An input connector activates its output flow when the event occurs. This may in turn execute a task or activate an output event. An internal event represents a predefined event related to simulator state changes and real-time errors. An external event is an event explicitly raised by the user from an MDL script or by an external event handler.

Figure 11.6: Input Connector Dialog

The following properties can be modified in the properties window (see Figure 11.6):

Name The name of the input connector. Predefined events cannot be renamed, only user defined input events can be renamed. The name must be unique. Capacity This indicates the buffering capacity of the connector. Raised by This indicates the sources of the event. An event can be raised internally by model code, a script or the event connection. An event can also be raised by an External Event Handler, e.g. a handler connected to a HW device or a signal handler (see Section 11.3.5: external event handler).

Error shows the status of the item.

11.2.6 Output events An output connector can be raised by a completed task or by an input connector. It represents an event related to simulator state changes and scheduler mode switches. A user defined output event activates the user defined input event that matches its name. Output connectors have an OR relation on their input flows. As soon as one of the connected inputs have fired, the output connector will raise the output event. If an AND relation is needed, this can be easily created by inserting a real-time task between the connected input items and the output connector. The real-time task then assures the AND relation on the input flows, and subsequently activates its output flow to the output connector to raise its event. No properties can be modified. Only user defined output events can be renamed.

11.2.7 Timers Timers activate their output at the specified frequency and can be used to activate f.i. tasks. The max- imum allowed frequency can be defined in the Schedule Configuration tool (see Section 11.3.5). The system uses 100 Hz as default value.

c Airbus Defence and Space 109 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 11.7: Timer Dialog

The following properties can be modified in the properties dialog (see Figure 11.7): Frequency and Period Use either of these to set the frequency of the timer. If one is modified, the other is updated au- tomatically. The maximum and default frequency is 100 Hz (Linux, Windows). The frequency range allowed is 0.001 Hz up to and including the maximum frequency, with a step 0.001 Hz.

Offset The delay of the output activation in milliseconds. This must be a multiple of the basic period (see Section 11.4.7).

Error shows the status of the timer.

11.2.8 Flows Flows are used to connect items in the schedule. They represent triggers going from one item to another.

11.3 Menu options

11.3.1 File menu Select Model With this option, a different model file can be selected from a file selection window. If the model does not have a data dictionary built, then it is not possible to specify entry points for tasks and non real-time tasks. Parameter Exchange files Opens a dialog to view, add or remove Parameter Exchange files for the current schedule, see Chapter 9 on how to create parameter exchange files. Import timings With this option, a timings file can be imported into the schedule. A file selection window will be shown in which a file can be selected. Timings files are generated automatically by the simulator and importing one will overwrite any manually entered timing settings.

11.3.2 Edit menu Rename Opens an in-place line edit to rename the currently selected item. Properties Pop up a dialog in which the properties of the currently selected node can be edited. The same effect can be reached by double clicking on an item in the schedule tab page.

11.3.3 View menu In this menu, the state whose schedule tab page should be raised to the top can be chosen. There are four possible states: Initializing, Standby, Executing and Exit.

110 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Enlarge drawing area Enlarges the drawing area so that more items can be placed. Note that printing the drawing area will resize it to fit all items on one page. Shrink drawing area Shrinks the drawing area.

Refresh Reads in the new data dictionary that is associated with the currently selected model. This option is useful if you have an instance of the Model Editor open and update the model - and data dictionary by building it - while you are also editing the schedule.

11.3.4 Insert menu In this menu, an item can be found for each of the items described in Section 11.2. For the internal events and output events, a cascading sub menu is available, from which various predefined internal and output events can be selected. For an explanation of the predefined events, see Section 11.3.4.2 and Section 11.3.4.3. When an item has been selected from this menu, the cursor will change to the selected item, after which the item can be positioned on the tab page. If a flow is chosen, click on the item from which the flow should go, keep the left mouse button pressed, move to the target item and release the mouse button.

11.3.4.1 External events External event handlers that are of type ’automatic’ automatically add their input connector to this menu. See Figure 11.3.5 on how to create an external event handler.

11.3.4.2 Predefined internal events The following internal events are predefined: NOTICE This event is raised when the esimMessage() or esimReport() with the esimSeverity param- eter set to esimSevMessage is called. WARNING Idem for a warning.

ERROR Idem for an error.

FATAL Idem for a fatal message. STATE ENTRY This event is raised when the state is first entered. STATE EXIT This event is raised when the state is exited. Beware that the task connected to this connector is executed in the new state. REAL TIME ERROR This event is raised in case of a real-time error. REAL TIME MODE ENTRY This event is raised at the transition to real-time mode, and at STATE ENTRY when in real-time mode. NON REAL TIME MODE ENTRY This event is raised at the transition to non real-time mode, and at STATE ENTRY when in non real-time mode.

c Airbus Defence and Space 111 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

SNAPSHOT END This event is raised after loading a snapshot and applying the values to the variables. Restoring a snapshot is performed asynchronous. This means that when the user issues the command, the snapshot is not applied when the command finishes. Instead this event is raised to indicate that it has finished.

11.3.4.3 Predefined output events The following output events are predefined:

INIT Requests transition from ‘Unconfigured’ to the ‘Initializing’ state.

GO Requests transition from ‘Standby’ to the ‘Executing’ state.

RESET System reset. Requests transition from ‘Standby’ to the ‘Initializing’ state.

PAUSE Requests transition from ‘Executing’ to the ‘Standby’ state.

ABORT System abort. Requests transition from ‘Standby’ or ‘Executing’ to the ‘Unconfigured’ state.

STOP Request transition from ‘Standby’ to the ‘Exiting’ state.

QUIT Requests transition from ‘Exiting’ to the ‘Unconfigured’ state. REAL TIME MODE Requests transition to the real-time mode. NON REAL TIME MODE Requests transition to the non real-time mode.

11.3.5 Tools menu Schedule Configuration. . . This menu item will show the Schedule Configuration dialog (see Figure 11.8).

Figure 11.8: Schedule Configuration Dialog

In this dialog, the following properties of the schedule can be set:

Type This determines which clock is used by the scheduler. The availability of clocks de- pends on the selected model and target platform (see Section 11.4.9). Sync When enabled, the startup process will include a synchronization effort such that the start of the simulator (the Simulator Started message in the journal) takes place on the next round second or neat to that if such is not possible due to the chosen frequency. The benefit is that the initial phase of subsequent simulations is better comparable,

112 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

hence the default is to be enabled. For most clock this initial synchronization pro- cess consumes signals or interrupts until the boundary is achieved and can take some seconds with a timout maximum of 20. For the plugin and Irig-B clocks the synchro- nisation to an external pulse can be programmed by the simulator developer. Period / Frequency The desired period or frequency at which the scheduler should operate. The default is 100 Hz, but this can be raised up to 1000 Hz, depending on the clock type. The requested frequency is converted to a period in milliseconds. This period is used as the basis to calculate simulation time, so round numbers are in favour. Note that on some platforms it is possible to specify external clock sources. In that case it is important that you specify the right frequency for correct simulation time calculation. Real time The number of processors to be allocated to the scheduler. The maximum number of real-time processors is 10. The default value is 3 processors. Number of Action Managers The number of action managers which can be explicitly scheduled in each simulator state. The default value is 1. External Event Handlers. . . This menu item will show the list of External Event Handlers (see Figure 11.9). Here Exter- nal Event Handlers can be added, deleted or modified. The user has to specify the processor that handles the external event. With ’exclusive’ use of the specified processor, the scheduler excludes the processor from the ’any’ pool for task execution1. Event handlers that have an ’au- tomatic’ handler type, automatically add an input connector to the Insert:External event menu (see Section 11.3.4.1). The external event gets the same name as the event handler. Event han- dlers of handler type ’user defined’, need additional code to handle the event and optionally raise one or more user defined input connectors, see Section 28.3.

Figure 11.9: External Event Handler Dialog

Intersection. . . This item will show the Intersection dialog (see Figure 11.10). The Intersection window shows all variables that are shared by all the selected tasks. This way, it is easy to see if there are any (possibly unwanted) interactions between tasks.

1 This setting has no meaning on single CPU machines.

c Airbus Defence and Space 113 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 11.10: Intersection Dialog

CPU load. . . The fields of this window show the processor load for each of the processors per state of the schedule (see Figure 11.11). The processor load is calculated using the mean duration (exe- cution) fields of the tasks. Timings for tasks assigned to ‘Any’ processor are split among all processors. If any of the processors has a load of more than 50%, this will result in a non- feasible schedule.

Figure 11.11: CPU Load Dialog

11.4 Advanced Scheduler topics

In this section some examples are given that will give more information on mutual exclusion behavior, the activation of user tasks according to mutual exclusions, dependencies, perform- ing I/O in the non-real time domain, time requirements, how the scheduler will handle state transitions between different simulation states, and how to schedule the ActionMgr.

11.4.1 Scheduler mutual exclusion behavior

11.4.1.1 Effect of mutual exclusions

A mutual exclusion, or asynchronous store, in the Schedule Editor represents a ‘mutual ex- clusive’ run-time behavior between tasks. The task that captures the store first is allowed to continue running while all other tasks that are attached to that store, are prevented from starting until the store becomes available again (only one task can capture the store at any one time).

11.4.1.2 Effect of task priorities

Using priorities on tasks implies that when the task with the lowest priority is running and a task with a higher priority is activated, the task with the highest priority will preempt the lower priority task when that lower task is preemptable and no other processor is available.

114 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Thus in the case that two tasks are connected to a mutual exclusion, using a higher priority for a task does not imply that that task will capture the mutual exclusion first, as it is the starting time that is of importance. If such a dependency is required, then it can be better specified using the following construction:

1Hz/0ms 1Hz/0ms 1Hz/0ms

prio highA B prio low A B

Wrong approach Correct approach

Note that even in the example above the starting time is never exactly the same, one of A or B will start slightly earlier than the other (the difference might be in nanoseconds). Which one in this case runs first depends on system internal behavior.

11.4.2 Dependencies, stores and frequency changers

Dependencies, stores and frequency changers are used to define a sequence of tasks. Suppose that we have the following schedule:

freq=200Hz freq=100Hz offs=0ms offs=0ms

A B

freq=50Hz freq=200Hz offs=0ms offs=0ms

C D

With this schedule it is defined that task A and D must be activated each 5 ms, task B must be activated each 10 ms, and task C must be activated each 20 ms. The maximum frequency on which the scheduler can activate tasks is for all states default 200 Hz. This means that the “real-time” is split up in time slots of 5 ms. For the example, the scheduler will activate tasks A and D in slot 1,2,3,. . . , task B in slot 2,4,6,. . . , and task C in slot 4,8,12,. . .

In the previous example, the sequence of tasks within the slots, is not defined. To define the sequence between tasks within the slots, dependencies (between tasks with the same frequency) and frequency changers (for tasks with different frequencies) can be used. In the following example the sequence of tasks within the time slots is defined with dependencies and frequency changers.

freq=200Hz D B C offs=0ms

A 200/100 100/50

c Airbus Defence and Space 115 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Note that the frequency of task D is still 200Hz, the frequency of task B is still 100Hz and the frequency of task C still 50Hz. These frequencies are now defined in the output frequency of the frequency changer. With these frequency changers it is defined that the time slots and sequences of tasks, within these slots, will be:

In the previous example we used frequency changers to define the sequences of tasks. With the defined sequence it is implicitly defined that tasks do not run simultaneous. If we do not want to define a sequence, but we only want to define that tasks are not executing simultaneous, we can use mutual exclusions. Tasks that read or write from the same mutual exclusion, are never executed by the scheduler simultaneous. For example, if we have a “printing” task that prints the contents of a linked list on 50 Hz, and a “updating” task that is changing the list at 200 Hz. It is obvious that the updating task may not run simultaneous with the printing task. To solve this problem, we can use a frequency changer.

freq=200Hz freq=50Hz offs=0ms offs=0ms

Update Print List List

List

11.4.3 Frequency changers and mutual exclusive execution of tasks

The frequency changer takes care of mutual exclusive execution of the tasks that write to it with the tasks that read from it. In case of a N:1 frequency store, this can severely limit the allowed execution time of the reading tasks. This is explained using the drawing below:

5Hz/0ms

A AET=200ms

5Hz/1Hz

B C

In this figure, the frequency changer must guarantee that task A will run mutual exclusive with tasks B and C. The allowed execution time of task A is limited to a maximum of 200 msec as a consequence of the frequency of 5Hz.

After 5 activations of Sync Store, the store will activate tasks B and C, before releasing task A for the next activation. However, task A must be released in 200msec (its AET), or else it will cause real-time errors. The total allowed execution time of the combination of task B and task C is therefore limited to a maximum of 200msec. In practice, the duration of task A will be larger than zero, which further reduces the allowed execution time of B+C.

If the execution of B+C is more than allowed, a solution might be to store the part of the code that needs the mutual exclusive behavior in a separate task. For instance:

116 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

5Hz/0ms

A AET=200ms

5Hz/1Hz

D E

B C

The part of the code of B and C that needs to be executed mutually exclusive with A (because it accesses the same variables) is stored in D and E. The remaining code is still in tasks B and C.

Now only the code in D and E must have a combined duration that is smaller than 200msec.

Note: D and E do not run mutually exclusive. If that is required, this can be accomplished by connecting these two tasks to a mutual exclusion (see Section 11.3), or even simpler by combining the code contained in D and C in one task.

11.4.4 Timing the output frequency of a frequency changer

Although a frequency changer has an output frequency, tasks reading from a frequency changer will only be activated with a frequency that approximates the specified output frequency. If more accuracy is desired, the frequency of the activations can be made exactly the one specified in the output frequency of the frequency changer by adding a timer. This is explained in the figure below:

1Hz/0ms

A

1Hz/5Hz

5Hz/0ms

B

C

Without the 5Hz timer, B is activated 5 times in rapid succession after each activation of A. Therefore the frequency of B would not be exactly 5 Hz, but would be determined by the execution duration of B. This is sufficient if only the ratio between A and B is of importance. However if it is required that B must be executed with an exact frequency of 5Hz, then the 5Hz timer should be added, which forces B to wait 200msec between the successive executions of B. The advantage of not adding a timer is that execution time is more efficiently used.

11.4.5 Example of using an output connector for I/O

I/O is non-deterministic in time and thus calls must be issued from the non-real-time domain. In the Schedule Editor this can be achieved by connecting the task that performs the I/O to an output-connector. There are two ways to synchronize your non-real-time tasks with the real- time tasks:

c Airbus Defence and Space 117 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

1. You can synchronize explicitly in the Schedule Editor, using the schedule items available 2. You can use a ‘flag’ variable in memory to pass the status information about the I/O.

Both are explained below:

11.4.5.1 Using Schedule Editor items for synchronization

The following figure explains the first approach.

A

C D B

Task A performs some action. When finished, the non real-time task D is activated which performs the task D containing entry points that do the I/O actions. Within task D, when it has performed its I/O actions, a call to the function esimRaiseEvent is made (in this case with argument “C”). This function call activates the Input Connector C which in turn will activate Task Item B. Data read by task D can now be used by task B.

11.4.5.2 Using a variable for synchronization

Approach 1 implies that D is activated each time A was activated. Using a synchronous store a relation can be established (like for every N times A was activated D is activated once). You may want a more parallel behavior where tasks A and D run in parallel, and A uses the data read by D when available. This is described below:

A

C

D

When task A needs to perform I/O, it sets a variable (e.g. io_request) and activates the input connector C by calling esimRaiseEvent(C). Task A keeps on running.

The activation of C will cause an activation of D. Task D connected to non real-time task D will perform its I/O and will set a variable (for instance io_handled) when the I/O operation is ready.

While running, task A scans variable io_handled to verify if I/O has completed. When it detects that this variable has been set, both io variables can be reset, and data read in the I/O action can be used.

Note that, within this approach, it is also possible to activate input-connector C from a MDL script instead of a task. Using this feature, D can be activated from the Simulation Controller.

118 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

11.4.6 State transitions

A state transition can only occur at a main cycle boundary. A main cycle has a period equal to the least common multiple (LCM) of the periodic tasks computed over all states of the simulator in the schedule. In the current implementation, the main cycle is taken as the LCM of the periods of all periodic tasks (over all states), instead of the LCM of the periods of active tasks in the current running state. This, for reasons of simplicity, is still correct, although it may make the main cycle somewhat larger than strictly necessary.

In the previous example we had a main cycle “AD:ADB:AD:ADBC”of 20 ms duration. This means that state transitions can only occur at each “4 slots” boundary. For this reason the scheduler will delay the user’s state transition request until the end of slot 4, 8, 12, . . . etc.

NB. If in the period between the request and the transition more state requests are given, these requests are buffered by the scheduler (up to 32) and applied on FIFO basis at the next main cycle boundaries, with one at a time.

11.4.7 Offsets

Offsets are used to “delay” tasks to following time slots. Suppose we have the following sched- ule:

freq=20Hz freq=20Hz offs=0ms offs=10ms

A B

The 10 ms offset of timer B will delay all activations of task B by 10 ms.

When offsets are used, state transitions will still be on the main cycle boundaries. This means that task B must still be activated (according to the current executing schedule), in the first two slots of the new state. This guarantees that the number of activations for each tasks are always the same. I.e. a functional model will always complete leaving the system in a deterministic state.

Note that no synchronization whatsoever is performed between the schedules in the ‘old’ and ‘new’ state: this is omitted under the assumption that there is only one nontrivial EuroSim

c Airbus Defence and Space 119 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

state (state EXECUTING), and that any other state is to perform simple procedures, such as initialization or keeping hardware alive. Supporting state synchronization would unnecessarily add to the complexity of the scheduler. The user must however be aware of a possible overlap in execution of the schedules of two states ‘just after’ a state transition when offsets are used.

Note: One exception is made for the transition to ABORT. An abort transition does not wait until the main cycle boundary, but is directly done by the scheduler. This means that all tasks, inclusive tasks with an offset, are directly stopped.

11.4.8 Scheduling the action manager (ACTION MGR)

The action manager is a special task provided by the EuroSim environment. Although it is a special task, the action manager must be scheduled just as any normal task. As with any normal task, how it is scheduled is of importance to its performance. For instance, if variables are to be logged just after performing a certain task, then the action manager could best be scheduled after this task using a flow (dependency relation).

When the action manager is not scheduled explicitly, i.e. not placed on the tab page in the Schedule Editor, the action manager is added to the schedule with a default frequency that is equal to the Basic Frequency of the scheduler and with a priority of Low. In many cases this will be sufficient, as this will activate the action manager with a high frequency, and after all other tasks have been activated.

However, there are cases where the action manager should be scheduled more carefully using the Schedule Editor. One such case has already been mentioned: to provide logging of variables on a specific moment in the overall schedule. Another example is the case in which only one real-time executor is available on which a low frequency task with long duration is running. Due to its long duration some time slots are filled completely, leaving no time to run the action manager. In this case the default Low priority will lead to real-time errors. Scheduling the action manager in the Schedule Editor with a higher priority may be the solution. This is illustrated below:

11.4.8.1 Multiple action managers

There are situations where a single action manager does not allow you to execute the actions at the appropriate place in the schedule. For that situation it is possible to specify more than one action manager task. The number of action managers can be configured in the Schedule Configuration dialog box (see Section 11.3.5).

Each action manager can be scheduled individually at different frequencies in each scheduler state.

120 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

When there is only a single action manager it has the name ACTION MGR. In the case when there is more than one action manager, the names are ACTION MGR 0, ACTION MGR 1, etc. The number corresponds to the action manager number you can specify for each individual action in the script dialog box in the Simulation Controller (see Section 12.10.3.1).

Messages printed by actions are labeled with the name of the action manager that executes them. The label has the form of actionmgrn, where n is the number of the action manager.

11.4.9 Clock types

Depending on the platform the simulator will be running on, the developer can choose from a number of clock types (or clock ’sources’) to drive the Scheduler. The type of clock to be used can be configured in the Schedule Editor (see Section 11.3.5). Note that for all external clock sources it is important that you specify the right frequency/period for correct simulation time calculation. The Scheduler will receive the heartbeat and assume that it in between the amount of time specified by the period will have passed. Additionally you can specifify if you want on startup a synchronisation to a pulse per second, or round second boundary.

The following clock types are available on Linux: Internal Represents the internal clock of the computer running the simulation. Plugin The clock that is glued via the plugin library identified with the library path in the selection dialog. IRIG-B The IRIG-B clock related to the option in the Model Editor. Note that the new clock plugin solution is prefered, this option will likely become deprecated with EuroSim [6]. Posix Signal Signals in the range RTMIN to RTMAX can be routed to the EuroSim master clock to drive the scheduler. Beware that with synchronisation on startup enabled, your signals will initially be consumed by the synchronisation process. RCIM clock Concurrent iHawk only. Selecting this clock will read the time from the RCIM card, allowing GPS and RCIM chain synchronized clocks. The device path will show /dev/rcim. Press Browse to select one of the rcim clock devices in the /dev/rcim subdirectory. The clock devices are named rtcN. RCIM interrupt Concurrent iHawk only. Ticking the EuroSim clock on the basis of the external inter- rupt input on the RCIM card. The device path will show /dev/rcim. Press Browse to select one of the rcim external interrupt devices in the /dev/rcim subdirectory. The interrupt devices are named etiN. EuroSim Compatible Device Type 1 Cicking the EuroSim clock on the basis of a EuroSim Compatible driver of type 1. These devices provide specific ioctl functions which EuroSim uses to wait for inter- rupts.See the External Hardware interface chapter on how to make a driver EuroSim compatible.The plugin is preferred, this option is however still available.

c Airbus Defence and Space 121 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

122 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 12

Simulation Controller reference

This chapter provides details on the Simulation Controller. The panes and tab pages of the editor, the various objects that can be created, all menu items of the editor and their options are described. For menu items not described in this chapter, refer to Section 5.6.

12.1 Starting the Simulation Controller

The Simulation Controller can be started by selecting the Simulation Controller button in the EuroSim start-up window (see Figure 6.1), by selecting the Observer button in the start-up window, or via the command line. When the Simulation Controller is started from the command line, the user can provide the following command line options: -observer Start the simulation controller in observer mode -connect hostname:prefcon Connect at start-up to an already running simulator running on host hostname on con- nection prefcon.

See also the manual page for the Simulation Controller SimulationCtrl(1). Example:

hobbes:˜$ SimulationCtrl -connect minbar:0

Before components for a new scenario can be defined in the Simulation Controller editor, a model and a schedule should be selected. The model is needed for the definition of the scenario actions and the initial condition files using the data dictionary specific for that model. The schedule is required in order to actually run a simulation. By selecting the File:New menu item a wizard will appear that helps you select the files you need.

If the Simulation Controller is started by selecting the Observer button, then the number of options will be limited, as the outcome of the test cannot be affected in any way. This means that some menu options (e.g. debugging) and some activities (e.g. using a script to update a data value) are not available.

Before a simulation can be started through the Simulation Controller, a simulation definition file has to be loaded (using the normal File:Open menu item), or should be created (using the normal File:New menu item).

c Airbus Defence and Space 123 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

12.2 Input Files of the Simulation Controller

The Simulation Controller allows the Test Conductor to create different simulation definitions for executing a model in the simulator, each testing e.g. a particular aspect of the model. Such a definition consists of the following components: Reference to a model This is a link to a model definition. This link is necessary to collect all required information about a model. Reference to a schedule This is a link to a schedule definition. This link is necessary to actually run a simula- tion. Reference to an export This is a link to an export definition. This link is optional and specifies the exports file that describes which variable nodes will be exported to external clients, see file formats in Section A.5 for a description on the exports file format. Chapter 32 describes in more detail how an exports file is used. Reference to an alias file This is a link to an alias definition file. This link is optional and specifies the alias file that describes which variable aliases will be created. See file formats in Section A.6 for a description on the alias file format. Section 12.7.3 describes in more detail how aliases work. Initial conditions These are used to change the initial state of the model. The initial conditions override the initial values of the variables defined in the code. Scenarios These are used to create events and actions, e.g. to introduce malfunctions in the sim- ulation. A scenario contains script, recorder and stimulus actions. Several scenarios can be loaded at one time. Stimuli files Stimuli are used to replace external data inputs which would be present in the real world. Time-series stimuli have their values taken from a file, for example to feed in values representing an operator’s input. Functional stimuli have their values generated from a mathematical function. MMI Definitions MMI definitions describe where monitors are placed on the MMI tab page and which data they monitor. Monitors on an active MMI page collect data during a simulation run. They do not store the information in a file, but display the data directly on screen. It is also possible to execute scenario scripts and activate/deactivate recorders and stimulus actions by placing buttons or checkboxes on the MMI tab page. In order to reduce required bandwidth between the simulator and Simulation Controller, you can deactivate an MMI file. Image Definitions The simulation definition can contain information about one or more image defini- tions. Once the simulation has been initialized, an image definition can be “launched” as a separate client. User Program Definitions A user program definition is used to launch a program as a separate client. That program can connect to the simulator and provide additional functionality.

Not all of these components have to be present in one simulation definition. Only the references to the model and schedule are required.

124 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

12.2.1 Initial Condition

A particular simulation is often required to be executed several times, each one starting from a different state i.e. a different initial condition definition. Instead of creating different simulation definitions for each of these possibilities, it is easier to reference all the possible initial condi- tions within a single simulation definition, and then to ensure that the required initial conditions are selected prior to initializing the simulator.

Figure 12.1: Simulation Controller with multiple Initial Conditions

The required (active) initial conditions are indicated in the Input Files tab page: the initial conditions marked Active form the set of values that will be applied if you request “Init” or “Reset” from the Simulation Controller. Values which have been updated are then used in tasks scheduled for the “initializing” state. The set of active initial conditions can be updated by activating or deactivating the appropriate file in the Input Files tab page.

Alternatively, you can request Control:Apply Initial Condition. . . from the Simulation Con- troller to cause the data values within the file to be applied directly to the current simulation. In this case, the values are used to override the current simulation values. The simulation state is not affected when this option is used.

12.2.2 Script Action

This type of action contains a Mission Definition Language (MDL) script. A script is the basic building block from which all actions can be made. For ease of use, EuroSim provides special- purpose interfaces for recorders and stimuli. However, any actions which require more complex activation conditions (e.g. a recorder which is to record when a particular data value is between predefined boundaries) can only be made by defining the script directly.

MDL is a simple yet versatile language for simulation scripting. It allows users to write control scripts in a limited free-text, C-like language. Chapter 23 contains a comprehensive overview of MDL. A script action is made up from four parts:

c Airbus Defence and Space 125 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

name Used to reference the action. attributes Which determine how the action looks on the scenario tab page, in which state it should be executed, etc. execution condition Which contains the condition (written in MDL) under which the action will be executed. action to be executed Which contains the actual MDL script which will be executed when the condition is true.

All of these items can be modified with the Action Editor, which is described in more detail in Section 12.10.3. The Action Editor is started when creating a new action, or when modifying an existing action.

12.2.3 Stimulus Action

The stimulus action is a special case of the script action, and can be used to easily create actions that provide stimuli to the simulator, using data from a specified file to update the values of the selected variables, at a certain frequency and for a certain time period. Using the Variables tab page in the Action Editor, there is no need for the user to write the MDL script himself. However, if needed, users can still access the raw MDL script, allowing the editor to be used for the creation of the basic stimulus action and then be customized. See Section 12.10.3.3 for a more detailed description of the stimulus Action Editor.

12.2.4 Recorder Action

The recorder action is also a special case of the script action, and can be used to easily create actions that record the values of one or more selected variables, at a certain frequency and for a certain time period. Using the Variables tab page in the Action Editor, there is no need for the user to write the MDL script himself. However, if needed, users can still access the raw MDL script, allowing this editor to be used for the creation of the basic recorder action, and then be customized. See Section 12.10.3.2 for a more detailed description of the recorder Action Editor.

12.2.5 Monitors

While it is possible to create a monitor script action, this type of monitor has become obsoles- cent. Generally you only come across a monitor action when loading an old (EuroSim Mk2 or earlier) .mdl scenario file or when you explicitly create a script action containing a monitor.

When an obsolescent monitor action is triggered a new tab page Script Monitors will appear that contains the created monitor.

In EuroSim Mk7.1 a monitor is no longer a script action. Instead monitors are defined in a .mmi file and can be edited in the corresponding MMI tab page. You can create multiple MMI tab pages, each containing a set of monitors.

In order to reduce required bandwidth between the simulator and Simulation Controller, you can deactivate an MMI file. When and MMI file is inactive, its monitors will not be subscribed for updates from the simulator. You can activate or deactivate an MMI file when the simulator is running. The monitors will then subscribe or unsubscribe for updates as appropriate.

126 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Monitors on the scenario tab page can be converted to an MMI tab page by using Tools:Convert Old Monitors. There are two built-in monitor types: alpha-numerical and graphical monitors.

With alpha-numeric monitors, a window will be shown in the MMI tab page in which the current value of one or more variables will be presented. The window will be updated when the value changes.

Graphical monitors use one of three types of graphs to display the values of variables:

XY Plot one or more variables against an independent variable. Simulation Time Plot one or more variables against the simulation time. Wall Clock Time Plot one or more variables against the wall clock time.

See Section 12.11.4 for a more detailed description of the Monitor Editor. For user-defined monitors, a special plugin type can be used. This type uses shared libraries to load plugins. For a more detailed description and examples see Section 12.11.5.

12.3 Windows of the Simulation Controller

When the Simulation Controller has been started, a window similar to the one in Section 12.12 is shown. This window is divided into two main parts, separated by a splitter: Tab pane This pane contains several tab pages that used for editing, debugging and viewing a simulation. Message tab pane Shows the messages from the simulator.

At the top is the menu bar and a tool bar. At the bottom a status bar provides additional state information.

12.3.1 The toolbar

The tool bar provides easy access to the following functions:

New Create a new Simulation Definition. The same as the File:New menu item. Open Open an existing Simulation Definition. The same as the File:Open menu item. Save Save the current Simulation Definition. The same as the File:Save menu item. Up Go up one level in the folder hierarchy. Available when the scenario is represented using icons. The same as the View:Up menu item. New Folder Create a new folder. Available in the scenario tab page. The same as the Insert:New Folder menu item. Init Initialize the simulator. The same as the Control:Init menu item. Reset Reset the simulation. The same as the Control:Reset menu item. Pause Pause the simulation. The same as the Control:Pause menu item.

c Airbus Defence and Space 127 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Step Advance the simulation through one executing cycle. The same as the Control:Step menu item. Go Put the simulation in executing state. The same as the Control:Go menu item. Stop Stop the simulation. The same as the Control:Stop menu item. Abort Abort the simulation. The same as the Control:Abort menu item. Mark Place a mark in the journal file. The same as the Insert:Mark Journal menu item.

12.3.2 The tab pane

The tab pane consists of the following tab pages: Input Files Shows all files used by the Simulation Definition. Schedule Used to debug a simulation run. API Show the data dictionary and quickly monitor and/or change the value of a variable. Scenario View and edit all actions in a scenario. One tab page appears for each scenario in the Simulation Definition. MMI The Man-Machine Interface. One tab page appears for each MMI file in the Simulation Definition. The MMI tab page allows you to monitor variables and to execute scripts, recorders or stimuli.

To start the simulation controller with a specific tab page, you can make one of them the default by using the menu item Edit:Set Default Tab Page.

12.3.3 The message pane

On the message pane all messages are displayed. This includes messages generated by the simulator (e.g. when starting the simulator, or when pausing it), errors from the scheduler (see Appendix E). as well as marks and comments created by the test conductor. Comments are marks with an extra item of text attached. See Section 12.12 for some examples. Marks and comments can be created with the Insert:Mark Journal and Insert:Comment Journal Mark menu items. All messages appearing on the pane are also logged into the journal file, see Section 12.4.

128 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 12.2: The Simulation Controller

Messages generated by the simulator include messages about: • Change of state • Problems encountered, such as real-time errors • Manual activation of actions • Updates to the action definitions Simulation message logging can be customized by creating additional message tabs. For each message tab a message filter can be created to filter (out) messages based on their types. There are four standard EuroSim message types (message, warning, error, fatal). Additional user defined message types can be created in the simulator using EuroSim library functions. Message tabs can have filters on built-in EuroSim message types and user defined message types. For more information see Section 12.12.

12.3.4 The status bar

In the status bar a number of items about the current simulation are displayed: • The current simulation state. • The simulation server. • The current user role (Test Conductor or Observer) • The simulation mode (real-time vs. non-real time vs. debug) • The simulation speed. • The simulation time (it is expressed in seconds or as an absolute time displayed as YYYY- mm-dd HH:MM:SS.ssss if the simulation uses UTC). • The wall clock time (elapsed time since start-up or the UTC time if the simulation uses UTC). • Traceability: experimental or traceable. If the simulation of a versioned simulation defini- tion is requested, then be traceable at a later date or not. If so, then the status bar will state that the simulation is Traceable, if not, then the simulation is Experimental. If internal version control is not used (not configured), the field will show No Versioning.

c Airbus Defence and Space 129 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

‘Traceability’ means that all source files involved in the simulation definition can themselves be traced at a later date. This is only possible if a) the source files (i.e. simulation definition, scenarios, initial conditions, executable, MMI files, data dictionary and schedule (the latter de- riving from the model file)) are (generated from) non-modified repository versions (e.g. 1.2 not 1.2+) and b) the versions on disk match the required versions.

12.4 Output files of the Simulation Controller

During a simulation run, a number of files are generated: journal file This file contains all messages generated by the simulator, as well as all entered marks and comments. There are two variants of this file. A human readable version and a ma- chine readable version. The file name of the human readable file is EsimJournal.txt. The file name of the machine readable file is EsimJournal.xml. recording files These are the files that result from the recording actions as defined in the scenario definition. For each recorder a file is created with the name recordername.rec if the default name was chosen in the scenario definition. test result file This file contains a list of all recordings performed during the simulation run. This file will have the extension .tr. timings file The timings file contains statistical information on schedule execution. It is a hu- man readable file and displayed automatically in the Schedule Tab of the Simulation Recording. It is also loadable in the Schedule Editor to enhance the Scheduling dis- play with actual measurements (see Section 11.3.1 of the Schedule Editor). This file has the name timings. See also Section 11.4 for information on task timings. trace file The trace file contains a detailed trace of schedule execution events. The file is op- tional, trace file generation must be enabled via the Simulation Controller (or from external scripting). The tracing can be displayed in the Simulation Controller’s Sched- ule Tab. The location of this file should be on a local driver and can be changed from its default into a local directory as for instance /tmp via the Simulation Controller preferences or by providing a path into the Session structure from script languages.

All these files are created in a directory with a name like 2001-12-14/15:33:30, which in- cludes the date and time of the simulation run.

12.5 Dictionary Browser

The Dictionary Browser allows the Simulation Controller program to look at the variables and entry points that have been defined in the data dictionary. The browser is introduced as a general component of many EuroSim applications in Section 5.7. Specific functionality provided in the Simulation Controller is the capability to show the values of the variables during simulation execution. Additional details on the provided functionality can be found in section Section 12.9.

12.6 Menu Items

This section describes the menu items that are not tied to a specific tab page and that do not belong to the group of common menu items that are described in Section 5.6.

130 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Menu items that are only enabled when a specific tab page is on top are described in the section for that tab page.

12.6.1 Edit menu Set Default Tab Page Make the current tab page the default one on start-up. This setting is saved in the .sim file and will be restored the next time the .sim file is loaded. This is only applicable for the tab pages on the top portion of the screen, and not for the message tabs.

12.6.2 View menu Input Files Raise the Input Files tab page to the top. Schedule Raise the Schedule tab page to the top. API Raise the API tab page to the top. Script Monitors Raise the Script Monitors tab page to the top. MMI A sub-menu with all MMI tab pages. The selected tab page will be raised to the top. Scenarios A sub-menu with all Scenario tab pages. The selected tab page will be raised to the top. Toolbar Button Labels Show text below the toolbar buttons. This setting is saved in a settings file and will be restored the next time the Simulation Controller is started. Large Toolbar Buttons Show large icons for the toolbar buttons instead of the default small icons. This setting is saved in a settings file and will be restored the next time the Simulation Controller is started. Tabbar Labels Show text on the tab-bar. Disabling this setting can be useful if your Simulation Def- inition file contains a lot of MMI and/or script files. This setting is saved in a settings file and will be restored the next time the Simulation Controller is started. Refresh If the data dictionary or schedule file have been changed, then reload these files. Clear Log All the messages (if any) in the message tab pane currently on top are deleted.

12.6.3 Insert menu New Scenario Add a new Scenario file to the Simulation Definition. This will automatically create a new Scenario tab page where this file can be edited. You will be asked to enter the caption of the new tab page. Add Scenario Import an existing scenario file into the Simulation Definition. A new tab page will be created where this file can be edited. You will be asked to enter the caption of the new tab page. New MMI Add a new MMI file to the Simulation Definition. A new MMI tab page will appear where you can add monitors, etc. You will be asked to enter the caption of the new tab page. By default the new MMI file will be marked as Active in the Input Files tab page.

c Airbus Defence and Space 131 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Add MMI Import an existing MMI file into the Simulation Definition. A new tab page will be created where this file can be edited. You will be asked to enter the caption of the new tab page. By default the imported MMI file will be marked as Active in the Input Files tab page. New Initial Condition Add a new Initial Condition file to the Simulation Definition. By default the new initial condition file will be marked as Active in the Input Files tab page. Add Initial Condition Import an existing Initial Condition file into the Simulation Definition. By default the imported initial condition file will be marked as Active in the Input Files tab page. New User Program Definition Create a new User Program Definition. This is basically a user defined program that will be launched when you select Edit:Launch. The User Program Definition window is very simple (see Figure 12.3). In the Definition input field the program to start is specified and any arguments that are needed. The %h sequence will be replaced with the hostname of the running simulator, and the %c sequence will be replaced with the preferred connection number. If you need to run .bat batch files (Windows version only), then you have to precede the User Program Definition with ’cmd /C ’. Simi- larly for shell scripts (.sh files); precede the User Program Definition with ’bash ’. If the shell script file is located in the same directory as the .sim file and you do not specify the full path to it, then you may need to prefix the name of the shell script file with a ’./’, depending on whether the current directory (dot) is in your search path or not (environment variable PATH). Examples: ’bash -c ./myscript.sh’ or ’cmd /C mybatch.bat’.

Figure 12.3: Example User Program Definition

Add User Program Definition Import an existing User Program Definition. Make Mark Use this menu item to make a mark in the simulation log. The mark is also displayed on the message pane. The idea behind marks is to allow you to tag some interest- ing/unexpected event quickly. Each mark is allocated a unique number which can also be used for adding explanatory comments later on. Make Comment Use this menu item to enter a comment in the simulation log. The comment is also shown on the message pane. When this menu item is selected, a window shown in Figure 12.4 will pop up, in which the comment can be entered. By default, the comment ‘belongs’ to the last mark made, but you can add comments to earlier marks by manually editing the number in the Mark field.

Figure 12.4: The Comment Journal Mark window

132 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

New Message Tab Use this menu item to create a new message tab to customize simulation message logging. For more information see Section 12.12.

12.6.4 Server menu Select Server Before a simulation can be started, a computer on the network has to be selected which can act as the simulation server. By default the host on which you started EuroSim is assumed to be the simulation server, and so this option is only necessary if you wish to use another host. When this menu item is selected, a window similar to the one in Figure 12.5 is shown. This window lists all currently available servers on the network. Use the Server:Show Current Simulations menu item to check the status of each of those servers.

Figure 12.5: Select Server window

If the checkbox Use FTP is enabled, as in Figure 12.6, the dialog allows a host to be specified via its ip address. In this mode, the relevant simulator files will be uploaded to the host using FTP at the start of the simulation. The last transferred file is a command file to start the simulator. A local process on the simulator host can scan for this file and launch the simulator using this file. This mechanism circumvents the need for a EuroSim Daemon to start simulators remotely. This functionality is for instance used for target computers that are used to run an EuroSim Embedded simulators and do not have a daemon installed. The current solution is tailored to embedded systems running the pharlap OS. Generalisation is currently a low priority as this approach is rarely used. Please contact the EuroSim helpdesk if you require this feature.

Figure 12.6: Specify FTP Server window

Show Current Simulations Use this menu item to check the status of the simulations running on either the local or all simulation servers on the network. An example is shown in Figure 12.7. The network check button can be checked to poll all reachable simulation servers on the network, as shown in the Figure 12.7. If unchecked only the local simulation server is checked. The Show Paths button can be used to show the exact path of each the simulation running on the servers. When the paths are shown, the button will change into a Hide Paths button, which reverses the action. The Refresh performs a new scan

c Airbus Defence and Space 133 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

and updates the list of simulations.The (Re)Connect button can be used to connect to one of the simulations in the list. The Kill Sim button can be used to kill a simula- tion if a run is hanging for any reason and is no longer responding to the Simulation Controller.

Figure 12.7: Show Current Simulations window

Reconnect to FTP Simulator If the Use FTP option has been enabled in the Server:Select Server dialog, this menu item will be enabled. It allows to reconnect to aremote running simulator launched via FTP using the IP address specified in the Use FTP dialog of Select Server. (These simulators cannot be selected using the Server:Show Current Simulations menu item, as there is no EuroSim daemon running on the remote host.) Only use this action to reconnect to a simulator that corresponds with the selected model, otherwise results will be unspecified. (Most likely establishing the connection will be succesful, but the parameters between the expected model and actual simulator will not match.) The current solutionis tailored to embedded systems running the pharlap OS. Gener- alisation is currently a low priority as this approach is rarely used. Please contact the EuroSim helpdesk if you require this feature. Disconnect From Server This menu option will disconnect the Simulation Controller from the simulation server. The simulation will remain on the server, and the Simulation Controller can be recon- nected to the server using the Server:Show Current Simulations or Server:Reconnect to ETS Simulation menu items. In case the Use FTP option is enabled, the intermediate results are retrieved from the server (using FTP) and stored in the appropriate result directory.

12.6.5 Control menu Set Realtime This menu item acts as a toggle with which the simulation can be set to real time mode or non-real time mode. This can only be done before the simulator is initialized. When the simulation selected to run non-real time, the user can use the Debug:Start Mode options (Linux only) to run the simulation in a debugger or to run the simulation in a memory check mode. Note that when the user selects to run the simulation real time, that Start Mode is reset to Normal. Speed Control Use this menu item to get the Speed Control Window as shown in Figure 12.8. When the simulation is running non- real time the user can speed up or slow down the sched- uler clock with the slider. The ‘as fast as possible’ button selects a mode where the scheduler is boosted to maximum speed without internal clock overhead. The actual

134 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

speed can be lower than the requested speed, since the scheduler slows down if tasks do not complete in time1.

Figure 12.8: The Speed Control window

Init This will initialize the simulator according to the selections made: real time or non-real time (Set Realtime), normal, debug of memory check (Debug:Start Mode), and gdb or ddd debugger (Tools:Preferences. Standard this process comprises of the following steps: 1. Load the application model associated with the current simulation definition. 2. Use the data dictionary information to set initial values. 3. Use the Initial Condition files (if active) to update initial values. 4. Execute the task from the initializing schedule through the scheduler. 5. Execute the actions that are tagged as active during the initializing state. Once the initialization is complete, the simulator will be in the standby state at simulation time 0.0000 seconds, or the simulation time set by a script or model code. If Use FTP has been enabled in the Server:Select Server dialog the following steps are executed before the default steps: 1. Check if no model is running on the selected host. If there is, an error is displayed and the Init action is aborted. 2. Collect the application model files and transfer these to the selected Phar Lap ETS host using FTP. 3. Collect the required “stub” DLL files for the model and transfer these as well. 4. Generate and transfer a “run.cmd” file that specifies the model with the correct runtime parameters. ... Rest of the steps. Reset This will reset the simulation (i.e. perform steps 2 through 5 of the initialization process). Note that if the schedule contains an output connector connected to ABORT, the simulation cannot be reset. Step This will advance the simulation through one executing cycle. If the schedule contains a low frequency task, then this could be a significant period of time. Go This will put the simulator in the executing state. Pause This will temporarily stop the simulation (put it in standby state). The simulation is not necessarily completely inactive however, as tasks and actions specified for the standby state will be still executed. Stop This will stop the simulation gracefully. The simulator will be transitioned to the exit state, all open files will be properly closed and the connection to the simulation will be disconnected. If the simulation was run on the Phar Lap ETS platform using the Use FTP option from Server:Select Server dialog, the result files from the simulation will be retrieved using FTP and stored in the result directory.

1Speed Control has no effect if an external clock is used whose frequency cannot be changed by EuroSim.

c Airbus Defence and Space 135 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Abort This will abort the simulation instantaneously. Open files will not be closed by Eu- roSim, but rather by the operating system, which results in loss of data as data still in memory is not saved. If a test execution has resulted in a simulator hang, or remaining executables from previous simulation runs, use the Server:Show Current Simulations menu option and select the offending simulation and request Kill Sim to remove the remaining executa- bles.2 Raise Event Show a list of available user defined events. Select an event and raise that event by either double clicking the event or pressing the Raise Event button. This menu item is only available when the connection to the simulator is active and if at least one user defined event is available. Enable Recording This menu option allows the user to activate/deactivate all recording actions in the sim- ulation via a single request. This can be useful for temporarily suspending recording during a simulation run. Enable Tracing This menu option allows the user to activate or deactivate the tracing of the Scheduler events to a trace file. Note that by default the Preferences setting is to actively record from the start. This can be changed to start in suspended mode to allow control via MDL scripts to resume recording when needed.

Figure 12.9: Take Snapshot window

Take Snapshot This menu option will pop-up a window (see Figure 12.9) with which a snapshot of the current state of all simulation variables can be made. In the same window a comment can be added to the snapshot. The file created has a default extension of .snap. Snapshot files can be used as initial condition files (see Section 12.7.4). Apply Snapshot This menu item will have a sub-menu showing all available initial condition and snap- shot files, i.e. all files referenced within the current simulation definition. Select one of the initial conditions to override current simulation values with the values in that file. Apply Initial Condition Apply the selected initial condition file to the currently active simulation to override the current simulation values with the values from the selected file. Check Health Check whether the connection to the simulator is working correctly. A message ap- pears in the log pane describing the health status of the simulator.

2 As a last resort, use the efoKill command from a UNIX shell or Windows command prompt to remove the remaining executables, see Section 24.12.2. The efoList command can be used to list the simulator runs currently executing on the host machine, see Section 24.12.1 or the UNIX manual pages for more information.

136 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

12.6.6 Debug menu Enable Timebar This option enables recording of detailed task timing data during simulation execution that can be displayed and analysed by means of the Time bar function afterwards. See Section 12.8.5.2 for details on the use of the Timebar. Start Mode This option defines the start mode of the simulation execution: • Normal - This is the default mode for simulation execution. The simulation is started according to the real time selection set by means of Control:Set Realtime. • Debug - If the simulation is configured to be started non-real time, the Debug menu item is enabled and allows the user to start the simulation execution by means of the debugger configured in the Simulation Controller Preferences. See Section 12.6.7 for these preferences, see Section 12.8.4 for details on symbolic debugging. When the simulation is set to run in real time mode by means of Control:Set Realtime, the Start Mode changes to Normal and the options are disabled. Note: the Debug-mode as Start Mode is not supported in the Windows version of EuroSim (the option is disabled in that version always). • Memory Check - If the simulation is configured to be started non-real time the Memory Check menu item is enabled and allows the user to start the simulation execution using valgrind. The valgrind output is added to the esim daemon log file. When the simulation is set to run in real time mode by means of Control:Set Realtime, the Start Mode changes to Normal and the options are disabled. Note that the source code of simulation must have been compiled in debug mode (-g for C and C++ compilers typically). The Memory Check-mode as Start Mode is not supported in the Windows version of EuroSim (the option is disabled in that version always).

12.6.7 Tools menu Preferences This option shows the Simulation Controller preferences dialog for editing user spe- cific global settings as show in Figure 12.10.

Figure 12.10: The Simulation Controller preferences window

c Airbus Defence and Space 137 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Settings in this dialog allow you to specify how the Simulation Controller GUI be- haves. This is independent from the project that is loaded. Settings that can be spec- ified define for instance the maximum number of Simulation Definition files that are stored in the most recently used files list in the File menu. You can also select whether all changes are always automatically written to disk when the stimulator is started, or which debugger will be launched when you use the Start Debugger (F5) option from the Debug menu. The MMI Auto Disable option forces the Simulation Controller to automatically dis- able any non visible MMI tab. This mode should only be used when large number of MMI tabs and monitors are used, and the user experiences that the Simulation Controller becomes unresponsive. In such extreme case the responsiveness can be im- proved by disabling tabs. Switching the MMI Auto Disable mode on automates the disabling, leaving only the visible MMI tab active. The option to change the directory where the timebar files are generated is relevant when the user is working with network mounted disks. The timebar files are filled at high speed and are best written on a local drive. By adding a date-time string in the filename, eachs simulation creates a new file whereas otherwise the files are overwitten which reduces the storage needs. Furthermore the trace active on start switch allows to select if recording should immediately start from startup. The alternative is to start in suspended mode and resume the recording from MDL or via a function call to the EuroSim API. CPU Load This option enables or disables a CPU load monitor as shown in Figure 12.11.

Figure 12.11: The CPU load window

The average and peak load percentage readings are shown for each CPU. The loads are measured over the time interval specified in the line edit in the last column. The av- erage load shows the average of the measured loads over a 1000 milliseconds period. The graphical plot shows the maximum of the measured loads over the 1000 millisec- onds period. The peak load reading shows the maximum measured load encountered during the simulation. The load measurement time interval can be set in a range from 1 to 9999 ms. If you edit values in the last column you should press the Apply Time button to actually use the changed value. If the measurement interval is larger then 1000 milliseconds, then the average load will be equal to the actual load in the plot as the time measure- ment interval is larger then the 1000 msec interrogation period used by the Simulation Controller.

This CPU load monitor is only available if a connection to a simulator is active and the simulator is running in real time.

138 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Rec/Stim Bandwidth This menu item will show in a window (see Figure 12.12) the runtime bandwidth (in bytes/second) for the recorders and stimuli defined in all scenarios in the Simulation Definition. There are two estimates: one for all actions and one for all active ac- tions. These estimates do not take into account start and stop times of these actions, or any other conditions (such as a test like if varx >100 record ...). The actual bandwidth values are only available during a simulation. The Time before disk full item is an estimate based on the bandwidth of the active recorders and does not take other file actions into account. It also assumes that all recorder files are written to the results directory as displayed in this window. Press the Rescan button to perform a new calculation based on the most actual band- width and free disk space values.

Figure 12.12: The Rec/Stim bandwidth window

Configuration This menu item will display a window in which various information on the current simulation is given (see Figure 12.13). In the top half of the window the names of the files currently in use as model, schedule, export, alias file, data dictionary, initial condition and scenario are displayed, as well as any stimuli data files referenced so far. Finally, the actual stimuli throughput (in bytes/sec) is given. In the bottom half of the window any recording data files in use and the recording throughput are given. Also (prior to requesting Init), the user can change here the directory in which all results files should be stored, as well as whether additional date and time subdirectories should be created where the results files are placed. The Show Paths button can be used to view the full path of each of the file names. The Rescan button can be used to get the latest information on the throughput rates.

c Airbus Defence and Space 139 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.13: Sample Configuration

12.7 Input Files tab page

This tab page lists all files used in the Simulation Definition. These files can be removed through Edit:Delete, new files can be added through the Insert menu and the contents can be edited (where applicable) through the Edit:Properties menu.

The tab page consists of a tree structure that organizes the files by type: Top Level Shows the used simulator definition (.sim), model (.model), schedule (.sched), ex- port (.exports), and alias (.alias) files. Scenarios Shows all scenario (.mdl) files. MMIs Shows all Man-Machine Interface (.mmi) files. Initial Conditions Shows all initial condition (.init) files. Calibrations Shows all Calibration files (.cal) files. This is mandatory if the calibration files are not included in the Model Editor and are loaded via the programming API. If they are included in the Model Editor tree, it is still allowed to also include these in the Simulation Controller to provide easy access to end users. User Program Definitions Shows all User Program Definition (.usr) files.

You can reorder the scenario or MMI tab pages. To do that you drag and drop a scenario or MMI file to before or after another scenario or MMI file.

To reorder the Initial Condition files (and thus the order in which these files are applied) you can also use drag and drop to move then around.

12.7.1 Menu items

The following File menu items are available in the Input Files tab page:

140 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Select Model Select another model file for this Simulation Definition. Select Schedule Select another schedule file for this Simulation Definition. Select Export Select an exports file for this Simulation Definition. Select Alias Select an alias file for this Simulation Definition. Save File As Save the selected file to another location.

The following Edit menu items are available in the Input Files tab page: Properties Allows you to edit the properties of the selected file. For scenario and MMI files the corresponding tab page will be raised to the front. For Initial Condition and User Program Definition files a dialog will appear. Delete Remove this file from the Simulation Definition. Note that the actual file is not deleted, the entry is only removed from the Simulation Definition. Activate Only valid for Scenario, MMI and Initial Condition files. Mark this file Active, i.e. this file will be used when the simulator starts. Deactivate Only valid for Scenario, MMI and Initial Condition files. Mark this file Inactive, i.e. this file will not be used when the simulator starts. Inactive scenario, MMI and initial condition files are ignored by the simulator. Launch Only valid for User Program files. This will launch the program definition. If the launch User Program produces output and/or error messages then a window will pop up that shows those messages.

The following Control menu item is available in the Input Files tab page: Apply Initial Condition The currently selected initial condition file will be applied to the running simulation.

Double clicking on the file name has the same effect as selecting Properties from the Edit menu. There are a few exceptions: double clicking on a User Program Definition file when a connection to the Simulator is active will Launch the program.

12.7.2 Context menus

Two context menus are available in the Input Files tab page depending on where you click the right mouse button. If you click on a file item in the tree then a context menu with the following items appears (see Section 12.7.1 for a description of the menu items):

• Properties • Delete • Activate • Deactivate • Launch • Apply Initial Condition • Select Model • Select Schedule

c Airbus Defence and Space 141 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• Select Export • Select Alias

The other context menu appears when you click outside the tree area to the right of the last column or below the last row (see Section 12.6.3 for a description of the menu items):

• New Scenario • Add Scenario • New MMI • Add MMI • New Initial Condition • Add Initial Condition • New User Program Definition • Add User Program Definition

12.7.3 Data Dictionary Aliases

The alias file defines aliases for individual data dictionary variables. A variable is defined through its data dictionary path. It is possible to create an alias for a composed variable such as an array or structure or to create an alias of an individual element of that variable.

Aliases are placed in a special /alias sub tree of the data dictionary at run-time. It is possible to refer to aliases using their short name through the client-server protocol to set and get individual variables (dtSetValueRequest or dtGetValueRequest).

The aliases placed in the /alias sub tree are accessible as if they were normal data dictionary variables (which they are).

12.7.4 Initial Condition Editor

The Initial Condition editor allows the specification of a particular state to which the model should be initialized prior to execution, e.g. locations of payloads or the state of hatches. It is only necessary to specify values in the initial conditions if these values override the initial value specified in the API header. The initial conditions are set prior to execution of the code, and a simulation can be re-initialized during a run.

The validity of the initial condition cannot be checked by EuroSim. However, the Initial Condi- tion editor will only allow values of the correct type to be entered which are the range that was specified in the API headers of the model.

The initialization sequence is as follows:

• first the simulator is loaded and the variables will get the values as they are hard coded in the source file. • next the model is loaded and the variables defined in the API headers will get their desig- nated default values • finally, the initial conditions are used to set the variables specified in the Initial Condition files, with their values. The order of appearance in the Input Files tab page determines the order of initialization. I.e., the top-most Initial Condition file is applied first, followed by the second file, etc.

142 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

12.7.4.1 Starting the Initial Condition editor

The editor is started by double-clicking with the left mouse button on an Initial Condition file in the Input Files tab page, or by selecting an Initial Condition file and then selecting Edit:Properties. A dialog appears that uses the Dictionary Browser to represent the dictionary and to edit the initial conditions.

You can set initial values by left-clicking on the line containing the variable that you want to edit or by selecting the line and pressing F2.

Values that are out of bounds are rejected. If you want to set the initial value for a variable designated as a parameter then a window appears asking for confirmation.

You remove an initial value by clearing the contents. However, clearing a member of a structure or array will only reset the value to the default value. If you want to clear the initial value of the whole compound variable, then right click on the top variable node and select Clear from the context menu.

If the initial value that you entered is equal to the default value, then the initial value is cleared and removed from the set of initial condition values. As indicated above, this does not apply to the members of compound variables.

Any variable that has an initial value is marked with a small asterisk ( ). Also all entry point and org nodes that contain variables that have an initial value are marked the same way.

12.7.4.2 Context menu items

If you right click on a node or on the background a context menu appears with the following items (besides the menu items that are described in Section 12.9):

Clear The initial value is removed for the selected variable. Show Modifications Only/Show All This menu item toggles between showing all variables or only those that have an initial value. You can also use the key F4 as a shortcut. Undo Undo the last change. Redo Redo the last Undo action.

12.8 Schedule tab page

The schedule used by the simulation definition can be debugged in the Schedule tab page (see Section 12.8.1). The upper fours buttons on the left allow switching between the schedule states. In these views the user can set traces and breakpoints, as well as disable and enable tasks prior to a simulation run. The lower two buttons Statistics and Timebar are related to displaying the timing results after a simulation run.

The Debugging concepts and operations are elaborated in the sections Section 12.8.1 up to Section 12.8.4. The timing analysis views are further elaborated in section Section 12.8.5.

12.8.1 Debugging Concepts

Debugging a simulation run (or software in general) is a means to investigate why the simulation run is not running as intended. In EuroSim this is done by allowing the user to run the simulation entry point for entry point. Thus, instead of going through the whole of the simulation, the

c Airbus Defence and Space 143 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.14: The Schedule Tab Page

Debug Control window allows the user to stop at any entry point he wishes, or even, to stop at every entry point before executing it. This process is called single stepping through the simulation code. However, as it can be rather tedious to single step through all entry points, breakpoints are available. A breakpoint is a kind of stop sign next to an entry point. Whenever the simulator encounters such a stop sign, it will hand over control back to the user. Also, in order to assist the user in debugging the simulation run, entry points can be traced and complete tasks can be disabled or enabled at will (note that if a task is disabled, all tasks connected to it ‘downstream’ in the schedule will also not be called).

Single stepping, breakpoints and disabling of tasks are all easily controlled through the schedule tab page. The schedule tab shows the schedule as defined by the Schedule Editor. You can set breakpoints, traces and enable/disable tasks using the Debug menu or by right-clicking on a task to show the context menu.

If you are in debugging mode, then the simulation state is ‘executing’, even if you are paused at a breakpoint. In such a case, the main window will say ‘executing’ whilst the simulation time is stopped. In order to return to normal executing, you need to clear all breakpoint tags and continue using the Continue button.

If you set a breakpoint of a task in Initializing state, then that breakpoint will not work because the list of breakpoints is passed on to the simulator after the Initializing tasks have been called. This is a known limitation.

12.8.2 Debug Control objects

12.8.2.1 Enabled task

These are the tasks as defined in the schedule of the simulation. An enabled task will be exe- cuted by the simulator.

144 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

12.8.2.2 Disabled task

A disabled task will not be executed by the simulator. Note that any task connected to a disabled task will also not be executed.

12.8.2.3 Current task

The current task (shown in green) is the task currently being executed by the scheduler. If the simulation is run on more than one processor, more than one current task can be present in the schedule view.

12.8.2.4 Breakpoint

This is used to indicate the entry point(s) which have a breakpoint attached.

12.8.2.5 Trace

This is used to indicate the entry point activation will be traced. A traced entry point writes time-tagged messages in the Simulation Controller log window. If an entry point has both a trace and a breakpoint, only the breakpoint is shown.

12.8.2.6 Color coding

The tasks are color coded:

blue indicates the selected task. green indicates the currently executing task/breakpoint.

12.8.3 Menu items

The following Debug menu item is available in the scenario tab page: Item Debug Settings. . . Open the Debug Settings window to set and clear breakpoints and traces for the se- lected task. Clear All Breakpoints Clear all breakpoints in the schedule. Clear All Traces Clear all traces in the schedule. Toggle Task Activity Enable or disable the task. Continue Let the simulator run until a breakpoint is encountered. Note that the Go button on the main Simulation Controller window cannot be used for this purpose. If Continue is requested after all breakpoints have been cleared, then this puts the simulation run back into a normal, non-debugging mode. You can use the function key F8 to quickly access this menu item. Step Advance the simulation to the next entry point to be executed. This button should not be confused with the Step button on the Simulation Controller window itself. You can use the function key F10 to quickly access this menu item.

c Airbus Defence and Space 145 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

12.8.4 External debugging facilities

There are two options for debugging model code within EuroSim. The first option is to use the debug control window in the Simulation Controller (see Section 12.8.1). This is useful for tracing which tasks and entrypoints get executed. It also offers an integrated interface with EuroSim itself.

However, when the model code is not behaving as expected, a symbolic debugger may become more practical. In these cases, it is possible to attach an external (symbolic) debugger. The only precaution to be taken is to set the usual -g flag in the Build Options of the simulator to include the symbols required by the debugger in the exectutable code. Because EuroSim uses the GNU compilers, the usage of the GNU Debugger (gdb) or graphical front-ends for it such as ddd or eclipse are advised. Of course symbolic debugging is not usefull with a real-time executing simulator as the timing will no longer be correct.

The Simulation Controller supports symbolic debugging by launching the debugger when press- ing F5 or selecting Start Debugger from the Debug menu.3. Which debugger is to be launched can be configured in the Preferences menu item of the Simulation Controller. When the debug- ger is launched by the Simulation Controller it will automatically load the correct symbols and attach to the simulator executable. The execution of the simulator will come to a halt, the time displayed at the bottom of the Simulation Controller will no longer increase. At this point the user can type the where command to see the stack trace, set breakpoints, step or continue with the execution.

The use of symbolic debugging can be combined with the scheduler debugger capabilities in the Simulation Controller. First use the scheduler debugger capabilities to stop at the entrypoint that you want to start debugging. Then attach the symbolic debugger, set your breakpoint in the code and allow the scheduler debugger and symbolic debugger to continue.

An alternative approach for launching the symbolic debugging is for the user to start the de- bugger independently with as argument the simulator executable which can be found in the .WINNT or .Linux directory that is generated by the ModelEditor. The last argument should be the process id ((which can be obtained with the ps command). This approach is more likely for eclipse users as eclipse takes long to start.

Because the Simulator executable uses signals, the GNU debugger will get interrupted when attached and continuing the simulation. To avoid this, create a file .gdbinit in your home directory containing the following lines:

handle SIG34 nostop handle SIG34 noprint handle SIG35 nostop handle SIG35 noprint handle SIG36 nostop handle SIG36 noprint handle SIG37 nostop handle SIG37 noprint handle SIG38 nostop handle SIG38 noprint handle SIG39 nostop handle SIG39 noprint

You can copy this file from $(EFOROOT)/etc/gdbinitˆ.

3In EuroSim for Windows the debugger currently may not attach, but does get started. You can find the process id (pid) via the Task Manager’s Performance Monitor after clicking Resource. Type attach to connect to the running simulator.

146 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

12.8.5 Timing analysis

EuroSim provides two approaches to record the timing characteristics of simulations for post analysis purposes. The first approach is a statistics recording, produced at the end of every successful simulation run. The second approach is a detailed recording of every event and execution over time.

12.8.5.1 Statistics view

The statistics view provides a text display of the timings file as produced at the end of a simu- lation run. The view is automatically loaded, but in offline mode the user can also load files via the browse button. Figure 12.15 shows the statistics view:

Figure 12.15: The timing statistics view

The Statistics view shows for most items the number of times it has been activated. For the tasks it provides also a detailed overview of the execution timing of the task and entrypoints:

Running The time that the code in the entry points was actually executing. Blocked The time between task activation and start of execution. Preempted The time the task was preempted by a higher priority task. Duration The total time to execute the task entry points. Offset The start of execution measured from the start of the current cycle. Finished The end of execution measured from the start of the current cycle (Offset + Duration).

12.8.5.2 Timebar view

The timebar view displays the detailed trace of scheduler events and processor execution when timebar recording is enabled. the SimulationController and must be performed prior to the start

c Airbus Defence and Space 147 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

of an execution. The timebar view is an integrated display of the last timebar recording, with an ability to display files in offline mode.

The integrated timebar display in the Schedule Tab shows automatically the latest recording. Note that the loading of the taskbar will take place when the timebar view is displayed, as the large files may lead to excessive loading times which will make the other functions in the Simulation Controller unaccessible. For this reason the loading will only occur if no simulation is in progress.

An example of the resulting timebar visualization is shown in Figure 12.16.

Figure 12.16: Timebar View

The timebarviewer can also be started with a seperate window from the command line by typ- ing:

TimeBarViewer

The timebar visualizes the trace data for each state in a seperate tab, with each tab drawing the data in three categories. The ITEMS category visualizes the data from the perspective of the items on the ScheduleEditor canvas, resulting in the subcategories of tasks, timers, inputs etc. When data is found line items are added to the subcategory, making it unfoldable to show the details. The color coding shows on which scheduler executer the item was executed. A task scheduled on Any Processor in the Schedule Editor will likely show its execution therefore with different colors as the task can be executed by the first available processor.

The PROCESSOR category visualizes the date from a processor usage perspective. The pro- cessor number refers to the executer selected in the Schedule Editor, with NRT as special item for the Non realtime task execution, and Other for all processors above 7. For each processor both the acutal processing time used by EuroSim as well as the actual execution of user code is shown. This allows the user to see the overhead of EuroSim with respect to the execution of the users model code.

The SYSTEM catefory catches all remaining items, such as messages from the scheduler rele- vant to tracing, or the clock tick interrupt timing.

Note that the trace file can grow substantially very quickly. Internal buffering is applied to pre- vent that the writing to disk affects the execution of the system, but nevertheless there is a small

148 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

overhead introduced. Also it is advised to specify the location (path) of the trace file some- where on a local drive, thus avoid using a networked drive. This can be set in the Simulation Controller Preferences dialog.

To control the size of the timebar recording and focus the recording on where the problem is expected the scheduler tracing can be paused and resumed. This can be performed via the EuroSim API functions:

void esimTracePause(void) void esimTraceResume(void)

as well as from MDL scripts using the command

trace on trace off

In addition you can tailor what is traced using the API function

void esimTraceMask(unsigned type_mask, unsigned processor_mask)

or the MDL command

esimtrace type_mask processor_mask

12.9 API tab page

The API tab page is a Dictionary Browser (see Section 5.7) with some extra functionality. When no simulation is running it just shows the dictionary with a few extra columns to show the minimum and maximum values, the unit of the value, and the description of the variable. The column Value is empty until a simulation is started. As long as a connection to the simulator is active this column will show the current value of that variable just like a monitor in an MMI tab page. By clicking on the value or by selecting the line and pressing F2 you can edit it and set the variable to a new value. Parameter variables cannot be set as they are read-only. Basically the API tab page is a quick monitor facility.

Figure 12.17: The API tab page

c Airbus Defence and Space 149 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

12.10 Scenario tab page

For each scenario file a separate Scenario tab page is created. When the scenario file is opened or created you are asked to provide the caption that appears as the name of the tab page. The scenario can be presented either as a tree view (see Figure 12.18) or as an icon view (see Fig- ure 12.19). In both cases the actions in the scenario can be organized in folders.

Figure 12.18: The Scenario tab page (tree view)

Figure 12.19: The Scenario tab page (icon view)

Actions in the scenario tab page can be either active or inactive (indicating whether it will be automat- ically checked against its run condition during a simulation run). For active actions the action name is shown in blue instead of black and (for the tree view only) the last column Status is marked with an ‘A’. By toggling the Active checkbox in the Action Editor dialog you can change the initial Active state.

150 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

During a simulation you can activate an inactive action or deactivate an active action. This does not modify the Active property of the action. When the simulation ends the Active status returns to its original setting. When an action is actually executing, the Status column is marked with an ‘X’ (for the tree view only) and the action name is shown in green instead of blue (active action) or black (inactive action). Icons are used to represent actions (stimuli, recorders, monitors, scripts) or folders. The following icons are used in the scenario tab page:

Recorder this icon is used for recorder actions (defined using the Recorder Editor)

Stimulus this icon is used for stimulus actions (defined using the Stimulus Editor)

Monitor this icon is used for monitor actions (can only appear in old pre-Mk.3 scenario files)

Script this icon is used for script (free format MDL) actions

Folder this icon is used for folders that can contain other actions or folders.

Double clicking on these actions when a simulation is running will have the following effect depending on the type of action: Recorder activate or deactivate this recorder Stimulus activate or deactivate this stimulus Monitor start this monitor (it will show up on the Script Monitors tab page)

Script trigger this action

You can drag and drop actions and folders from one place to another. In order to rename a folder or action you can click on the item with the left mouse button to select it, then click again to edit the name. You can also press F2 to edit the name of the selected item.

12.10.1 Menu items The following File menu item is available in the scenario tab page: Diff with This menu option will pop-up a file-selection box, in which another scenario file can be selected. The selected scenario file will be compared with the current file, and any differences will be reported. The following symbols are used to identify any differences; these will appear between column listings of components in scenario A (first column) and scenario B (second column): -> means that an item is present in B but not in A <- means that an item is present in A but not in B <-> means that there is a difference in versions between a file in both scenarios means that there is a difference in the body of two actions with the same name means that there is a difference in the condition of two actions with the same name. See Figure 12.20 for an example.

c Airbus Defence and Space 151 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.20: Example difference list

The following Edit menu items are available in the scenario tab page: Undo/Redo Action changes and changes to the hierarchy structure of a scenario (i.e. actions moved to another folder, folders dragged to another position, folders deleted or added) can be undone and redone. Cut/Copy/Paste Actions and folders support the usual cut, copy and paste operations. An action/folder that is copied or cut from one scenario tab page can be pasted onto the tab page of another scenario. Activate/Deactivate Activate or deactivate the selected action. Only available if a simulation is running. Properties Start the editor for the selected action.

Delete Delete the selected action or folder. The action or folder is not placed in the clipboard and thus cannot be pasted. Edit Scenario Caption Change the caption of the scenario tab page. Delete Scenario Tab Page Delete the scenario tab page. You will be asked to confirm this operation.

The following Edit menu items are available in the scenario tab page: Show Icon View Toggle between the tree view and the icon view of the scenario. Rearrange Icons Icon view specific: rearrange the icons of the scenario.

Up Icon view specific: by double clicking on a folder you move down in the action hierarchy. This menu item moves the icon view to one level up the action hierarchy.

The following Insert menu items are available in the scenario tab page: New Recorder Create a new recorder action. See Section 12.10.3.2 for more information. New Stimulus Create a new stimulus action. See Section 12.10.3.3 for more information. New Script Create a new script action. See Section 12.10.3.1 for more information.

152 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

New Folder Create a new folder called New Folder followed by a unique number. You can immediately edit the generated folder name and change it to something more appropriate.

The following Control menu item is available in the scenario tab page: Execute Action Execute the selected action. Only available when the connection to the simulator is active.

The following Tools menu items are available in the scenario tab page: Commandline Script Quickly enter an action script and execute it. Only available if there is a connection to a simu- lator. Convert Old Monitors Convert all monitor actions in this scenario to a new MMI tab page. You are asked for the file name of the new .mmi file, the caption for the new tab page and if you want to delete the old monitors after conversion.

12.10.2 Context menus Two context menus are available in the Scenario tab page depending on where you click the right mouse button. If you click on an action item in the tree then a context menu with the following items appears (see Section 12.10.1 for a description of the menu items):

• Properties

• Activate

• Deactivate

• Execute Action

• Delete

• Cut

• Copy

• Paste

• Undo

• Redo

The other context menu appears when you click outside the tree area to the right of the last column or below the last row (see Section 12.10.1 for a description of the menu items):

• New Recorder

• New Stimulus

• New Script

• New Folder

• Up

• Paste

• Undo

c Airbus Defence and Space 153 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• Redo

• Rearrange Icons

• Edit Scenario Caption

• Delete Scenario Tab Page

12.10.3 Action Editor The Action Editor allows for the creation and modification of action objects, as they are used in the Simulation Controller. For each of the three possible action types, a variation of the Action Editor is used. A number of elements are shared amongst all editor variations, and these are described in the section on script actions (Section 12.10.3.1).

All actions are ultimately defined in MDL and handled at run-time in the same way. The provision of the Action Editors is to allow the most common types of actions to be created with the minimum knowledge of MDL syntax.

12.10.3.1 Script Action Editor The script Action Editor is shown in Figure 12.21.

Figure 12.21: The Script Action Editor

The window consists of several parts, each part corresponding to an element of an action, as described in Section 12.2.2. In the first three parts, the following attributes can be entered: Action name This is the name of the action as it appears in the tree or icon view. It should be a unique name within the current scenario. Description A description of the action.

154 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Global & Active States These options are used to indicate whether the action should either be active or inactive when the scenario is started; as well as in which of the four simulation states the action should be active. ActionMgr Nr This attribute allows you to specify on which action manager this action will be executed.

The next part of the window is a text entry area where the execution condition of the current action can be specified. The execution condition is specified using the Mission Definition Language (see Chapter 23). The final part of the window is another text entry area in which the actual action script can be entered. The Check script button can be used to check whether or not the entered MDL scripts are syntactically correct.

The MDL Keywords button will pop up a small window with a list of all available MDL commands. With the Add to Clipboard button (or by double clicking on a command) you can copy the command to the clipboard and paste it in the Condition or Action text entry areas. The Events button will show a window with all input connectors from the schedule. With the Add to Clipboard button (or by double clicking on an events) you can copy the events to the clipboard and paste it in the Condition or Action text entry areas. If no user defined input connectors are found, then this button will not appear. Any errors that are detected in the condition or action text will appear in the Errors area at the bottom of the window. The left hand side of the window contains a Dictionary Browser (see Section 12.9) that you can use to drag and drop variables from the dictionary to the condition or action text areas. You can select more than one variable and they will be inserted into the text as a list of variables, one per line. Besides drag and drop you can also double click on a variable to add it at the current cursor position, or use the Add Variable button to add all selected variable at the current cursor position.

12.10.3.2 Recorder Action Editor The recorder Action Editor consists of two tab pages. The editor with the first tab page (Variables) on top is shown in Figure 12.22. The second tab page (Script) is the same as the script Action Editor window (Figure 12.21) except for an extra checkbox Manual. When checked the Condition and Action text areas can be edited, and the entry fields in the Variables tab page cannot be edited. When unchecked the situation is the other way around.

c Airbus Defence and Space 155 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.22: The Recorder Action Editor

It should not be necessary to check the Manual checkbox when building simple recorders. For more complex recorders you could start with the Variables tab page, fill in all the fields, switch to the Script tab page, check the Manual checkbox and then customize the condition and action. In the Variables tab page, the following information can be entered to define a recording action. Action name and Description As for the script action attributes. Recorder File The name of the file in which the recorded variable values should be stored. The default file name is actionname.rec. Frequency, Start Time and End Time The three attributes specify when the recording should start and stop, and with what sample rate the variable values should be written to the file. Note: if UTC is selected times should entered as YYYY-mm-dd HH:MM:SS[.sss], e.g. 2001-12-31 16:01:02.400. Switch Per. A switch period can be specified to indicate that the recorder should switch periodically. This value can be given in units of seconds or in units of hours. After each elapsed switch period recorder actionname-nnn.rec is closed and recorder actionname-nnn + 1.rec is opened (where nnn is the switch counter). Below these attributes the Recorded Variable listbox is shown. If any variables were added from the Dictionary Browser (see Section 12.9), they are shown here. Variables can be added using drag and drop, by double clicking on a variable in the Dictionary Browser, or by selecting variables in the Dictionary Browser and pressing the Add button to add them. To remove a variable from the list, select it, and press the Remove button. You can change the order of the variables by selecting variables in the listbox and using the Up and Down buttons. The values of the variables in the list are recorded into the specified file at the specified frequency. EuroSim automatically generates an MDL-script for this purpose, which can be viewed in the Script tab page. If you want to use a non-numerical start or end time you can change the values manually in that tab. For example, you can use a simulator variable as the end time.

156 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The created .rec files can be converted to ascii with the r2a utility, as well as from ascii to the binary rec file format with a2r. A utility recdiff is available to compare rec files. See the man pages or ICD document for more details on these utilities.

12.10.3.3 Stimulus Action Editor When the stimulus editor is started you will be asked to select a stimulus file. You can select both a .stim file or a .rec recorder file. The stimulus Action Editor consists of two tab pages (see Figure 12.21 and Figure 12.22). The Script Action Editor tab page (see Figure 12.21) is identical for both cases. The first stimulus Action Editor tab page (see Figure 12.22) has the following fields:

Figure 12.23: The Stimulus Action Editor

Stimulus File This should be the name of the input file containing the stimulus data.4 You can use the Browse button to select an input file. Frequency, Start Time and End Time The three attributes specify when the stimulus should start and stop, and with what sample rate the variable values should be read from the file. Note: if UTC is selected times should entered as YYYY-mm-dd HH:MM:SS[.sss], e.g. 2001-12-31 16:01:02.400. Variables If any variables were added from the Dictionary Browser (see Section 12.9), they are shown here. Variables can be added using drag and drop, by double clicking on a variable in the Dictionary Browser, or by selecting variables in the Dictionary Browser and pressing the Add button to add them. To remove a variable from the list, select it, and press the Remove button. You can change the order of the variables by selecting variables in the listbox and using the Up and Down buttons. 4Note that this action editor can only be used to make stimuli actions which read in data from an external source. To update a variable using a function (e.g. to feed a sinusoidal value), this needs to be defined using a script Action Editor with e.g. varZ = sin(varX).

c Airbus Defence and Space 157 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Stimulus Variables The variables you add to the Variables list must match with the variables from this list. This list is extracted from the selected stimulus file. The variable types are shown in both lists and in the Dictionary Browser. This makes it easier to find a match. If the Variables list is empty when a stimulus file was selected, then the program tries to prefill the Variables list with correct matches.

Mode This can either be set to soft, hard or cyclic. With the first option, the data in the stimulus file is read in sequential order at the specified frequency, and the timestamps attached to the data are ignored. With the second option, only those data from the file are used whose timestamp match the current simulation time (or has the nearest elapsed time) when the data is requested. Data between these points are ignored. With the third option the data in the stimulus file is read in sequential order and after the last data point read, the stimulus file is reread from the beginning. These stimuli data is applied in ‘soft’ manner.

Consider the following input data file: Data file:

simtime data 0.9 10 1.9 15 2.9 17 3.9 19 4.9 20 5.9 18 6.9 15 7.9 15 8.9 14 9.9 12

If the stimulus action is to update variable ‘Z’ at a frequency of 0.5 Hz, and the stimulation mode was set to soft, then ‘Z’ would be updated as follows, i.e. every 2 seconds the next value is used from the file: Simulation:

simtime Z 0 10 2 15 4 17 6 19 8 20 10 18 12 15 14 15 16 14 18 12 20 no more data

If the stimulus actions is to update variable ‘Z’ at a frequency of 0.5 Hz, and the stimulation mode was set to hard, then ‘Z’ would be updated as follows, i.e. every 2 seconds the most ‘up-to-date’ value is used from the file: Simulation:

simtime Z 0 0 2 15 4 19

158 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

6 18 8 15 10 12 12 no more data

If the stimulus action is to update variable ‘Z’ at a frequency of 0.5 Hz, and the stimulation mode was set to cyclic, then ‘Z’ would be updated as follows, i.e. every 2 seconds the next value is used from the file, and when there is no more data, the data from the file is used again: Simulation: simtime Z 0 10 2 15 4 17 6 19 8 20 10 18 12 15 14 15 16 14 18 12 20 10 (start from the beginning) 22 15 etc.

12.11 MMI tab page

For each .mmi file a separate MMI (Man-Machine Interface) tab page is created. When the .mmi file is opened or created you will be asked to provide the caption that appears as the name of the tab page.

The MMI tab page is a large pane on which you can place monitors to monitor variables in the simulation. There are two basic types of monitors: alpha numerical, i.e. each variable is presented as a caption followed by the value, and graphical, where each variable is tracked over time (or possibly against another variable) and plotted on a canvas. See Figure 12.24 for an example. Besides monitoring variables you can also add Action Buttons to execute MDL scripts or to enable/disable recorders or stimuli or add user defined plugins that act like monitors.

c Airbus Defence and Space 159 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.24: The MMI tab page

When you select a monitor by clicking on the monitor window with the left mouse button a rectangle with ‘grab handles’ appears. By clicking on the handles and moving the mouse around (keeping the left mouse button pressed) you can resize the monitor. If you click inside the rectangle and move the mouse around you can move the monitor to another place. You can insert a new monitor by using the Insert:New Monitor menu item or by double clicking in the MMI tab page. Double clicking on a monitor will open the Properties window where you can modify the properties of that monitor. You can insert a new user defined monitor (custom plugin) by using the Insert:New Plugin menu item. Double clicking on plugin monitor will open the Properties window where you can modify the properties of that plugin. You can insert a new action button by using the Insert:New Action Button menu item. Double clicking on an action button will open the Properties window where you can modify the properties of that action button.

12.11.1 Menu items

The following Edit menu items are available in the MMI tab page: Undo/Redo When a monitor or action button is resized, moved, or properties are changed then those changes can be undone and redone. Cut/Copy/Paste Monitors and action buttons support the usual cut, copy and paste operations. A monitor or action button that is copied or cut from one MMI tab page can be pasted onto the tab page of another MMI. You can also (as a special case) copy or cut an old monitor action from a scenario tab and paste it onto an MMI tab page. The reverse is not possible since monitor actions are obsolescent. Properties Edit the properties of the selected monitor or action button.

160 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Copy to Desktop Copy the monitor or action button as a floating window on the desktop.

Edit MMI Caption Change the caption of the MMI tab page.

Delete MMI Tab Page Delete the MMI tab page. You will be asked to confirm this operation.

The following Insert menu items are available in the MMI tab page: New Monitor Create a new monitor. See Section 12.11.4 for more information. New Plugin Create a new plugin. See Section 12.11.5 for more information. New Action Button Create a new action button. See Section 12.11.3 for more information.

12.11.2 Context menus

Two context menus are available in the MMI tab page depending on where you click the right mouse button. If you click on a monitor or action button then a context menu with the following items appears (see Section 12.11.1 for a description of the menu items): • Properties • Copy to Desktop • Delete • Cut • Copy • Paste • Undo • Redo The other context menu appears when you click directly on the tab page background (see Section 12.11.1 for a description of the menu items): • New Monitor • New Action Button • Paste • Undo • Redo

• Edit MMI Caption

• Delete MMI Tab Page

• Activate MMI Tab Page

• Deactivate MMI Tab Page

The latter two menu items, Activate MMI Tab Page and Deactivate MMI Tab Page, are short-cuts to the Activate and Deactivate menu items that are available in the Edit menu of the Input Files tab page (see Section 12.7.1).

c Airbus Defence and Space 161 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

12.11.3 Action Button Editor

The Action Button Editor (see Figure 12.25) allows you to add a button or checkbox to the MMI pane to execute MDL scripts or enable/disable recorders or stimuli. The editor has the following properties: Caption This is the text that you want on the button/checkbox. If left empty, then the name of the action is used instead. Scenario Choose the scenario containing the action that you want to use.

Action Choose the action from the scenario selected above.

A script action will now appear on the MMI tab as a button. Pressing the button when simulator is running will execute the action. Recorders and stimuli appear as a checkbox. When checked the recorder or stimulus is active, when unchecked it is not active. Toggling the checkbox will activate/deactivate the recorder or stimulus. See Figure 12.24 for an example.

Figure 12.25: The Action Button Editor

12.11.4 Monitor Editor The monitor editor is similar to the recorder Action Editor (see Figure 12.22) in terms of overall layout, but there are still many differences. Nevertheless, as can be seen in Figure 12.26, the basics are the same: on the left hand side is the Dic- tionary Browser (see Section 12.9 for more information), on the right hand side is a Variables list and in between are buttons to add to, remove from and rearrange the variables in the list. If you try to add an array or structure that contains more than 10 elements you will be asked if this is really what you want. Since structures and arrays are expanded in the Variables list to their constituent variables this prevents against the accidental selection of large arrays or structures. A monitor of more than 10 variables is generally not very useful. There are two property areas in the editor: the properties above the Variables list are properties of the monitor as a whole, the properties below the list are properties of the currently selected variable in the Variables list.

162 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 12.26: The Monitor Editor

12.11.4.1 Monitor Properties The following properties are always available: Caption Enter the caption of the monitor.

Style Select the style of the monitor. The following styles are available: Alpha Numeric Give a textual representation of the value of a variable. Plot against Simulation Time Use the value of the variable as the Y-axis value and the simulation time as the X-axis value. Plot against Wall Clock Time Use the value of the variable as the Y-axis value and the wall clock time as the X-axis value. XY-Plot Use the value of the variable as the Y-axis value and the value of a designated other variable as the X-axis value.

Depending on the style some of the other properties in the monitor editor become enabled or disabled. For the Alpha Numeric style the Read Only checkbox in the variable properties area is only enabled if the variable is an input variable and the Format combobox is only enabled if the variable is not a string. For the plot styles all properties are enabled except for the Read Only checkbox and the Format combobox. The X-Axis Variable combobox is only enabled when the XY-Plot style is selected. The following properties are available when one of the plot styles is selected:

History This value indicates how many samples of each variable should be simultaneously displayed. Once the maximum is reached, the older values will be discarded. Manual scaling This checkbox can be checked if the user wishes to specify the minimum and maximum values for the axis.

c Airbus Defence and Space 163 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Minimum The minimum value for the corresponding axis. Maximum The minimum value for the corresponding axis. Rotation The rotation of the labels on the corresponding axis.

The following property is available when the XY-Plot style is selected: X-Axis Variable Select a variable from the Variables list that provides the X-Axis variable values.

12.11.4.2 Variable properties The variable properties are disabled if no variable is selected in the Variables list. Otherwise they change the representation of the selected variable. The following properties are available when the Alpha Numeric style is selected:

Format Allows you to enter an optional formatting string using the printf style, see Section 12.11.4.3. The drop down list box gives you a few suggestions for representing integer values as hexadec- imals. Read Only If checked, then this variable cannot be modified in the monitor.

label Allows you to enter an optional label to be displayed in the monitor instead of the name of the selected variable

During a simulation run, an alphanumeric monitor can be used as a mechanism for updating the value of the variable(s) it is displaying. You just need to type a new value into the field and press Return. If the Format field specifies a conversion, f.i. to hexadecimal, then you must also enter the value in that format. For traceability, this update event is logged. Read-only variables cannot be edited and are displayed as text instead of an edit field. If the variable is a parameter, then that variable is always read-only. The following properties are available when a Plot style is selected: Show Line If checked, connect the data points in the plot with a line. Line Color Press the Select. . . button to select the color for the line.

Symbol Choose a symbol to be used for each data point. Symbol Color Press the Select. . . button to select the color for the symbol.

label Allows you to enter an optional label to be displayed in the monitor instead of the name of the selected variable

12.11.4.3 Variable formatting and conversion The Format field of the Variable properties allows formatting and/or conversion of the monitored vari- able. When this field is left blank, then a default formatting will be applied that is appropriate for the type of the variable. The Format field supports a sub-set of the format string as specified for the printf function, see the printf(3) man page for more details. The following length modifiers are supported: h (short int or unsigned short int), ll (long long int or unsigned long long int). Make sure that the length modifier matches the type of the model variable in

164 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

the simulator. You can retrieve the variable type by pressing the right mouse button on the variable in the Dictionary Browser and selecting the Info menu item in the context menu. Variables of type int, long int, float and double do not need a length modifier in the format string (note that int and long int are the same on 32-bit platforms). The following conversion specifiers are explicitly not supported: c (character) and s (string). Table 12.1 gives a few examples of formatting and conversion of monitored variables. Note that conver- sion to/from hexadecimal values can only be done on integers, while formatting of floating point numbers only works on float and double types.

Value in simulator Format Result in monitor 255 %X FF 255 %08X 000000FF 255 0x%08X 0x000000FF 3.141592 %.2f 3.14 3000 %.2E 3.00E+03 Table 12.1: Examples of formatting and conversion.

12.11.5 User-Defined Monitors (Plugins)

To accommodate the need to add user-defined monitors to the MMI tab page, it is possible to load custom plugins. These are added as shared libraries during runtime. Section 12.11.5.1 describes the general use of these plugins in the Simulation Controller and explains where example code can be found and how it should be used. Furthermore it describes in more detail what has to be done to implement a plugin and what functionality can be used.

12.11.5.1 Loading Plugins

A plugin can be added to the MMI by using the insert menu or the right click context menu. A dialog will ask for a shared library file to be selected. Three examples ar eavailable in the EuroSim lib/MMIPlugin directory. The (pluginDedicatedMonitor is a simple example that shows how to make a dedicated mon- itor using QT widgets for specific dictionary variables. The (pluginThermo and pluginKnob) are more advanced as they also provide a dialog to select variables as for the Simulation Controller monitor wid- gets. These more advanced examples use QWT widgets, an opens source library of advanced widgets based on QT for dials, sliders etc.

12.11.5.2 Programming Plugins The source code for the provided examples can be found in the EuroSim src/MMIPlugin directory. Plu- gins are written in C++ and use the Qt library. These are mandatory for plugin development. Every plugin will have to include two header files, which are located in the EuroSim include directory. scUserPluginInterface interfaces the plugin with the Simulation Controller. All abstract functions of this header file need to be implemented in the plugin code scMonInterface interfaces the Simulation Controller with the plugin. This header file contains methods the plugin can use to interact with the Simulation Controller and the simulation model. scUserPluginInterface contains three abstract methods and one extern function.

c Airbus Defence and Space 165 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

scUserPluginInterface::update This method handles update requests by the Simulation Controller. Whenever an update request is sent, this method should update the variables and show them on the screen. scUserPluginInterface::refresh This method is called to paint the monitor when the monitor is constructed or when the simula- tion is not running. It will usually just contain the paint instructions. scUserPluginInterface::editProperties This method is called when the user requests the properties menu. The minimum functionality of this dialog should be to select variables. CreatePlugin t This function type is used by the Simulation Control to create a plugin and get a pointer to the object. Without it, the Simulation Controller will not be able to build and control the plugin. DeletePlugin t this function type is used by the Simulation Control to delete a plugin. Without it, the Simula- tion Controller will not be able to properly delete the plugin.

The actual plugin can use several methods to communicate with EuroSim. This way Variables can be requested, values changed, names set, etc. These methods are available through scMonInterface.h. Detailed descriptions are given in the header files itself.

changeValue Change the value of a variable in the model. getValue Request the value of a variable in the model. setVarlist Set the list of used variables. getVarlist Request the list of used variables. parentWidget Request the parent widget of the plugin. dictWidget Request a variable selection dialog. getPluginPath Request the path to the shared library setCaption Set the caption of the plugin monitor getCaption Request the caption of the plugin monitor addProperty Add a custom property. readProperty Request the value of a property. clearProperty Clear all custom properties. Usefull to rebuild the list. deleteProperty Remove a single property.

166 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

An example makefile for each plugin example is provided. They are called plugin.make and placed with the source code. These should help the user to quickly generate their own makefile for building, installing and testing their plugin. After a plugin is compiled to a shared library, it can be tested for basic loading functionality. For this purpose a small program called pluginTest can be used. It is located in the EuroSim src/MmiPlugin directory. It requires the path to the shared library as an argument.

12.12 Message tab pane

All the messages from the simulator are logged in the message tab pane. By default there will be only one message pane without tabs. However, additional message tabs can be created in order to customize the logged messages (see Figure 12.27). Message logging can be customized by creating message filters which can be created by choosing a combination of different message types. Message types could be either EuroSim defined (by default) or user defined message types you created in your currently running simulation.

Figure 12.27: The Simulation Controller with message tabs

A new message tab can be created either by choosing Insert:New Message Tab menu item or by double clicking on the empty space (to the right of the last message tab) in the Tab header. A dialog box to edit the message tab properties appears (see Section 12.12.1). Note: i) The message tab with title ”Default” is the default message tab. This title does not appear if this is the only message tab. ii) The default message tab cannot be edited or deleted. However, the messages can be copied and cleared if necessary.

12.12.1 Editing message tab properties The dialog box to edit the message tab properties has the following fields:

c Airbus Defence and Space 167 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 12.28: Message Tab Properties Dialog

Name Enter the name of the message tab (which appears in the tab header). Message types A list of all message types in the model, in the currently running simulation session and the built-in EuroSim defined message types (message, warning, error and fatal). If a message type appears in gray color it means either a simulator is currently disconnected (not running) or that the message type is not defined in the currently running simulation session. Even if some message types appear gray, they can be selected to create a message filter.

Inverse Check this check box to indicate that the selected message type messages should not be logged in this message tab.

12.12.2 Menu Items The following Edit menu items are available when a message tab page is in focus: Copy Copy the selected message in the currently visible message tab pane to the clipboard. Copy All Messages Copy all messages in the currently visible message tab pane to the clipboard.

Delete Delete the currently visible tab pane. Message Tab Properties... Change the properties of the currently visible message tab. A dialog box to edit the message tab properties appears (see Section 12.12.1). Undo/Redo Undo/Redo a message tab deletion.

12.12.3 Context menus If you click the right mouse button anywhere on the message tab pane the following items appear (see Section 12.12.2 for a description of the menu items): • Copy

• Copy All Messages

• Clear Log

• New Message Tab...

• Message Tab Properties...

168 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• Delete

• Undo

• Redo

12.12.4 User defined message types

You can create your own message types using the EuroSim library function esimReportAddSeverity() in your simulation (see ??. When you initialize the simulator, all the message types that you have created appear in the message tab properties dialog box.

c Airbus Defence and Space 169 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

170 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 13

Test Analyzer reference

The Test Analyzer can be used to create and display plots of the generated test results. It uses PV- WAVE1 or gnuplot to display and print the plots. For most plots the user interface of the Test Analyzer is sufficient, but it is also possible to send commands to the PV-WAVE or gnuplot back-end directly. The purpose of this chapter is to provide a detailed reference of the Test Analyzer. The first part of this chapter describes how to start and use the Test Analyzer (Section 13.1- Section 13.2). The second part can be used for reference (Section 13.4- Section 13.7).

13.1 Starting the Test Analyzer

The Test Analyzer can be started by selecting the Test Analyzer button in the EuroSim start-up window (see Figure 6.1). The Test Analyzer can also be started from the command line by issuing the TestAnalyzer command.

13.2 Using the Test Analyzer

The next sections describe how the Test Analyzer can be used without going into too much detail. For a complete description of a particular part of the user interface please refer to Section 13.4- Section 13.7.

13.3 Test Analyzer main window

The main window of the Test Analyzer is shown in Figure 13.1. The main window contains the following elements: 1Not supported on the Windows platform.

c Airbus Defence and Space 171 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 13.1: The Test Analyzer main window

Menu bar For a detailed description of the menu items see Section 13.7.

Toolbar A description of the action the toolbar button performs is displayed if the mouse is left above the button for a short period of time. The toolbar provides a shortcut to many often used menu items like undo, redo, add plot, etc. Plot view The plot view holds the icons representing the plots that are defined. Variable browser The variable browser contains the variables found in the test results that are loaded. You can use these variables to create or edit curves in the plots. Plot properties The plot properties pane contains three tabpages. The first page deals with the general plot properties like plot title and description. The second page is dedicated to the curves of the plot (curve editor). The third page is used to change axes related settings like scaling (linear/loga- rithmic) and axis range. Statusbar The status bar displays the location of the currently loaded test results file on the right. The rest of the statusbar is used to show short (status) messages.

13.3.1 Opening a plot file The Test Analyzer works with plot files. A plot file contains one or more (often related) plots. Previous versions of the Test Analyzer worked with plot definition files (pdf). This file format is no longer in use. Instructions on how to convert old pdf files can be found in Section 13.3.2. To open a plot file, select File:Open. . . from the menu or click on the button on the toolbar. The plot view now shows the plots defined in this file. To be able to show the plots, test results need to be loaded as well.

172 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

13.3.2 Importing old plot definition files

To import old plot definition files, select File:Open. In the dialog that appears, select the “Plot definition files (*.pdf)” from the file filter selection area (see picture below).

Figure 13.2: Importing plot definition files. Click on the “File type” combobox to switch between file formats.

Next, browse to the plot definition file that needs to be imported and click on the OK button. A warning message will appear stating that the pdf file will be converted. Press OK to convert the pdf file. The Test Analyzer now contains the converted data. If you wish you can save the converted file with File:Save or with File:Save As. . . in case you wish to save the file under a different name.

13.3.3 Selecting the test results file Plots cannot be shown until a matching set of test results is loaded. A matching set of test results is a test results file that contains the same variables as used in the plot(s). If the selected test results do not match (some of) the plots, these plots will be marked with a big red X. To select a test results set, select File:Select Test Results File. . . and the test results file will be loaded into the variable browser. It is not possible to have multiple test results files selected at the same time.

13.3.4 Using recorder files Usually, the recorder files used are the ones related to the selected test results file. Plots use the data from that specific test results set. Sometimes however, it is desirable to be able to create a plot from a specific recorder file. For example, to compare the results from a certain test run to a reference run. This can be achieved by adding recorder files to the variable browser (File:Add Recorder File. . . ). Curves created with variables from this specific recorder file always display with the data in that specific recorder file. Switching test result files has no effect on these curves. The variables in the curves from such a manually inserted recorder file are labeled with “[A]” (absolute).

13.3.5 Creating a new plot

To create a new plot, either select Plot:New Plot to create an empty plot or select Plot:Add Plot Wizard. . . to start the wizard that will guide you through the various needed steps to create a plot from information you provide.

c Airbus Defence and Space 173 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

13.3.6 Changing a plot A plot is changed using the plot properties part of the user interface. To show the plot properties select a plot on the plot view and choose Plot:Properties. . . Adding curves Curves can be added to a plot in many ways. The easiest way is to use drag and drop. Select the variables you would like to add as curves in the variable browser and drag them to the curve editor or on the desired plot icon in the plot view. More information can be found in Section 13.4.2. Changing curves To change a curve or one of its properties, click on it in the curve editor. An edit field will appear depending on where you clicked. For example, clicking the variable name in one of the curves axis will show a selection box with the variables used (or recently used) in the plot. A more detailed list of the possibilities can be found in Section 13.4.2 Removing curves To remove a curve, select it in the curve editor and press the delete key, use the toolbar or menu ( Curve:Remove Curve). Changing other plot settings General plot settings can be changed on the “General” tab page of the plot properties area. This in- cludes settings like plot title, description, legend position etc. A more detailed list can be found in Section 13.4.1. Settings related to the axes like scaling and range can be changed on the “Axes” tab page of the plot properties area. Detailed information can be found in Section 13.4.3

13.3.7 Showing and printing plots After a plot has been properly set up it is shown by selecting Plot:Show Plot from the menu (or double- click the plot icon). A new window appears containing the plot. If gnuplot is selected as the plot back-end, the window can be closed like any other window or by selecting Plot:Close Plot from the menu. If PV-WAVE is the current back-end the window can only be closed by selecting Plot:Close Plot from the menu. To print one or more plots, select them and choose File:Print. The print dialog appears.

Figure 13.3: Printing plots.

It is possible to print to the printer or to print to file(s). Printing to the printer will print each plot on a separate page, while printing to file will print each plot in a separate file.

13.4 Plot properties reference

The next three sections describe the plot properties area. This area can be used to alter the plot’s proper- ties. It is divided into three parts: general properties, the curve editor and the axes properties.

174 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

13.4.1 General plot properties Figure 13.4 shows the tab page with the general plot properties.

Figure 13.4: General plot properties.

Plot title The title of the plot is shown on the plot view as well as on the plot itself. Plot description This can be a more elaborate description of the plot and is shown on the plot. Legend position The legend is placed on the specified position. Simulation time The simulation used in the plot can be set to either all data or to a specified time range.

Grid To display a grid check the “Show grid” option. Optionally, a grid style can be entered. The effect of the grid style depends on the back-end. In gnuplot for example, this influences the line style of the grid.

Note that the apply button must be pressed after you have made your changes.

13.4.2 Curve editor reference The curve editor is the tool to make, change or remove curves from a plot. It displays the curves of the plot selected on the plot view.

Figure 13.5: The curve editor.

c Airbus Defence and Space 175 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

About curves As shown in Figure 13.5, a variable or function must be specified for the X and Y in each curve2. Some of the fields in the curve editor can be edited by clicking them. For example, to change the line style of a curve click on the last column of the curve’s row and type in the desired style. Legend text The legend text can be specified manually by typing in a legend text or it can be generated automatically. In that case, one of these formats can be chosen:

• variable name • variable path • variable description Line style The effect of the line style depends on the back-end and the output media (screen or printer). With gnuplot, for example, the decimals specify the linetype as specified in the gnuplot doc- umentation and the hundredths specify the style. Up to nine gnuplot styles are supported. Example: the value “100” will give you the gnuplot “points” style. Variable The axis variable can be changed in two ways. The drop-down list contains the recently used variables in this plot and can be chosen the normal way. It is also possible to drag a variable from the variable browser and drop it on the desired axis.

Axis The axis can be set to “Primary” or “Secondary”. The primary axis is on the left for X and at the bottom for Y. The secondary axis is the right axis for X and the top axis for Y. Adding curves Curves can be added in many ways:

• Double click a variable in the variable browser. The selected variable is added as a curve. Initially, the variable is plotted against simulation time so do not forget to change this if necessary.

• Drag the variables selected in the variable browser to an empty spot of the curve editor. If there is a variable with “time” or “x” in its name it is used as the x-axis variable. The curves created are all other variables plotted against this curve (or against the first variable if no such variable could be found). This is probably the easiest method.

• Select Curves:Add Curve from the menu. The result is the same as dragging the selected variables from the variable browser to the curve editor.

13.4.3 Axes properties The plot’s axes can be configured with the last tabpage. Figure 13.6 shows this tabpage. On the left the axis can be selected. On the right, the settings for the current axis are shown.

2This is different from previous versions of the Test Analyzer, where there could be only one x-axis variable or function in a plot.

176 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 13.6: Axes properties.

The axis properties that can be set include axis range, scale and label. “Automatic axis range” calculates a default range from the data values. “Automatic axis label” creates a default label for the selected axis based on the variable names.

13.5 Variable browser reference

The variable browser displays the variables present in the currently loaded test result and recorder files. By default, all nodes are collapsed. To expand all nodes to the variable level, right-click the variable browser and choose Expand All Nodes.

Figure 13.7: The variable browser.

The variable browser has two columns. The first column contains the variables, the second column contains the variable descriptions.

13.6 Plot view reference

The plot view shows all defined plots. The plot view can be switched between three modes:

• Large icons

• Small icons

• List

c Airbus Defence and Space 177 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 13.8 shows the default large icons.

Figure 13.8: The plot view.

In small icons and list mode, the plot icon is small and the plot title is shown right of the icons instead of below them. The difference between small icons and list mode is the order of display. In small icons mode the icons are ordered left to right while in list mode the icons are ordered top to bottom.

13.7 Menu items reference

The next sections describe each of the menus and their menu items. Some of these menu items also have a toolbar button that performs the same action. These are described in Section 13.8.

13.7.1 File menu New Starts a new, empty .plt file.

Open. . . Opens an existing .plt file. Can also be used to import old .pdf files.

Save Saves the current .plt file. Save As. . . Saves the current .plt file under the specified name.

Close Closes the current .plt file. Asks to save changes if there are unsaved changes.

Select Test Results File. . . Switches the current test result set (.tr file). The variables used in the plots must be present in the new test results file, otherwise (some of) the plots will be marked as invalid. See also Section 13.3.3. Add Recorder File. . . Adds a recorder file to the current test results. See also Section 13.3.4 for more information about this feature. Close Recorder File Closes the recorder file selected in the variable browser. This is only possible for recorder files added with File:Add Recorder File. . . Print. . . Prints the selected plots. Recent files The four most recently used .plt files can be opened quickly from here.

Exit Exits the program. Asks to save changes if there are unsaved changes.

178 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

13.7.2 Edit menu Undo Undoes the last action if possible.

Redo Redoes the last undone action if possible.

Cut Cuts the selected item from the document and places it on the clipboard.

Copy Copies the selected item from the document and places it on the clipboard.

Paste Inserts the item on the clipboard into the document.

13.7.3 View menu Toggle Variable Browser. . . Shows/hides the variable browser. Large icons Toggles the plot view to large icon mode. The icons are large, the plot title is shown below the icon and icons are initially placed right to left.

Small icons Toggles the plot view to small icon mode. The icons are smaller, the plot title is shown next to the icon and icons are initially placed right to left.

List Toggles the plot view to list mode. The icons are small, the plot title is shown next to the icon and icons are initially placed top to bottom.

13.7.4 Plot menu Add Plot Wizard. . . Starts the wizard. The wizard allows you to create a plot step by step. All information needed to create a plot is gathered in several pages.

New Plot Creates a new, empty plot.

Delete Plot(s) Deletes the plots selected on the plot view. Show Plot(s) Shows the plots selected on the plot view. Close Plot Window Closes an open plot window for the selected plot. If you are using gnuplot the plot window can also be closed as usual. However, if you are using PV-WAVE you must close the plot window this way.

Print. . . Prints the selected plots.

Add Selected Variables as Curves Adds the variables selected in the variable browser as curves to the current graph. If a variable is found containing ‘x’ or ‘time’ it is used as the X-axis variable. Otherwise, the first variable is used as the X-axis.

c Airbus Defence and Space 179 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Edit Functions Shows the function editor dialog box for this plot. It contains all variables and user defined functions for this plot. Properties Shows/hides the plot properties area.

13.7.5 Curve menu Add Curve Adds a new curve to the current plot. See also the remarks in Section 13.4.2 about adding curves. Remove Curve Removes the current curve from the current plot.

13.7.6 Tools menu Select Plot Backend Shows a dialog in which the plot back-end can be selected. See Figure 13.9 below.

Figure 13.9: Plot back-end selection.

Plot Backend Interface Shows the interface to the plot back-end. The interface allows you to see the responses from the plot back-end and send commands to the back-end manually. See Section 13.10.1 or Sec- tion 13.11.1 for more information.

13.7.7 Help menu Online Help Starts the help browser. About EuroSim Shows a dialog with information about EuroSim.

13.8 Toolbar reference

Many of the menu items described in the previous section are also present on the toolbar. The toolbar provides shortcuts to these menu items as toolbar buttons. The toolbar is shown in Figure 13.10. A description of the action of each toolbar button is provided in Section 13.7. The icons on the toolbar are shown next to the menu items.

Figure 13.10: The Test Analyzer toolbar.

13.9 Using User Defined Functions

User defined functions can be specified in the function editor (see Section 13.9.1). How format and validation of these functions is handled is described in Section 13.9.2.

180 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

13.9.1 The function editor The function editor allows you to specify a function that uses one or more of the variables of the test results. The function editor is displayed if you select Plot:Edit Functions or if you press the “Add a function of variables” button in the curve editor.

Figure 13.11: The function editor.

By default, the function editor displays the variables already in use by the selected plot. If a variable is required that is not yet listed, it suffices to drag and drop the variable from the variable browser onto the function editor. To add a user defined function, type it in the edit field below the list and press the add button. User defined functions are added to the bottom of the list and are tagged as “func”. They can be edited by clicking on the function. An edit field will then appear. To use a function in a plot, drag and drop the function from the function editor to the desired axis of the desired curve in the curve editor. It is also possible to click on the variable or function field of the desired axis of the desired curve and then select the function from the list. Note that unused functions and variables are removed between sessions. That is, if you save the .plt file and load it again unused variables and functions are no longer listed.

13.9.2 Format and Validation The entry for the function is free format, allowing you to build functions using standard mathematical operators and expressions. To reference data from another variable (or from another user defined func- tion), refer to the reference tag shown in front of the variable (in the “Ref.” column), e.g. sin($1) will give the sine of the variable tagged as “$1” in the list. Functions are tagged as “func” in the list. Note that it is no longer possible to reference functions (i.e. it is no longer possible to nest functions). The function typed in is sent to the plot back-end “as is”. No checks are performed to see if the function is correct because each back-end has its own format for functions. If there is an error, then the plot will not appear when Plot:Show Plot is requested. Common errors are recognized and the plot back-end interface window will appear. Since not all errors are recognized, it is recommended that the plot back-end interface window is kept open when plotting user defined functions (at least for the first few times), so that any errors can be quickly identified and corrected.

c Airbus Defence and Space 181 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

13.10 PV-WAVE interface

Figure 13.12: The plot back-end interface window, showing PV-WAVE output.

13.10.1 PV-WAVE Operators and Functions There are many PV-WAVE functions which can be used; the main criteria is that the function should return an array. The following are examples of valid functions (assuming that the variables tagged with $1 and $2 exist in the list of variables).

• sin($1)

• $1 ˆ 2

• $1 * exp(0.1)

• $1 + (3 * $2)

• !Dtor * $2

The last example shows the use of the PV-WAVE system variable “deg to rad”; this and other possibilities are described in Section 13.10.2. PV-WAVE has various operators and functions available, including the following:

• * / + - ˆ

• sin, cos, tan, sinh, cosh, etc

• alog, alog10, exp, sqrt, abs

PV-WAVE Programmers Guide (Chapter 3): describes expressions and operators PV-WAVE Reference Volume 1 (Chapter 1): gives an overview of all the available routines; of particular relevance are the General/Special/Transcendental Mathematical Functions.

182 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

When referencing two vars within a function, e.g. “$4 - $6”, the function is applied in turn to each of the values within the two datasets, e.g. the difference between the first two values, and then between the second values and so on. In the case of the two datasets having different number of recording entries, then the function is applied until the smaller set of values is exhausted. Warning: a comparison of datasets produced by plotting $1 and $2 requires that /simulation time vari- ables3 from both of the source recording files are referenced, with the resulting comparison being actually an overlay of the two graphs, each using a separate time base. However, if you use a single diff function instead (e.g. $1 - $2) then only one timebase is possible. This is taken from the first file that is referenced (in this example, the $1/simulation time values). For this to give the intended result, the two datasets should have the same recording characteristics (i.e. have been recorded at the same frequency and be in “synchrony” (either due to the same timestamps within the recording, or because both recording files begin after the same event).

13.10.2 PV-WAVE Variables PV-WAVE has various system variables available, of which the following may be useful: • !Pi: The floating-point value of pi: 3.14159 • !DPi: Contains the double-precision value of pi: 3.1415927 • !Dtor: Contains the conversion factor to convert degrees to radians. The value is pi/180, which is approximately 0.0174533 • !Radeg: A floating-point value for converting radians to degrees. The value is 180/pi or approxi- mately 57.2958 PV-WAVE Reference Volume 2 (Chapter 4): gives an overview of all the available system variables (although the majority are concerned with plot appearances/defaults and are not relevant for function definitions).

13.10.3 Accessing recorded data After a plot has been activated, the plot back-end interface window will show the exact commands sent to PV-WAVE (in blue). If we inspect this output, we can see that the variables used in our plot ($1, $2, etc.) are available as V1, V2, etc. The dollar sign ($) of the variable reference is replaced with a “V”. We can access these variables in PV-WAVE as usual. For example, to check the number of data values for $1 we can give the command: info, V1 V1 DOUBLE = Array(307)

Which means that V1 is an array of 307 elements. To actually see the values in the array we could issue a print command: print, V1 0.0029616649 0.0059233298 0.0088849947 0.011846660 0.014808325 0.00092749497 0.0038891599 0.0068508248 0.0098124897 0.012774155 0.015670285 0.0018549899 ......

13.10.4 Examples of using PV-WAVE commands directly

PV-WAVE provides many options for presenting/filtering data. These can be used by typing the com- mands in the back-end interface dialog window and sending them to the PV-WAVE process. Some examples of the use of these commands on recorded data are presented below.

3It is assumed that simulation_time is used for the x axis variable, but it could be some other variable of course.

c Airbus Defence and Space 183 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

13.10.4.1 Creating a table To create a table of the data from a recorder file, the following commands could be used:

simtime = V1 temp1 = V2 temp2 = V5 temp3 = V6 tempTable = build_table("simtime, temp1, temp2, temp3")

Now, to select and display a subset of the data the following commands can be used:

subsetTable = query_table(tempTable, " * Where simtime > 10.0 and simtime < 12.0") print ,"time celltmp[1][1] celltmp[1][2] celltmp[1][3]" for i=0, N_ELEMENTS(subsetTable)-1 do begin PRINT, subsetTable(i)

This will result in output similar to:

time celltmp[1][1] celltmp[1][2] celltmp[1][3] { 10.005000 193.298 169.990 260.438} { 10.015000 193.298 169.990 260.438} ......

To export the selected data, and store it in a file (as ASCII), use the following command:

status = DC_WRITE_FIXED(‘table.’,subsetTable.simtime, subsetTable.temp1,subsetTable.temp2,subsetTable.temp3,/Col )

13.10.4.2 Data analysis

On the recorded data, analysis functions such as a Fast Fourier Transform (FFT) can be performed. An example would be:

xd = simtime yd = temp1 n_sample = N_ELEMENTS(xd) samp_rate = (n_sample-1)/(xd(n_sample-1) - xd(0)) x = FINDGEN(n_sample) - (n_sample/2.) x_ind = WHERE(x GE 0) x(x_ind) = x(x_ind)+1. x_freq = x * samp_rate/ FLOAT(n_sample) y_proc = ABS(FFT(yd, -1)) PLOT, x_freq, SHIFT(y_proc, n_sample/2.)

A FFT plot should then appear. Plots generated with the plot command can be removed again by using the command wdelete,0 (for plot number 0) Also, various statistical analysis functions are available through PV-WAVE. For example:

print, "min= ", min(yd) print, "max= ", max(yd) print, "mean= ", avg(yd) print, "median= ", median(yd) print, "std dev= ", stdev(yd)

184 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

13.10.5 User defined functions It is possible to define user defined functions which can later be used interactively in the dialog box which shows the interface with the plot back-end. To create a new user defined function you must first create a file containing the commands. From the Test Analyzer menu Tools:Shell.. . a shell window can be opened where you can create a file using your favorite editor. The filename should be the name of the function and the filename extension should be ‘pro’, e.g. user func.pro. Type the PV-WAVE commands in the file and save it. In the Test Analyzer select Tools:Plot Backend Interface. . . A dialog box appears where you then can enter your command in the Command box as follows: “.run user func”. Click Send to execute the command.

13.10.6 PV-WAVE help This can be accessed from the back-end interface dialog window by sending the command help.

13.10.7 The PV-WAVE process As soon as the current plot back-end is set to PV-WAVE, an attempt is made to start PV-WAVE. De- pending on the number of PV-WAVE licenses available in the local environment however, this might not succeed. If the start-up fails, then the user’s request for a license is placed in a queue. All the Test Ana- lyzer edit functions are still available however and the user can make/edit plot definitions as required: the only difference is that the “activate” (display graphical plot) request will not be immediately executed. If the Test Analyzer appears unresponsive to requests to display a plot, then the back-end interface window should be checked for this situation and/or other error messages.

13.11 gnuplot interface

Figure 13.13: The plot back-end interface window, showing gnuplot output.

13.11.1 gnuplot operators and functions According to the gnuplot documentation, the expressions accepted by gnuplot can be any mathematical expression that is valid in C, FORTRAN, Pascal or BASIC. The precedence of operators is the same as in the C programming language.

c Airbus Defence and Space 185 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The functions supported by gnuplot are about the same as those present in the UNIX math library. A complete list is available in the gnuplot documentation. Examples:

• sin($1)

• log10($3)

• $1**2 [this means $1 squared]

• $1 * exp(0.1)

• $1 + (3 * $2)

13.11.2 Accessing recorded data Showing a plot causes a temporary file to be written containing the variables used in the plot. This file will be deleted when the Test Analyzer is closed or when the back-end is set to something else than gnuplot. In the meantime, the data in this file remains accessible. The name of the data file can be obtained from the plot back-end interface window. After showing a plot, the name of the datafile is shown on the line containing the plot command, for example:

plot "/var/tmp/gnuAAAa0Y093" using ($1):(1.1 * ( $2 - 250 )) axes

x1y1 title "just a plot’’ with lines lt 0

The name of the file is shown in bold. The data can be accessed using gnuplot’s using command, as shown in the plot command above. See the gnuplot documentation for more information.

13.11.3 gnuplot help The gnuplot help interface can be accessed by sending the “help” command from the back-end interface window. Note that you should press enter a few times to leave help mode.

186 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 14

Dictionary Browser reference

This chapter provides details on the Dictionary Browser (DB). The menu items that are specific to the Dic- tionary Browser will be described in separate subsections of this chapter. For menu items not described in this chapter, refer to Section 5.6.

14.1 Introduction

The Dictiotnary Browser DB is a Graphical User Interface to view the contents of a EuroSim dictionary file. This content can also be viewed in the dictionary tab of the Model Editor and Simulation Controller. However these tools load the dictionary as part of a large set of information and have a more cluttered view as a result. It is therefore sometimes more convenient to use the Dictionary Browser for quick access to the dictionary items. An example is for instance for script developers to search for a variable and copy its path to the clipboard for use in other editors. Another benefit is that the Dictionary Browser only requires a runtime license whereas for instance the Model Editor require a developer license.

14.2 Starting the Dictionary Browser

The Dictionary Browser is started from the command line using

DictBrowser

The filename argument allows loading a dictionary file at startup and is optional. The same can be achieved through the File::open menu item after startup without file argument.

14.3 Working with the Dictionary Browser

After launch from the commandline, the Dictionary Browser GUI becomes visible. Figure 14.1 shows the dictionary browser after launch from the commandline without dict file argument.

c Airbus Defence and Space 187 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 14.1: Dictionary Browser after launch

The user can now use Open from the file menu to select a dictionary (.dict) file. Note that the dict file is created in the EuroSim build process and therefore ends up in the directory with generated files which is automatically names ., where is the same name as you model file and indicates the operating system platform, e.g. Linux.

Figure 14.2: Dictionary Brwowser file selection

After opening the file the Dictionary Browser shows the content of the loaded Dictionary as shown in Figure 14.3.

188 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 14.3: Dictionary Brwowser file selection

The usage of the Dictionary Browser is the same as in the dictionary tab of the Model Editor. Options for searching and selection of Operator versus Developer view are supported, as well as right clicking on dictionary items to either copy the path to the clipboard or to get more information on a dictionary item. (Note: the search button must be clicked, enter in the search box does not activate the search button.)

c Airbus Defence and Space 189 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

190 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part III

Modelling Reference Guide

c Airbus Defence and Space 191

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 15

C, Fortran, Ada interface reference

15.1 Introduction

The C, Fortran and ADA interface is the classic EuroSim modelling interface. The concept it is based on is to integrate code without modifying it using parser technology. The EuroSim parsers scan the code and extract type, variable and function (entrypoint) information. The user is provided a view of the variables and functions that can be used in EuroSim. The user can tag which of these variables and functions are to be visible in EuroSim, e.g. for scheduling or data viewing/manipulation. In addition he can add description, unit, and min/max information to the variable to give it more context. This information is stored as comment in a header of the file. When a simulator is build, the building process gather’s this information and stores it in a dictionary. When the simulator executable is started this dictionary must be extended with pointer information to allow EuroSim the access the data and functions during execution. EuroSim also automates this process by appending the file with code that publishes the functions and variables defined in the API. Note that because this has a file scope it can only do this for global variables and static variables with filescope. Static variables in functions can not be reached. Where the API header makes the functions and variables that provide the model API to EuroSim, Eu- roSim itself also provides an API to the models. EuroSim offers many services to the models, such as state managament, realtime recording, event management, scheduling interface functions etc. The ability to run these functions from the source code adds powerful capabilities to EuroSim. When used though the model code does become dependent on EuroSim. If portability is important, it is a good strategy to wrap these functions such that the model code depends on a defined interface that can have different implementation. This chapter first introduces the required setup activities to support Fortran And ADA. Users of the C interface can directly continue to the next section as the C interface is fully integrated because the EuroSim core itself is written in C. After the setup, section Section 15.3 provides an overview of the functions used to publish the API in the dictionary. Normally this is performed by the EuroSim parsers startes from the EuroSim ModelEditor, but if required these functions can be used directly by the user to integrate model functions and variables in EuroSim. Section Section 15.4 defines first the synopsis of the services offered by EuroSim to the model software for C, Fortran and Ada, followed by an elaboration of the functions. Finally section Section 15.5 provides the limitations that apply to the interfaces described in the chapter.

15.2 Setup procedure

The C API is fully integrated and does not require any setup. For Fotran and Ada the linking of the Fortran or Ada runtime library must be seleced in the Model Editor build options. See Figure 15.1.

c Airbus Defence and Space 193 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 15.1: EuroSim build options

15.3 Publication interface

15.3.1 API Header

This section contains the lay-out of the API headers, as they are generated by EuroSim for C and Fortran model code. As EuroSim does not generate API headers for Ada-95 model code, the information in this appendix can be used to create API headers for Ada-95 model code by hand.

The API header is contained in a comment block at the top of the source code (i.e. between /**/ in C, on lines starting with C in Fortran and on lines starting with -- in Ada-95). In Ada-95 and Fortran, make sure that if the original source code started with a comment block, that there is an empty line between the API header and the source code comments.

Each API header consists of the following four keywords (see Section 2.4 for more information):

• ’Global_State_Variables

• ’Global_Input_Variables

• ’Global_Output_Variables

• ’Entry_Point

The first three keywords are used to describe the variables in the source code, and the last keyword is used to describe the entry points. The first keyword is used once per source file, the last three once per entry point. Each keyword is preceded by a straight quote.

194 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

15.3.1.1 ’Global State Variables Global state variables are the variables which are used in the current source file only, and should not be seen by other source files. The syntax of the keyword is: ’Global_State_Variables VariableType VariableName : Attributes The VariableType and VariableName are as they are defined in the source file. The Attributes can be zero or more of the attributes described below. If more than one attribute is used, they should be sepa- rated by spaces or newlines. If more than one variable is defined with the keyword, each VariableType VariableName : Attributes set should be separated by commas.

• UNIT="text"

This defines text as the unit of the variable. The string text can be any string.

• DESCRIPTION="text"

This defines a string text which is used as description of the variable.

• PARAMETER or RO

No additional information. It defines a variable as ‘parameter’, meaning that EuroSim should not allow the value of the variable to be changed during a simulation (only during initialization).

• INIT="value"

This defines value as the initial value for the variable. value should be in the correct syntax for the associated variable.

• MIN="value"

• MAX="value"

These two define the minimum and maximum values of the variable. value should be in the correct syntax for the associated variable.

15.3.1.2 ’Global Input Variables This keyword is used to define the variables that are used by the current source file, and which are set to a value by another source file. The syntax of the keyword is the same as for global state variables.

15.3.1.3 ’Global Output Variables This keyword is used to define the variables that are used by other source files, and which are set to a value by the current source file. The syntax of the keyword is the same as for global state variables.

15.3.1.4 ’Entry Point This keyword is used once per function/procedure that has to be available for the scheduler. See Sec- tion 15.5 for more information on restrictions on functions/procedures to be used as entry points. The syntax of the keyword is: ’Entry_Point FunctionName : DESCRIPTION="Description"

c Airbus Defence and Space 195 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

15.3.2 Publication functions It is also possible to ‘publish’ variables from the data dictionary. There are several functions that set the address where a variable or entry point in a certain data dictionary is stored, thus making it accessible from the outside. This is useful for people who want to make their own model interfaces. The publish functions are divided in two categories, a function to get the runtime data dictionary and functions to publish data variables and entry points in a data dictionary.

15.3.2.1 Function to get the runtime data dictionary When a EuroSim simulation application program needs access to the runtime data dictionary it must call esimDict(void). This function returns a pointer to the runtime data dictionary (DICT*) and is defined in the header file esimDict.h.

15.3.2.2 Functions to publish data variables and entry points in a data dictionary

dictPublish(DICT *dict, const char *name, const void *address) sets the address of the vari- able specified by name in the data dictionary specified by dict to address. This function can be called from C or Ada.

dictpublish_(DICT *dict, const char *name, const void *address, int namelen) is the For- tran wrapper for dictPublish. It has an extra parameter with the length of the name parameter. This is required by the calling convention of Fortran functions.

dictPubEntry(DICT *dict, const char *name, EntryPtr address) sets the function address of the entry point specified by name in the runtime data dictionary to address. This function can be called from C or Ada.

dictpubentry_(DICT *dict, const char *name, EntryPtr address, int namelen) is the Fortran wrapper for dictPubEntry. It has an extra parameter with the length of the name parameter. This is re- quired by the calling convention of Fortran. functions. The prototypes for these functions can be found in DictPublish.h.

15.4 Service interface

This section describes all services and their interface description available for simulation models that want to use the EuroSim services. These services can be used both from C as well as Fortran programs. In the latter case the function calls are all in lower or upper case (depending on your programming style). Below a short description of the available functions is given. For more information, refer to the esim(3C) man page.

15.4.1 Usage in C #include

cc ... -L$EFOROOT/lib32 -lesServer -les

15.4.1.1 Real-time (shared) memory allocation

void *esimMalloc(size_t size) void esimFree(void *ptr) void *esimRealloc(void *ptr, size_t size) void *esimCalloc(size_t nelem, size_t elsize) char *esimStrdup(const char *str)

196 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

15.4.1.2 Real-time timing functions double esimGetSimtime(void) struct timespec esimGetSimtimets(void) void esimGetSimtimeYMDHMSs(int t[7]) double esimGetWallclocktime(void) struct timespec esimGetWallclocktimets(void) double esimGetHighResWallclocktime(void) int esimSetSimtime(double simtime) int esimSetSimtimets(struct timespec simtime) int esimSetSimtimeYMDHMSs(int t[7])

15.4.1.3 Real-time simulation state functions esimState esimGetState(void) int esimSetState(esimState state) int esimSetStateTimed(esimState state, const struct timespec *t, int use_simtime) struct timespec esimGetMainCycleTime(void) struct timespec esimGetMainCycleBoundarySimtime(void) struct timespec esimGetMainCycleBoundaryWallclocktime(void)

15.4.1.4 Real-time task related functions const char *esimGetTaskname(void) double esimGetTaskrate(void) int esimEnableTask(const char *taskname) int esimDisableTask(const char *taskname) int esimEntrypointFrequency(esimState state, const char *entrypoint, double freq) int esimEntrypointSetEnabled(const char *entrypoint, bool enabled) int esimGetRealtime(void) int esimSetRealtime(int on)

15.4.1.5 Event functions int esimEventRaise(const char *eventname, const void *data, int size) int esimEventRaiseTimed(const char *eventname, const void *data, int size, const struct timespec *t, int use_simtime) int esimEventCancelTimed(const char *eventname) int esimEventData(void *data, int *size) int esimEventTime(struct timespec *event_occurrence_time, struct_timespec *event_raise_time) int esimEventCount(const char *eventname) typedef int (*esimEventHandlerDispatchFunc)(esimEH *context, const void* msg, int size,void* user_data) int esimEventHandlerHDispatch(esimEH *context, const char* name, const void *msg, int size) int esimEventHandlerInstall(const char *name, esimEventHandlerDispatchFunc dispatcher, void *user_data) int esimEventHandlerUninstall(const char *name)

15.4.1.6 Real-time clock functions double esimGetSpeed(void) int esimSetSpeed(double speed)

c Airbus Defence and Space 197 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

15.4.1.7 Real-time recording functions int esimGetRecordingState(void) int esimSetRecordingState(int on)

15.4.1.8 Real-time reporting functions

void esimMessage(const char *format, ...) void esimWarning(const char *format, ...) void esimError(const char *format, ...) void esimFatal(const char *format, ...) void esimReport(int lvl, const char *fmt, ...) int esimReportAddSeverity(const char *sev_name)

15.4.1.9 Real-time Heap functions

void esimGetHeapUsage(int *tot_size, int *max_used, int *current_use)

15.4.1.10 Real-time processor load functions bool esimSetLoadMeasureInterval(int processor, double interval) bool esimGetProcessorLoad(int processor, double *avg_load, double *max_load)

15.4.1.11 Non-real-time thread functions

esimThread* esimThreadCreate(const char *name, void (*start_routine)(void*), void *arg) int esimThreadKill(esimThread *thread, int signal) void esimThreadExit(int exit_val)

15.4.1.12 Auxiliary functions int esimGetProcessor(void) const char *esimVersion(void) void esimInstallErrorHandler(ErrorHandler userhandler) void esimAbortNow(void) bool esimIsResetting(void)

15.4.1.13 Tracing functions void esimTracePause(void) bool esimTraceResume(void) void esimTraceMask(unsigned type_mask, unsigned proc_mask)

15.4.1.14 User-defined recording functions #include

EsimRec* esimRecOpen(const char *path, int flags) int esimRecWriteRaw(EsimRec *rec, const void *ptr, size_t size) int esimRecWriteHeader(EsimRec *rec) int esimRecWriteRecord(EsimRec *rec) int esimRecClose(EsimRec *rec)

int esimRecInt8FieldAdd(EsimRec *rec, const char *name, int8_t *address)

198 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

int esimRecUint8FieldAdd(EsimRec *rec, const char *name, uint8_t *address) int esimRecInt16FieldAdd(EsimRec *rec, const char *name, int16_t *address) int esimRecUint16FieldAdd(EsimRec *rec, const char *name, uint16_t *address) int esimRecInt32FieldAdd(EsimRec *rec, const char *name, int32_t *address) int esimRecUint32FieldAdd(EsimRec *rec, const char *name, uint32_t *address) int esimRecInt64FieldAdd(EsimRec *rec, const char *name, int64_t *address) int esimRecUint64FieldAdd(EsimRec *rec, const char *name, uint64_t *address) int esimRecFloatFieldAdd(EsimRec *rec, const char *name, float *address) int esimRecDoubleFieldAdd(EsimRec *rec, const char *name, double *address) int esimRecInt8ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, int8_t *address) int esimRecUint8ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, uint8_t *address) int esimRecInt16ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, int16_t *address) int esimRecUint16ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, uint16_t *address) int esimRecInt32ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, int32_t *address) int esimRecUint32ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, uint32_t *address) int esimRecInt64ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, int64_t *address) int esimRecUint64ArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, uint64_t *address) int esimRecFloatArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, float *address) int esimRecDoubleArrayFieldAdd(EsimRec *rec, const char *name, size_t n_elem, double *address)

15.4.2 Usage in Fortran include ‘esim.inc’ f77 ... -L$EFOROOT/lib32 -lesServer -les

The synopsis in this section uses the following variables: double precision time, rate, frequency, speed integer state, on, ok, level, counter, timespec(2), timeymd(7) integer data(n), size, use_simtime, number character*N eventname, taskname, message, version, entrypoint

c Airbus Defence and Space 199 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

15.4.2.1 Real-time timing functions time = esimgetsimtime time = esimgetwallclocktime time = esimgethighreswallclocktime call esimgetsimtimets(timespec) call esimgetsimtimeymdhmss(timeymd) call esimgetwallclocktimets(timespec) ok = esimsetsimtime(time) ok = esimsetsimtimets(timespec) ok = esimsetsimtimeymdhmss(timeymd)

15.4.2.2 Real-time simulation state functions state = esimgetstate ok = esimsetstate(state) ok = esimsetstatetimed(state, timespec, use_simtime) call esimgetmaincycletime(timespec) call esimgetmaincycleboundarysimtime(timespec) call esimgetmaincycleboundarywallclocktime(timespec)

15.4.2.3 Real-time task related functions call esimgettaskname(taskname) rate = esimgettaskrate ok = esimenabletask(taskname) ok = esimdisabletask(taskname) ok = esimentrypointfrequency(state, entrypoint, frequency)

15.4.2.4 Event functions ok = esimeventraise(eventname, data, size) ok = esimeventraisetimed(eventname, data, size, timespec, use_simtime) ok = esimeventdata(data, size) ok = esimeventime(timespec, timespec) counter = esimeventcount(eventname) ok = esimeventhandlerinstall(name, dispatcher, user_data) ok = esimeventhandleruninstall(name) ok = esimeventhandlerdispatch(context,name, msg, size)

15.4.2.5 Real-time clock functions on = esimgetrealtime ok = esimsetrealtime(on) speed = esimgetspeed ok = esimsetspeed(speed)

15.4.2.6 Real-time recording functions on = esimgetrecordingstate ok = esimsetrecordingstate(on)

200 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

15.4.2.7 Real-time reporting functions call esimmessage(message) call esimwarning(message) call esimerror(message) call esimfatal(message) call esimreport(level, message)

15.4.2.8 Auxiliary functions number = esimgetprocessor() call esimversion() call esimabortnow()

15.4.2.9 Trace functions call esimtracepause() call esimtraceresume() call esimtracemask()

15.4.3 Usage in Ada-95 use Esim; with Esim

Do not forget to check the ‘Gnat Ada runtime libraries’ option in the Model:Options window of the Model Editor (see Figure 7.5).

15.4.3.1 Real-time (shared) memory allocation function EsimMalloc(Size : Size_T) return Void_Ptr procedure EsimFree(Ptr : Void_Ptr) function EsimRealloc(Ptr : Void_Ptr Size : Size_T) return Void_Ptr function EsimCalloc(Nelem : Size_T Elsize : Size_T) return Void_Ptr function EsimStrdup(Str : Chars_Ptr) return Chars_Ptr function EsimStrdup(Str : String) return String

15.4.3.2 Real-time timing functions function EsimGetSimtime return Long_Float function EsimGetSimtimets return Time_Spec procedure EsimGetSimtimeYMDHMSs(SimTime: out YMDHMSs) function EsimSetSimtime(Simtime: Long_float) return Integer function EsimSetSimtimets(Simtime: in Time_Spec) return Integer function EsimSetSimtimeYMDHMSs(Simtime: in YMDHMSs) return Integer function EsimGetWallclocktime return Long_Float function EsimGetHighResWallclocktime return Long_Float function EsimGetWallclocktimets return Time_Spec

15.4.3.3 Real-time simulation state functions function EsimGetState return esimState function EsimSetState(State : esimState) return Integer function EsimSetState(State : esimState) return Boolean function EsimSetStateTimed(State : EsimState; T : in Time_Spec; Use_Simtime : Integer) return Integer

c Airbus Defence and Space 201 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

function EsimSetStateTimed(State : EsimState; T : in Time_Spec; Use_Simtime : Boolean) return Boolean function EsimGetMainCycleTime return Time_Spec function EsimGetMainCycleBoundarySimtime return Time_Spec function EsimGetMainCycleBoundaryWallclocktime return Time_Spec

15.4.3.4 Real-time task related functions function EsimGetTaskname return Chars_Ptr function EsimGetTaskname return String function EsimGetTaskrate return Long_Float function EsimEnableTask(Taskname : Chars_Ptr) return Integer function EsimEnableTask(Taskname : String) return Boolean function EsimDisableTask(Taskname : Chars_Ptr) return Integer function EsimDisableTask(Taskname : String) return Boolean

15.4.3.5 Event functions function EsimEventRaise(EventName : Chars_Ptr; Data : Void_Ptr; Size : Integer) return Integer function EsimEventRaise(EventName: in String; Data : in Void_Ptr; Size : Integer) return Boolean function EsimEventRaiseTimed(EventName : in Chars_Ptr; Data : in Void_Ptr; Size : Integer; T : in Time_Spec; Use_Simtime : Integer) return Integer function EsimEventRaiseTimed(EventName : in String; Data : in Void_Ptr; Size : Integer; T : in Time_Spec; Use_Simtime : Boolean) return Boolean type Integer_Ptr is access Integer; function EsimEventData(Data : in Void_Ptr; Size : Integer_Ptr) return Integer function EsimEventCount(EventName : String) return Integer

15.4.3.6 Real-time clock functions function EsimGetSpeed return Long_Float function EsimSetSpeed(Frequency : Long_Float) return Integer function EsimSetSpeed(Frequency : Long_Float) return Boolean function EsimGetRealtime return Integer function EsimGetRealtime return Boolean function EsimSetRealtime(On : Integer) return Integer function EsimSetRealtime(On : Boolean) return Boolean

15.4.3.7 Real-time recording functions function EsimGetRecordingState return Integer function EsimGetRecordingState return Boolean

202 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

function EsimSetRecordingState(On : Integer) return Integer function EsimSetRecordingState(On : Boolean) return Boolean

15.4.3.8 Real-time reporting functions procedure EsimMessage(Warning : Chars_Ptr) procedure EsimMessage(Warning : String) procedure EsimWarning(Message : Chars_Ptr) procedure EsimWarning(Message : String) procedure EsimError(Error : Chars_Ptr) procedure EsimError(Error : String) procedure EsimFatal(Fatal : Chars_Ptr) procedure EsimFatal(Fatal : String) procedure EsimReport(S : esimSeverity Report : Chars_Ptr) procedure EsimReport(S : esimSeverity Report : String)

15.4.3.9 Auxiliary functions function EsimVersion return Chars_Ptr function EsimVersion return String procedure EsimAbortNow

15.4.3.10 Trace functions procedure EsimTracePause procedure EsimTraceResume procedure EsimTraceMask(TyepMask : Integer ProcMask : Integer)

15.4.4 Description of functions

When you link in the libesim.a library a main() function is already included for your convenience. It makes sure all EuroSim processes are started up. esimMalloc, esimFree, esimRealloc, esimCalloc and esimStrdup are common memory allocation functions. These are the same as their malloc(3) counterparts in the “C” library, with the exception that the EuroSim calls are optimized for parallel/real-time usage, and checks for memory exhaustion are built-in. For the semantics and arguments and return values see malloc(3) for details. esimGetSimtime() returns the simulation time in seconds with the precision of the basic cycle with which the simulation runs (5 ms by default). In case the simulation is driven by the external interrupt the precision is equal to that period. If the simulator has real-time errors the simulation time will be slower than the wall clock. The simulation time is set to zero (0) on arriving in initializing state. esimGetWallclocktime() returns the wallclock time in seconds. The basic resolution is equal to the resolution of the high-res time described next, but is truncated to milliseconds. The wallclock time is set to zero when the first model task is scheduled, and runs real-time which means that is independent from the simulation time. esimGetWallclocktimets() returns the wallclock time in a timespec structure. It replaces the obsoles- cent esimGetWallclocktimeUTC(). esimGetHighResWallclocktime() returns the “same” time as esimGetWallclocktime() but in mil- liseconds and with a higher resolution. This high resolution is 21 ns on high-end platforms such as a Challenge and Onyx. On low end platforms this resolution is as good as what can be achieved by the gettimeofday(3) call. esimGetSimtimets() returns the simulation time in a timespec structure. It replaces the obsolescent esimGetSimtimeUTC().

c Airbus Defence and Space 203 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

esimGetSimtimeYMDHMSs() returns the simulation time in an array of 7 integers containing: year, month, day, hour, minute, second and nanoseconds. esimSetSimtime() sets the requested simulation time simtime in seconds. This can only be done in the standby state. If calling esimSetSimtime in any other state is attempted or simtime is less than zero, no simulation time is set and (-1) is returned. On success zero (0) is returned. esimSetSimtimets() sets the simulation time using a timespec structure. It replaces the obsolescent esimSetSimtimeUTC(). esimSetSimtimeYMDHMSs() sets the simulation time using an array of 7 integers containing: year, month, day, hour, minute, second and nanoseconds. esimGetState() returns the current simulator state. The state can be any of the following values: esimUnconfiguredState, esimInitialisingState, esimExecutingState, esimStandbyState or esimStoppingState. esimSetState() sets the simulator state to the indicated value state. state can be any of the following values: esimUnconfiguredState, esimInitialisingState, esimExecutingState, esimStandbyState or esimStoppingState. If state is not reachable from the current state 0 is returned; on a successful state transition 1. is returned. esimSetStateTimed() sets the simulator state to the indicated value state at the specified time t. The possible values of state are listed in the previous paragraph. If the flag use simtime is set to 1 (true), the specified time is interpreted as simulation time. If the flag is set to 0 (false), the specified time is interpreted as the wallclock time. The transition time uses a struct timespec where the number of seconds is relative to January 1, 1970. On success this function returns 0, otherwise -1. esimGetMainCycleTime() returns the main cycle time of the schedule. The result can be used to com- pute valid state transition times for use in the function esimSetStateTimed(). esimGetMainCycleBoundarySimtime() returns the simulation time of the last state transition. This boundary time can be used to compute valid state transition times for use in the function esimSetStateTimed() when the value of use simtime is true. esimGetMainCycleBoundaryWallclocktime() returns the wallclock time of the last state transition. This boundary time can be used to compute valid state transition times for use in the function esimSetStateTimed() when the value of use simtime is false. esimGetTaskname() returns the name of your current task. esimGetTaskrate() returns the frequency (in Hz) of your current task. esimDisableTask() disables the task ‘taskname’ defined with the Schedule Editor. It will be skipped (not executed) by the EuroSim runtime until a call is made to esimEnableTask. esimEnableTask() enables the task ‘taskname’ defined with the Schedule Editor. It will be execut- ed/scheduled according to the schedule made with the Schedule Editor. esimEntrypointFrequency() stores the frequency (in Hz) of the entry point with the name ‘entrypoint’ in the argument ‘freq’ in the state ‘state’. If the entry point appears multiple times in the schedule the function returns -1. If the entry point does not appear in the schedule in the given state, the frequency is 0. esimEventRaise() raises the event eventname for triggering tasks defined with the Schedule Editor. User defined data can be passed in data and size. On success this function returns 0, otherwise -1. esimEventRaiseTimed() raises the event eventname for triggering tasks defined with the schedule editor at the specified time t. User defined data can be passed in data and size. If the flag use simtime is set to 1 (true), the specified time is interpreted as simulation time. If the flag is set to 0 (false), the specified time is interpreted as the wallclock time. The transition time uses a struct timespec where the number of seconds is relative to January 1, 1970. On success this function returns 0, otherwise -1.

204 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

esimEventData() gets the data passed with the event. This function can only be used in the task con- nected to the input connector. Beware that the size argument is both input and output. It specifies the size of the buffer pointed to by the data pointer, and is set by esimEventData to the actual number of bytes written in that buffer. esimEventTime() gets the timestamps of detection of the occurrence of the external event (e.g. interrupt) and the timestamp of injection of the event into the scheduler as a EuroSim event. This function can only be used in the task connected to the input connector. esimEventCount() returns the number of times that event eventname has been raised or -1 if no such event is defined. esimEventHandlerInstall External Event Handlers are a means of handling asynchronous events such as device interrupts. Events are forwarded from its external source to an Input Connector. The External Event Handler are created with the Schedule Editor and can be automatic or user defined. Automatic event handlers forward the event to a single input connector that must have the same name as the even- thandler. This is the fastest route for an interrupt. However, the user can use the esimEventHandlerInstall function to install a callback that will be activated before the event is instert. This allows the user to in- spect data and decide to which inputconnector the event should be forwarded. As a side effect, it also blocks the event handler from handling interrupts untill the esimEventHandlerInstall routine is called. External event handlers interrupt the real-time scheduler, and thus influence the real-time performance of the system. To prevent jitter on the scheduler clock the external event handlers should be installed on other processors than the clock. Best performance can be obtained if the processor with the external event handler does not run any periodic tasks. In a task connected directly to the input connector the event data can be retrieved with the esimEventData functions. The time at which EuroSim became aware of the external event and the time at which it injected the event into the scheduler can be retreived with the esimEventTime service function. esimEventHandlerDispatch Is used from within the event handler callback function to the event with name name and message msg of size bytes to an inputconnector. This data can be retrieved withint a task with esimEventData. context should be the context parameter of the callback function. On success this function returns 0, otherwise -1. esimEventHandlerUninstall uninstalls the previously installed callback functions. esimGetRealtime() returns the current operational state of the EuroSim real-time Scheduler. If 1 is returned, hard real-time execution is in progress, whereas a return of 0 indicates that your model is not executing in real-time mode. esimSetRealtime() sets the current operational state of the EuroSim real-time Scheduler. Hard real time execution can only be set if the scheduler was launched in hard real time mode. 1 is returned on success. 0 is returned on failure. esimGetSpeed() returns the current speed of EuroSim Scheduler. e.g. 1.0 means (hard or soft) real time. 0.1 means slowdown by a factor 10. -1 means as fast as possible. esimSetSpeed() sets the current speed of EuroSim Scheduler. e.g. 1.0 means (hard or soft) real time. 0.1 means slowdown by a factor 10. -1 means as fast as possible. The speed can only be changed if the scheduler is running non real-time. If speed is not a feasible speed 0 is returned; on a successful setting of the speed 1 is returned. esimGetRecordingState() returns the current state of the EuroSim real-time data Recorder. If true is returned, data is logged to disk, whereas a return of false indicates that recording is switched off. esimSetRecordingState() sets the state of the Recorder to on. If on is true data will subsequently be written to disk, if on is false data recording will be suspended. Return value is either true or false, depending on success or not. The functions esimReport, esimMessage, esimWarning, esimError and esimFatal can be used to send messages from the EuroSim model code to the test-conductor interface. The esimReport function allows

c Airbus Defence and Space 205 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

the caller to specify the severity of the message. The other functions have implicit severities. The possible severity levels are:

• esimSevMessage for comment or verbose information

• esimSevWarning for warnings

• esimSevError for errors

• esimSevFatal for non-recoverable errors

It is possible to define your own severity levels. The function esimReportAddSeverity creates a new severity with the name sev name. The return value of the function is the new severity that can be used in calls to esimReport(). In the C interface routines the message consists of a format string format and its optional arguments. (see printf(3)). In the Fortran interface routines the message consists of a single string argument message. esimRecOpen() opens a user-defined recorder file. The file is opened for writing. If the path is relative, the file is created in the recorder directory. The flags parameter contains configuration and/or option flags. It shall be set to 0 if no options are selected. The recorder handle is returned. On error NULL is returned. esimRecWriteRaw() writes the size bytes of data in ptr to the recorder file indicated by the recorder handle rec. On error -1 is returned, on success 0. esimRecWriteHeader() writes the recorder file header to disk. The simulation time is automatically included as the first field of each recording. After calling this function no more fields can be added to the recorder. Only calls to esimRecWriteRecord() and esimRecClose() are allowed. rec is the recorder file handle. On error -1 is returned, on success 0. esimRecWriteRecord() samples all the variables that are in the recording referenced by rec and writes it to disk. On error -1 is returned, on success 0. esimRectypeFieldAdd(), where type can be Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Float or Double, is used to add a data field to the recorder of the specified type. rec is the recorder file handle. name is the symbolic name of the field. address is the address pointing to the variable to be recorded. On error -1 is returned, on success 0. esimRectypeArrayFieldAdd(), where type can be Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Float or Double, is used to add an array data field to the recorder of the specified type. rec is the recorder file handle. name is the symbolic name of the field. n elem is the number of elements in the array. address is the address pointing to the variable to be recorded. On error -1 is returned, on success 0. esimRecClose() closes the user-defined recorder file indicated by recorder handle rec. On error -1 is returned, on success 0. esimThreadCreate() creates a new non-real-time thread in the address space of the simulator. The thread starts the routine start routine with argument arg. The name of the thread is given in name. This function should only be called from a non real-time task. Usage from a real-time task will result in a warning message and no further action taken. The ThermoMra example (distributed with EuroSim) shows how this function can be called correctly. esimThreadKill() sends signal signal to thread thread. esimThreadExit() ends the current thread with exit code exit val. esimgetProcessor() returns the number of the logical processor that executes the esimGetProcessor call. Only when running real-time, the logical number matches the physical processor number. In non real-time simulations the logical number would remain constant, whereas the actual execution may switch physical numbers to optimize load balancing. When the processor setting in the schedule is ANY

206 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

processor, the returned number can fluctuate as the logical processor may change depending on which processor is first ready to execute the calling task. esimVersion() returns a string indicating the current version of EuroSim that you are running. esimInstallErrorHandler() installs a user-defined error handler callback of the form:

void userhandler(esimErrorScope scope, const char *objectid) This callback function is called when an error occurs that may need intervention in user code. Passing a NULL pointer will de-install the user error handler. No stack of user error handlers is main- tained. This means that the last call to esimInstallErrorHandler defines which handler will be called. The possible values for scope are:

• esimDeadlineError when the user defined error handler is called with this scope then the objectid is the name of a task in the simulator schedule that has exceeded its deadline by a factor of ten. This allows a model developer to take action (f.i. force a core dump) when part of a model is ill-behaved (never ending loops or simply a calculation that takes too long and causes real-time errors). If no error handler is installed, the default action is to disable the offending task and enter the stand-by state. Note that deadline checking is only performed when the simulator is running in real-time mode. esimAbortNow() immediately starts termination and cleanup of the simulator. This is useful when an error condition is found (f.i. at initialisation time) and no more entry points should be scheduled for execution. esimTracePause() can generate a detailed tracing of the scheduler execution. When enabled via the ScheduleEditors Timebar dialog, the tracing starts when the scheduler starts executing. The esimTra- cePause can be called to freeze the tracing unit. esimTraceResume() can be called to resume the tracing of the scheduler execution. See also esimTra- cePause. esimTraceMask() The EuroSim Scheduler tracing capability generates a stream of data at high rate. Especially when multiple processors are active this can either overflow the internal buffering, the file system or just make the visualisation in the TimeBarViewer very slow. Using the esimTraceMask func- tion the user can filter out event types and/or processors. Setting bits in the processor mask to 1 enables the processor to be logged. The least significant bit (i.e. bit 0) identifies the Non RealTime processor, the subsequent bits identify the processor number as set in the Schedule Editor. Setting bits in the event type mask to 1 enables events to be logged,where

bit 0= Timer item events, relating to the timers on the schedule canvas bit 1= Task item events, recording the execution time of tasks bit 2= Task Entry events, recording the execution time of entrypoints bit 3= Busy time, recording the time the scheduler is executing (not id le) bit 4= Clock, recording the clock interrupt bit 5= Interrupt, recording the interrupt time bit 6= Event, recording the executing times of event handler execution bit 7= Input, recording the triggering of the input connector bit 8= Command, recording the triggering of the command connector bit 9= Execution, recording the preemption of tasks esimIsResetting() returns true when the reset procedure is in progress and false when it is not. The reset procedure starts in standby state and progresses through exiting, unconfigured, initializing and back

c Airbus Defence and Space 207 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

into standby state. This function allows you to distinguish between for example a user initiated state transitions to exiting state to stop the simulator and the state transitions performed in the reset procedure. esimGetHeapUsage() returns the real-time heap size, the maximum heap size used since startup and the current use (all reported in bytes) esimSetLoadMeasureInterval() sets the measurement interval (msec) over which the processor load percentages will be measured. The interval must be equal to or be a multiple of the basic cycle period. If not it will be truncated to the nearest multiple. The start of a measurement interval is synchronized to a multiple of its period with respect to the start of the simulation (t=0). Synchronisation is delayed until the end of the running measurement interval. If no interval was set by a previous call to this function then synchronisation is started immediately.

Figure 15.2: Example of using the processor load functions

Specifying a measurement interval equal to the major cycle time allows acurate load measurements of the major cycle to be made using the function esimGetProcessorLoad() esimGetProcessorLoad() reads the maximum load and the average load of the specified processor (0- 100%). The maximum is defined as the maximum percentage of time a processor was executing model tasks during a measurement interval (set by esimSetLoadMeasurementInterval()). The returned load values are only accurate when the simulator is running real time. Processing time of Eurosim itself and possible event handlers is not included. The maximum is reset each time the processor load is read (using this function). The average load is calculated over the number of measurement intervals that passed since the last call to this function. I.e. if the time interval is set to the main cycle period (by esimSetLoadMeasurementInterval) and this function is called every fourth main cycle, then the average load is calculated over the loads of the last four (completed) main cycle periods. Calling this function every main cycle will return the processor load over the last completed main cycle.

15.5 Limitations

15.5.1 Generial limitations Model code should follow a set of rules when it is to be used in EuroSim. The rules are:

• Entry points should have no return value.

• Entry points should have no calling arguments/parameters (functions not used as entry points do not have this restriction). When calling arguments or parameters are needed they should be defined through one of two methods (of which the first one is recommended):

208 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

1. Define global variables through an API as ‘virtual’ arguments/parameters. 2. Encapsulate a function with arguments in a function which complies to the guidelines; this function can then call the function with arguments.

• If the entry point is used in the real-time domain it is not allowed to use any operating system call (open, printf, etc...). This is because operating system calls do not have deterministic execution times. Calls which are allowed are the services provided by EuroSim. See Section 15.4 for details on the EuroSim services.

• The entry point must not create a deadlock (i.e. waiting on a resource not available for some (undefined) time).

• No names should be used which conflict with one of the internal EuroSim functions. Refer to the file $EFOROOT/etc/reserved-words.txt for the complete list of reserved words.

• Only variables with a memory address that is fixed at load time can be used as API variables1.

The operation must not make use of a locking mechanism (semaphores) to establish mutual exclusion of a common defined variable. This should be done using an asynchronous store (see Section 11.3). During real-time simulation, the size of the system stack cannot change. Therefore, care should be taken with model code which allocates large data structures on the stack. When combining programming languages in one model (e.g. C and Fortran), there are a number of rules to keep in consideration with respect to variable and function naming. Refer to the programming language documentation for more information. For an example, see Section 3.6.

15.5.2 C limitations

Unnamed structures, unions and bitfields cannot be used as API variables. Bitfields cannot be used on typedef’ed types. Thus use unsigned int instead of uint32_t as these are typedef’s definedin stdint.h.

15.5.3 Fortran limitations

Because Fortran lacks the extern keyword as available in C, the ‘owner’ of a variable is not known to the Fortran compiler. Therefore, variables are declared in more than one Fortran source file. However, for EuroSim purposes, the API information for a variable should only be in one API header. The user should therefore make sure that a variable which is declared in more than one source file, should only be added to the API header of one of those files.

15.5.4 Ada-95 limitations Although EuroSim does support the use of Ada-95 (except on the Windows platform) for the develop- ment of model code, the support is not at the same level as for C and Fortran. This is mostly due to the complexity of the Ada-95 language. The main difference with the use of C and Fortran code is that the API Editor does currently not support parsing of Ada-95 code. This means that any API headers have to be entered by hand to the source code. See Section 15.3.1 for details on the layout of the API headers, and Section 15.6.2 for an example of an Ada-95 header. Also, EuroSim currently only supports the use of the “GNAT” Ada-95 compiler. In this section, the limitations of the use of Ada-95 are described.

1There is one exception: static variables declared within a C function have a load time fixed address but are not accessible by EuroSim. No implementation of such access is possible without violating the rule that EuroSim should not modify source code files.

c Airbus Defence and Space 209 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

15.5.4.1 Ada-95 compilation

The GNAT compiler allows only one compilation unit per file. The gnatchop utility can be used to split the files. A body should be contained in a .adb file, and specifications should be in .ads files. If the package name example is given in a with clause, the compiler will look for example.ads. Filenames are mapped to lowercase, so the file Example.ads will not be found.

15.5.4.2 Ada-95 variables Only variables which have a fixed address (as specified by the Ada-95 ‘Address’ attribute) can be used as global variables within EuroSim. Variables that are to be used as globals must be made visible to the generated publish procedure. Therefore they must be put in a subprogram or package specification, so that they can be accessed by means of the with clause. When two packages define a variable with the same name, the names should be fully qualified in the data dictionary (i.e. with the package name), otherwise the connection between variables and their compilation subunits would be lost. If Ada-95 code is mixed with C and/or Fortran code, the model developer has to get the bindings of variable and entry names correct himself. An entity name that appears in a library package is accessible from C as package__name (two underscores). If the entity appears outside a package, its name will be prefixed with _ada_.

15.5.4.3 Ada-95 entry points Ada-95 procedures without arguments can be used as entry points. In contrast with the global variables, they will not be referenced from generated Ada-95 publish code. However, they will be called from C code that is generated using information in the data dictionary, so the name in the data dictionary should correspond to the generated name in the object file. Since entry points cannot have arguments, they cannot be overloaded.

15.5.4.4 Ada-95 Types

Generic packages cannot have API headers, because each instantiation would also have to instantiate a new API header. The API header has no support for generic types. If an instantiation of a generic package is made, the user has to perform the necessary parameter substitution himself. User defined types are not supported by EuroSim.

15.5.4.5 Ada-95 Tasks Since the EuroSim environment supplies its own task mechanism, the Ada-95 task and exception mech- anism and associated commands (e.g. select, delay) should not be used.

15.5.4.6 Ada-95 Real time aspects The timing of Ada-95 routines may be less predictable than the timing for C and Fortran, due to the dynamic allocation of variables.

15.6 Example API header

15.6.1 C Example

As an example, the API header from the Thruster.c file used in the case study is shown below (see Sec- tion 3.5 for the source code and the API information).

210 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

/* ’Entry_Point Thruster: DESCRIPTION="The thruster brings the satellite to" " the correct altitude." ’Global_Input_Variables int lowerAltitudeLimit: UNIT="km" DESCRIPTION="Below this limit, the thruster must" " be turned on." INIT="210" MIN="0" MAX="1000", int sateliteAscentSpeed: UNIT="km/h" DESCRIPTION="The ascent speed of the satellite." INIT="10" MIN="1" MAX="200", int thrusterOnOff: UNIT="On/Off" DESCRIPTION="Indicates whether the thruster is" " on or off." INIT="1" MIN="0" MAX="1", int upperAltitudeLimit: UNIT="km" DESCRIPTION="The upper limit at which the thrust" "er is to be switched of." INIT="280" MIN="0" MAX="1000" ’Global_Output_Variables int thrusterOnOff: UNIT="On/Off" DESCRIPTION="Indicates whether the thruster is" " on or off." INIT="1" MIN="0" MAX="1" */

Note that there is no restriction on line length for the API headers, but that the API Editor generates no lines longer than 80 characters. This is done to ensure good readability on most terminals.

Also note that variables which act both as input as well as output variables are defined twice in the API header.

15.6.2 Ada-95 Example

------Name: ball.adb -- Type: Ada-95 implementation. -- -- Author: John Graat (NLR). -- Date: 19961125 -- Changes: none

c Airbus Defence and Space 211 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

------Purpose: Model for the Simulation of a Bouncing Ball. -- -- The Bouncing Ball describes a ball that is thrown -- straight-up from the ground with an initial velocity -- or dropped from an initial height. -- In the absence of friction, the ball should reach -- exactly the same maximum height time and time again. -- The ball is described as a mass point. -- -- Parameters: GRAVITY Gravitation constant [m/s2] -- -- State: Height Height of the ball above the ground [m]. -- Velocity Velocity of the ball [m/s]. -- -- Additional: DeltaT Time Step for the Model. -- LoadLoop Loop counter to increase computation time. -- Duration Duration of the Ball Model. -- -- Remark: The mass of the ball has mplicitly been set to 1 [kg]. -- -- API Header required for the correct Data Dictionary: -- -- ’Entry_Point ball.Ball: -- DESCRIPTION="Computation of one time step of the ball" -- "." -- ’Global_Input_Variables -- Long_Float ball.deltat: -- UNIT="s" -- DESCRIPTION="Time step for the Ball Sub-Model." -- MIN="0" -- MAX="1", -- Long_Float ball.height: -- UNIT="m" -- DESCRIPTION="Height of the ball." -- MIN="0" -- MAX="100", -- Integer ball.loadloop: -- UNIT="-" -- DESCRIPTION="Loop counter to increase load." -- MIN="0", -- Long_Float ball.velocity: -- UNIT="m/s" -- DESCRIPTION="Velocity of the Ball." -- ’Global_Output_Variables -- Long_Float ball.deltat, -- Long_Float ball.height, -- Long_Float ball.velocity, -- Long_Float ball.duration: -- DESCRIPTION="Duration of the Ball Model." ------

with integr; with esim; use esim;

package body Ball is

212 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

GRAVITY : constant Long_Float := 9.80664999;

-- Global variables of the Bouncing Ball -- Actual declaration of these variables can be found in ball.ads -- Height, Velocity, DeltaT : Long_Float; -- Duration : Long_Float; -- LoadLoop : Integer;

procedure Ball is -- Local Variables of the Bouncing Ball State, Dot : Integr.Vector; Rate, Fine : Long_Float; Loopcnt : Integer; Start, Stop : Long_Float;

begin -- Get the Start time from the Wall Clock. Start := esimGetWallclocktime;

-- Get DeltaT Time from the EuroSim Tool. Rate := EsimGetTaskrate; DeltaT := 1.000/Rate; Fine := DeltaT/Long_Float(100);

for Counter in 1 .. 100 loop State(1) := Height; State(2) := Velocity; Dot(1) := Velocity; Dot(2) := -GRAVITY;

-- Forward Euler Integration. Integr.intEulerADA( State, Dot, 2, Fine );

-- Check on events, e.g. Ball touches the ground. if State(1) < 0.0 then State(2) := -State(2); end if;

Height := State(1); Velocity := State(2); end loop;

Loopcnt := 0;

-- Loop to increase the computation time of the model. for Counter in 1..LoadLoop loop Loopcnt := Loopcnt + 1; end loop;

-- Get Stop time from the Wall Clock and calculate Duration. Stop := esimGetWallclocktime; Duration := Stop - Start; end Ball; end Ball;

c Airbus Defence and Space 213 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

214 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 16

C++ interface reference

16.1 Introduction

The C++ API is a complete Application Programmer Interface (API) for integration of models written in C++ with EuroSim. It provides both the functionality to connect the models to the EuroSim framework as a set interconnection mechanisms to integrate models with eachother. In contrast with the classic Eu- roSim approach which uses parsers and GUIs to incorporate and integrate models, the C++ API provides an easy and intuitive programmers interface to accomplish this. This interface is designed such that it is intuitive and takes minimal effort for the user to develop, incorporate and integrate models in Eu- roSim. The interface also fits very well with usage from modern tools such as Eclipse and UML design tools. The performance and capabilities of the C++ interface are at least equivalent to the classic proven interface, including support for hard realtime execution. The C++ API consists of six API sections:

• Services: the runtime platform service functions that models can use as for example reading the simulation time,

• Publication: the mechanism and associated functions that models can use to publish (member) variables and methods or functions in the EuroSim dictionary,

• Type Library: EuroSim C++ suitable implementations of Vector, List and Map that support the publication mechanism and can be used in hard realtime simulators,

• Integration: A C++ API solution to support interconnection of models,

• Error Injection: An extension on the integration API part to support error injection,

• Exceptions: Throwing and catching exceptions in the context of the CPP API.

Three examples are provided with the installation that show the basic usage of the C++ interface for different parts of the API. The Satellite++ example is intended for general usage and focusses on pub- lication and type library usage, the SatelliteUML focusses more on the integration of model instances. This model also contains the UML transformer, an extension to Enterprise Architect that can generate code. However this is not yet available in EuroSim mk7.0 due to the extension of the port interface. The ThermoCpp1 exampel is the best example for developers of test systems, which uses the C++ API in combination with the EuroSim standard heaters and sensors example. This includes the use of Error Injection capabilities. Far more powerful examples that show the C++ API in a context of a representative situation are the ThermoMra1 and ThermoMra2 example. These examples use the Thermo example in combination with the MRA library (section 17) and the Front-end Models (section 29) and the reuse of Simulink models (section 20).

c Airbus Defence and Space 215 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

In this chapter we first show the setup of EuroSim for usage of the C++ interface in the section 16.2. In the following sections the different parts of the interface are explained in detail; Section 16.3 explains the publication interface, section 16.4 the available runtime interface functions, section 16.5 the data types that can be used in the C++ interface, section 16.6 the exception handling for the CPP interface, section 16.7 the model integration concept and functions, section 16.8 the support for error injection and section 16.9 the UML support provided via Enterprise Architect. Finally tips and guidelines are provided in section 16.10.

16.2 Setup procedure

The EuroSim C++ API is provided as a build option. To enable support for this API, tick the check box in the Model Editor build options. See Figure 16.1.

Figure 16.1: EuroSim C++ build option

When the EuroSim C++ support capability is switched on, the users model software is required to imple- ment a bootstrap function called esimCppSetup in which scope the developer should create all objects and publish them into the EuroSim dictionary:

bool Esim::esimCppSetup(bool runmode)

This function provides a return value of false to indicate to EuroSim that the publication process has failed and aborts the simulator before the scheduler starts. The runmode argument is true if the simulator is running, and false in when the dictionary is generated as part of the simulator build (dictgen). The runmode can be queried from esimCppSetup (or from functions/methods called from it) using:

DictPublishMode getDictPublishMode()

216 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

This function returns Esim::BUILD MODE or Esim::RUN MODE consistent with the runmode argu- ment passed to Esim::esimCppSetup function. The getDictPublishMode function can be used to prevent that certain functions (e.g. esimThreadCreate)= are called from Esim::esimCppSetup function when the dictionary is build. The use of the getDictPublishMode function prevents that the runmode argument needs to be passed as an argument to all the functions and methods called from the Esim::esimCppSetup function. Generally it is found that the C++ model code contains an OO factory pattern, which defines one object that creates all other objects and can be seen as the root of the object hierarchy. The esimCppSetup func- tion scope is the appropriate time and location to create such factory object and initiate its functionality. The allocation of memory for objects is automatically rerouted by EuroSim to its real-time memory allocator (esimMalloc), such that new and delete operators can be used safely without endangering the real-time performance. When all objects are created, the models must be published in EuroSim’s dictionary. The preferred approach is to use the recursive mechanism, in which case for every model that is to be published directly under the /CPP root node, the following function should be called:

bool Esim::publish( object,"dictionary name",<"description">, )

The details on the recursive publication mechanism and function arguments are explained in Section 16.3. The publication result is a reflection of the object hierarchy in the dictionary. Figure 16.2 illustrates the CPP root node and models that are published underneath.

Figure 16.2: CPP Dictionary node

c Airbus Defence and Space 217 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

As shown in 16.2 the function call publishes the information on objects under the name /CPP/.../objectname in the dictionary with the in the EuroSim dictionary. The optional vis- ibility argument is related to decluttering the view of the dictionary for operators by hiding developer only items. The publication API provides functions to further shape the dictionary and add more details. All other tools that use the dictionary, such as the ScheduleEditor and the SimulationController are unchanged and function with the C++ interface as they did with the classic EuroSim languages. Following listing shows the setup approach in a small example.

Listing 16.1: Example of source code organization using the C++ API #include

class Example { Private: Float aFloatAttribute; Int anIntAttributeArray[10]; void someMethod(); Public: virtual esimPublish(); }

Bool esimPublish() { result=true; //to return the status of publication to higher levels, ultimately \esim itself

result=result&&Esim::publish(aFloatAttribute,"aFloatAttribute’," Description of a float"); result=result&&Esim::publish(anIntAttributeArray,"anIntAttArray","An integer array publish"); result=result&&Esim::publish(&Example::someMethod,"someMethod"," publishing a method");

result=result&&Esim::setUnit("aFloatAttribute","kg"); result=result&&Esim::setMin("aFloatAttribute",0.01); result=result&&Esim::setMax("aFloatAttribute",0.99); result=result&&Esim::setParameter("aFloatAttribute",0.99); result=result&&Esim::setInput("aFloatAttribute");

}

void esimCppSetup() { Example* expl=new Example(); Esim::publish(*expl,"example","publishing my example directly under the /CPP root"); }

16.3 Publication interface

16.3.1 Standard publication interface The goal of the C++ publication interface is to show all the variables and entrypoints in objects in a tree format that reflects the ownership relations (composition or aggregation) between instances in your application. If Object A is a composition of Objects B and C, then in the dictionary Objects B and C should be child nodes of Object A. These ownership relations are enclosed in objects through their member variables. The EuroSim C++ interface uses a simple but effective recursive mechanism that

218 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

publishes objects and subsequently its member variables. The mechanism requires that every object that is to be published must provide an esimPublish() method:

bool esimPublish()

When performing Esim::publish(x, "x") on an object x, the publication mechanism adds object "x" to the dictionary and subsequently calls x.esimPublish(). The esimPublish method of the model should contain the publication code of each attribute and method that the model wishes to publish in the EuroSim dictionary.

bool Esim::publish(attribute,"attr_name", <"descr">,) bool Esim::publish(&class::method,"method name", <"descr">,)

The publication always starts from the current scope, which is the object that contains the esimPublish call. There are three functions available to the user to change the scope:

• bool Esim::getScope(char* scope)

• bool Esim::setScope(const char* new_scope)

• bool Esim::cmpScope(const char* my_scope)

Esim::getScope(buffer) sets the provided argument buffer to the current scope (the caller thus has to provide the memory). Esim::setScope("my new scope") changes the current scope to the relative or absolute path argument. Esim::cmpScope("my own scope") matches the argu- ment with the current scope. All three routines return true in case of success. As shown in above listing, the actual publication of attributes and entrypoints is accomplished through the call Esim::publish:

bool Esim::publish( item, dictionary name, <"description">, )

Where:

• item defines the object, attribute or method that is to be published.

• "dictionary name" defines the name that should be used in the dictionary to identify the published item, which in most cases will be the object, attribute or method name,

• <"description"> defines an optional description that will be visible in the GUIs, e.g. in monitors in the SimulationController to aid the user in working with the simulation.

• <"visibility"> defines an optional setting that regulates if the published item is by default visible to developers of the simualtor and operators (value true), or whether this an item that shoudl normally not be accessed by operators and just clutters there view (value false). This capability does not completely avoid access to operators, it is an aid to avoid but not to restrict. The operator can still switch a dictionary view to developer mode and then see all developer restricted variables.

Through extensive overloading, the same method can be applied for every type that is to be published, being either an object, an attribute of an object or a method of an object, or a static method. For example:

Esim::publish(attribute, "attribute", "description of the attribute") Esim::publish(&method, "method", "description of the method") Esim::publish(object,"object","description of the object")

There are situations where the Esim::publish() method needs additional information from the user to achieve the desired publication. This concerns enumerations, structures and strings. Generally the best way around this is to use the typed API with the esimGetTypeName function (see 16.3.3). However for the enumeration and strings there is also the following work arounds:

c Airbus Defence and Space 219 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• The first case is for enumerated types . In the C++ 98 standard which EuroSim must support the enumerated type is mapped on an integer or unsigned integer depending on the compiler but in the dictionary the type can be known if that type is either in C source code that is parsed by the EuroSim parser or if the type is published in the dictionary via the Esim::enumeration interface. The easiest approach in which EuroSim will try to detect the type is to use the publish_enum method:

Esim::publish_enum(attribute,"attribute",<"description">,)

The advantage of this approach is that EuroSim will first try to detect the type and find it in the dictionary, and if succesfull it will show the variable with the correct labels in the EuroSim Simulation Controller API and MMI tabs. If it does not succeed it will determine what base type the compiler selected for this enumerated type and ublish accordingly. There is also a solution, called typed publication, in which the user can provide the type of the attribute, overriding any detection mechanisms. This is explained in section 16.3.3.

• The second case is for strings of type char*. The char* type conflicts with char[] in the overloading and unfortunately you can not have both at the same time. The solution provided is that by default the char[] is supported, which automatically detects the size of the array and publishes the array variable correctly in the dictionary. If char* support is needed, for instance because it is the type of the key of an Esim::Map (see section 16.5), then this can be enabled by placing #define ESIM_CPP_STRING before is included in the source file. After that point in that file, both char* and char[] publication assume the user intents to publish a zero terminated string and it determines the amount of characters to publish based on strlen.

The name with which a published item will appear in the EuroSim dictionary will in most cases be just the name of the object, variable or method that is published. However, this can be a relative or absolute path. A relative path is written as a command line directory navigation, e.g. ”../../myobject/myitem” will publish the item ”myitem” not as a child of the current object but as a child of the object myobject that exists two levels up in the hierarchy. An absolute path starts with /CPP, the root node in the dictionary for all models software that uses the C++ API. (See Section 16.3.1 for a description of the recursion mechanism). The optional description <"description"> in the method definition is only used to provide extra information to the user of the simulation in which the model is applied. If the optional description argument is left out, an empty string is applied. As shown in the example the description can also be set later on, after an item is published. A special case of that is setting the description of an object from within its own publication routine. When publishing a derived class by calling the publish routine of its base class, the desciption can then reflect information about the dervied class. The publication of variables using overloading works on multi-dimensional arrays just as on scalars. The overloading will automatically detect the dimensions of the variable and assure a proper incorpora- tion in the EuroSim dictionary such that it becomes available in EuroSim GUIs and scripting as multi- dimensional array. The maximum number of dimensions is currently limited to five, thus supporting arrays, matrices, cubes. and even 4- and 5 dimensional variables. We have not seen a demand for higher number of dimensions then three and thus expect up to 5 dimensions to be more than sufficient. Please contact the helpdesk if you have a case where more then 5 dimensions are required, workarounds are readily available and patch release can be provided. Note also that there is a fundamental difference in how multi-dimensional variables are stored for standard types and C-type structures versus objects that include methods. For objects, each object is seperately defined in the dictionary, which leads to large dictionaries and more processing time. If you have C-type structures we recommend publishing using the typed publication approach ( Section 16.3.3). A special case of Esim::publish overloading allows the creation of an empty object, or in other words a folder or tree node in the dictionary. When using

220 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Esim::publish("itemname",);

A folder is created in the dictionary with name itemname. The argument itemname may include an absolute or relative path specification to create a node anywhere in the dictionary. Use either the relative path mechanism to publish items in the created folder, or use Esim::setScope to set the publication scope to the newly created folder.

16.3.2 Adding publication details When adding models to EuroSim via the classic C API approach, the EuroSim ModelEditor supports the user in adding minima, maxima and unit definitions to variables in the dictionary. With the C++ API, this information can be added from the model software, and not only for a variable but also for fields of structures. In case of the latter the type is annotated in the EuroSim dictionary so the change applies to all the variables of that structure type in the dictionary. It is also possible to manipulate the attributes of a field of a type via the typename. The Esim namespace contains the following methods to set the attributes of C++ variables (via their path in the dictionary, where needed including the dot selector for fields of a structure):

• bool Esim::setMin("dictionary name" ,minimum value) • bool Esim::setMax("dictionary name" ,maximum value) • bool Esim::setUnit("dictionary name" ,"unit") • bool Esim::setDescription("dict name" , "description") • bool Esim::setDescription("description") • bool Esim::setAttr("dict name", "min", "max", "unit", "description") • bool Esim::setParameter("dictionary name" ,true (default) or false) • bool Esim::setInput("dictionary name") • bool Esim::setOutput("dictionary name")

Where: • setMin, setMax, setUnit, setDescription, setAttr all accept a dictionary name that can either be the dictionary path of a normal variable as well as the path to a field of the vari- able if it is a struct (path/var.field). The other methods only work on path variables and fail if a path contains the dot selector. • setUnit, setMin, setMax have the same meaning as in the classic C API, • setInput and setOutput can be used to manipulate the variable node icon to show the end user (e.g. in the Simulation Controller) that the variable is an input or output variable. This differs from the Access point of view taken in the classical API, where the parsers show whether entrypoints read or write in the variable. In the C++ API such information is not present and the input or output marking becomes a means by which the developer can visualize to the end user this this variable can be set during simulation (input, arrow pointing into the box) or is of interest for monitoring or recording (output, arrow pointing out of the box), • setParameter marks the variable as one that only can be set at the start of the simulation, i.e. can only be set via an initial condition, • setDescription is added to support setting the description of a dict variable separately from the publication. The special version with only a description as argument sets the description of the current object and is very usefull to show derived class information for objects in vectors, lists and maps.

c Airbus Defence and Space 221 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• setAttr allows to set the min, max, unit and description attributes in one go. This interface accepts a NULL for attributes that should not be changed. The Esim namespace contains the following method to manipulate the attributes of a field of a structure via the type name of the structure: • bool Esim::setAttr("typename","fieldname","min","max","unit","descr") Where: • typename is the name of the type in your code. The typename should be known in the dictionary. This can be enforced by putting the variable of the type in a C file as the EuroSim parser will see it and put it in the dictionary for you, or by using the CPP methods to define a type in the dictionary. • fieldname is the field in the structure of type typename that you want to manipulate • min max unit description are the arguments that define the new names to be set in the type. When a NULL is passed no action will be taken for that argument.

16.3.3 Typed publication The Typed Publication API is very similar to the standard publication API, but circumvents the overload- ing mechanismby providing the typename as an extra argument. The user can pass a string that identifies a type specification which is known in the EuroSim dictionary or use the esimGetTypeName() function to detect the name of the type. In most case the normal approach will work and the typed publication is not needed, but typed publication is a powerful mechanism to perform the unusual cases. Following example shows the typed publication functions: bool Esim::publish( "dictionary typename", object, "dictionary name_path", <"description">, )

bool Esim::publish( esimGetTypeName(object), object, "dictionary name_path", <"description">, )

The esimGetTypeName() function uses the gcc compiler ABI to detect the typename, which requires that the type must be defined in the dictionary prior to this call. Additionally, namespaces can be a problem in resolving the typename correctly. If esimGetTypeName() can not detect the typename it returns a null pointer. This typed publication is particularly usefull for publication of variables of a complex C style type such as structs, unions and enumerations. The easiest interface to get the type correctly entered in the dictionary is via the EuroSim C parser. Declare a static variable of the type in a C file and include that file in the model editor files tab. It is not necessary to publish the variable via the C API, the parser will already go through the file, encounter the variable and fill the dictionary with the type information. The build process will parse the C files before publishing models via the C++ API. The dictionary typename is the same name as the type of the variable in the C file and its specification in the dictionary includes all additional information added in the ModelEditor such as units, minumun, maximum and description. All types defined in the dictionary using the EuroSim C and Fortran parsers are known when publishing C++ interface based models. Besides the benefit of an easy to use interface to define types in the dictionary, the usage of the parser also ensures that the type remains consistent with its definition in the header file because in every (re- )build the parsers will check the consistency, which outweighs the possible overhead of a global variable that may not be used. However in some cases this approach is unnecessary complex, in particular for enumerated types where the user mainly want to have the benefit of seeing labels in the Simulation Controller rather then integer numbers. For enumerated types a function is provided to allow the user to add a specification of the enumerated type with labels to the dictionary.

222 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

bool Esim::enumeration(const char *type, int nr_labels, const char *label, int value, ...)

The Esim::enumeration function allows the user to define an enumerated type in the dictionary in order to see labels instead of values in the EuroSim Simulation Controller. The previously described approach of defining the type in the dictionary by creating a variable of it in a C file has benefits, but for merely associating labels to values, it may be overdone. In such case the user can also use the above enumber- ation function to add an enumeration type to the dictionary. The provided type string defines the name of the enumerated type in the dictionary, the nr_labels argument defines the number of fields of the enumerated type, and subsequent label-value pairs attach a label to an enumerated type value. Using typed publication the programmer can publish a variable for which EuroSim will assume that it is an enumerated type as defined in the dictionary for the specified type name. There is also function to enter structures in a similar way into the dictionary, however, please consider the padding. The C parser will automatically get the offsets right. The structure function requires that you specify padding member variables to assure that the correct offsets are used in the type definition.

//defined in esim++publish.h namespace RTS { typedef struct { const char *type; const char *field; const char *min; const char *max; const char *unit; const char *descr; } structline;

bool structure(const char *name, int nr_lines, const structline first, ...); }

As shown above, the Esim::structure call takes as argument the typename of the structure in the dictio- nary, the number of struct member lines and for each member the attributes. It is advised to use the EuroSim parser but the above is available.

16.3.4 Esim::Object The EuroSim API design goal is to minimize the constraints put on the programmer. An approach where everything is to be derived from EuroSim defined base classes was therefore not followed in the basic C++ API and hence it is not required. However, there is some benefit to deriving from a EuroSim class because it can support a mechanism to find objects. All EuroSim pre-implemented objects that are introduced in successive sections and chapters are therefore derived from this interface. Examples are the base classes of the MRA modelling support library that adds a predefined architecture to models and regulates their scheduling. Additionnaly the Links, Ports and Line objects are all derived from Esim::Object. The main features of the Object interface is that any object derived from it can be retrieved because each object has the reference to its information in the EuroSim dictionary, as well as that each object has an unsigned integer id which can be used for object retrieval. Objects can be found with the functions:

Object* getObject(const char *dictpath); Object* getObject(unsigned id);

c Airbus Defence and Space 223 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The first function finds the object in the EuroSim dictionary using the dictionary path. This requires that the object is published, otherwise such path does not exist. The second function relies on an id that is stored in the object. On creation, the ID is automatically generated based on a counter that increases with each new object. This id can be retrieved but it can also be changed. Especially the latter is usefull if the user wants to built up a list of numbers that refer to a specific objects.

Object* object= new ObjectDerivedClass(); bool result=object->getId(); bool result=object->setId(unsigned value); bool result=object->setIdCounter(value);

The getId() function returns the default id number, which starts counting up from 1. A zero id value is reserved to indicate a failure in the id management. The setId(value) function changes the id value of the object. Setting the value to zero or to a number that is already in use will lead to a warning and a false return value. If this function is used it is up to the user to assure that the default counting does not interfere with the numbers that are used via setId(). using high values beyond the number of objects created in the simulator is a valid approach. Alternatively the setIdCounter can be used to let the automatic number start at the offset of the value passed as argument. The latter approach reserves the numbers 1 to value for the programmer.

• void Esim::switchDisplayObjectId(OnOffMode onoff)

Note that all the EuroSim provided objects for simulator integration, such as Links, Ports, Lines and Models are derived from Esim::Object and can publish the object id in the EuroSim dictionary such that the user can see the number that was automatically assigned when the object was created or explicitly assigned by the user. Such id is always only displayed when the dictionary is viewed in developer mode and only after such display is enabled using the switchDisplayObjectId function below. The default setting is disabled as even in developer mode it can annoyingly clutter the view and take screen space if not needed. An interested user thus as to enable it. Note that using the Object ID provides a means to find models that were created without the need to maintain a reference, however this is not not only means available to find models. For instance the MRA::system object probvides a method to get a model by name, and similarly the FeModels have an interface to get a Bus and Line and operate it, or to retreive a Mil1553 RT or a specific buss.

16.3.5 Publication configuration and debugging The C++ API provides a number of configuration functions to support debug features and memory opti- mization features that are built into the C++ API.

• typedef enum Esim::OnOffMode_tag { OFF=0, ON=1 } OnOffMode

• void Esim::switchPublishVariable(OnOffMode onoff)

• void Esim::switchPublishEntrypoint(OnOffMode onoff)

• void Esim::switchPublishDescription(OnOffMode onoff)

• void Esim::switchPublishUnit(OnOffMode onoff)

• void Esim::switchPublishMinMax(OnOffMode onoff)

• void Esim::switchPurgeObject(OnOffMode onoff)

• void Esim::switchNullPointerWarning(OnOffMode onoff)

• void Esim::switchTrace(OnOffMode onoff)

224 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• void Esim::switchCycleDetection(OnOffMode onoff)

• void Esim::switchDisplayObjectId(OnOffMode onoff)

• void Esim::switchNewToCalloc(OnOffMode onoff)

The functions switchNullPointerWarning, switchTraceEsim, switchCycleDetection support the debug- ging of the publication process. The C++ API generates a warning whenever it encounters a null pointer in the publication process, ignore this error and continue. The default is thus ON, but this can be sur- pressed, for instance when large amounts of nullpointers still occur because the code is not complete yet. The function switchTrace can be use to activate the tracing capability of the C++ API (default is off). The tracing feature will generate a message for every call to a publish routine, showing the dictionary path of what is to be published. The switchCycleDetection function can be used to activate the cycle detection feature of the C++ API. Especially when generating the code from UML, associations lead to objects publishing eachother. The Cycle detection looks for repeating patterns in the path and generates an error message if one is found. In such cases one of the publish calls must be removed. The default value of the cycle detection feature is Esim::OFF. The switchPublish functions and the switchPurgeObject function are related to memory consumption. These functions only need to be used in extreme cases of many objects and severe memory limitations. The default value is therefore OFF. The switchPublish routines switch the publication of a category of dictionary items on or off. The PurgeObject function removes an object that has no attributes in the dictionary directly after completion of publishing object. Objects without attributes are never visible in the EuroSim, and thus may as well me removed from the dictionary to reduce memory consumption. Be carefull though when using relative paths, as when removed you cannot add attributes in a later stage. The switchNewToCalloc function can be switched on to assure that all dynamically allocated memory (heap space) is nulled. Quite often the source of a problem is that the object is not well initialized as member variables do not have a default initialization. using this functoin assures that the memory contains zeroes. This is at the expense of extra processing time to allocate memory. The procesing time of heap space allocation is usually not such a problem in EuroSim simulation because often the memory is only allocated in the initializing state.

16.4 Service interface

The Services section of the C++ API is essentially a C++ style written version of the classic EuroSim C API. Thus where the EuroSim C API functions have esim as a name prefix, the C++ API functions have Esim as namespace. A function esimMessage() becomes Esim::message(), and an enumerated type esimState becomes the enumerated type Esim::State. The EuroSim C++ API is defined in the file esim++Services.h (which is automatically included by esim++.h). Following is a complete listing of the EuroSim C++ API in relation to the C API functionality. The detail of each function can be found in in the manual page esim++services and is exactly the same as for the EuroSim runtime C API.

Listing 16.2: EuroSim’s C++ API in relation with the C API

REALTIME MEMORY ALLOCATION: void *malloc(size_t size) void free(void *ptr) void *realloc(void *ptr, size_t size) void *calloc(size_t nelem, size_t elsize) char *strdup(const char *str)

REALTIME TMING FUNCTIONS:

c Airbus Defence and Space 225 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

double getSimtime(void) int setSimtime(double simtime) struct timespec getSimtimets(void) void getSimtimeYMDHMSs(int t[7]) double getWallclocktime(void) struct timespec getWallclocktimets(void) double getHighResWallclocktime(void) int setSimtime(double simtime) int setSimtimets(struct timespec simtime) int setSimtimeYMDHMSs(int t[7])

REALTIME STATE FUNCTIONS: State getState(void); int getState(State state); int setStateTimed(State state, const struct timespec *t, int use_simtime) struct timespec getMainCycleTime(void) struct timespec getMainCycleBoundarySimtime(void) struct timespec getMainCycleBoundaryWallclocktime(void)

REALTIME TASK RELATED FUNCTIONS: const char *getTaskname(void) double getTaskrate(void) int enableTask(const char *taskname) int disableTask(const char *taskname) int entrypointFrequency(State state, const char *entrypoint, double *freq) Entrypoint *entrypointGet(const char *entrypoint_path) int entrypointEnable(Entrypoint *entrypoint, bool enabled) int entrypointExecute(Entrypoint *entrypoint) int entrypointFree(Entrypoint *entrypoint) int getRealtime(void) int setRealtime(int on)

EVENT FUNCTIONS: int eventRaise(const char *eventname, const void *data, int size) int eventRaiseTimed(const char *eventname, const void *data, int size, const struct timespec *t, int use_simtime) int eventCancelTimed(const char *eventname) int eventCount(const char *eventname) int eventData(void *data, int *size) int eventCount(const char *eventname)

REALTIME CLOCK FUNCTIONS: double getSpeed(void); int setSpeed(double speed)

REALTIME RECORDING FUNCTIONS: int getRecordingState(void) int setRecordingState(int on)

REALTIME REPORTING FUNCTIONS: void message(const char *fmt, ...) void warning(const char *fmt, ...) void error(const char *fmt, ...) void fatal(const char *fmt, ...) void report(int s, const char *fmt, ...) int reportAddSeverity(const char *sev_name)

NON-REALTIME THREAD FUNCTIONS

226 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

thread *threadCreate(const char *name, void (*start_routine)(void*), void *arg) int threadKill(Esim::thread *thread, int signal) void threadExit(int exit_val) void threadJoin(Esim::thread *thread) void threadDelete(Esim::thread *thread)

METRICS FUNCTIONS bool setLoadMeasureInterval(int processor, double interval) bool getProcessorLoad(int processor, double *avg_load, double *max_load) void getHeapUsage(size_t *tot_size, size_t *max_used, size_t * current_use)

RACE FUNCTIONS void tracePause(void); void traceResume(void); void traceMask(unsigned type_mask, unsigned proc_mask);

The above C++ API functions thus wrap the EuroSim C API functions, and thus have the same argu- ments, effect and results as defined for the C API.

16.5 Supported data types

16.5.1 Basic types and arrays The EuroSim C++ interface supports the C++ basic data types, and arrays thereof. The table below show how they are mapped to a type in EuroSim:

C++ type EuroSim Type Description bool 8 bit unsigned integer type byte 8 bit signed integer type char 16 bit unsigned integer type short 16 bit signed integer type int 32 bit signed integer type long 64 bit signed integer type float 32 bit floating point type double 64 bit floating point type

16.5.2 Predefined structured types The EuroSim C++ interface also supports the following vector, quaternion and matrix types (note that with Mk7 it is also possible for ports to use arrays instead):

c Airbus Defence and Space 227 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Type EuroSim Type Description struct EsimVector2 Vector of 2 doubles: x, and y struct EsimVector3 Vector of 3 doubles: x, y, and z struct EsimVector4 Vector of 4 doubles: p, q, r, and s struct EsimQuaternion Quaternion (scalar last) of 4 doubles: q1, q2, q3, and q4 struct EsimMatrix22 Matrix vector of 2x2 doubles: - m11, m12, and - m21, m22 struct EsimMatrix33 Matrix vector of 3x3 doubles: - m11, m12, m13, - m21, m22, m23, and - m31, m32, m33 struct EsimMatrix44 Matrix vector of 4x4 doubles: - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, and - m41, m42, m43, m44

16.5.3 Container Types In addition, the C++ API also provides a number of container types to provide a similar capability as the Standard Template Library. These containers support the recursive publication mechanism and allocate memory for their internal administration before publication; hence the maximum size must be provided at compilation time. Following container types and for each type a number of methods are provided. Esim::Vector

• void clear() Resets the administration of the Vector (contained objects are not destroyed by clear)

• size_t size() const Returns the number of elements added to the vector.

• template void foreach( Functor&) Iterates through all the el- ements in the vector and call for each element the user defined functor with the element as argu- ment

• bool push_back(const Element&,const char* name="", const char* description="" ) Adds element to the back of the vector. The optional name and description allow each element to appear in the vector with a user defined name

• bool pop_back() Remove the element at the back of the vector.

• Type& front; Provides a reference to the element at the front of the vector.

• const Element& front() Const version of front().

• Element& back() Provides a reference to the element at the back of the vector.

• const Element& back() Const version of back().

228 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• Element& operator[] (int index) Provides a reference to the element at the specified index in the vector

Esim::List

• void clear() Resets the administration of the Vector (contained objects are not destroyed by clear)

• size_t size() const Returns the number of elements in the list.

• template void foreach( Functor&) Iterates through all the el- ements in the vector and call for each element the user defined functor with the element as argu- ment .

• bool push_front(const Element&,const char* name="", const char* description="") Adds element to the front of the list. The optional name and description allow each element to appear in the list with a user defined name

• bool pop_front() Removes element from the front of the list.

• bool push_back(const Element&,const char* name="", const char* description="") Adds element to the back of the list. The optional name and description allow each element to appear in the list with a user defined name

• bool pop_back() Removes element from the back of the list.

• bool insert_after(const Element& after, const Element& e, const char* name="", const char* description="") Inserts element e after element after. The optional name and description allow each element to appear in the list with a user defined name

• bool insert_before(const Element& before, const Element& e, const char* name="", const char* description="") Inserts element e before element before. The optional name and description allow each element to appear in the list with a user defined name

• bool remove(const Element&) Removes element from list.

• Element& front Provides a reference to the element at the front of the list.

• const Element& front() Const version of front().

• Element& back()Provides reference tothe element at the back of the list.

• const Element& back() Const version of back().

• Element& operator[] (int rank) Provides a reference to the element that is at the po- sition rank in the ordered list.

Esim::Map

• void clear() Resets the administration of the Vector (contained objects are not destroyed by clear)

• size_t size() const Returns the number of elements in the map.

c Airbus Defence and Space 229 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• template void foreach( Functor&) iterates through all the el- ements in the vector and call for each element the user defined functor with the element as argu- ment .

• Element* find( const Key& ) Return a pointer to the element that has the provided key, or NULL otherwise.

• const Element* find( const Key& ) const const version of find().

• bool insert(const Key&, const Element&, const char* name="", const char* description="") Inserts the provided Key,Element pair in the map. The optional name and description allow each element to appear in the map with a user defined name

• bool remove(const Key&) Removes the element with the provided Key from the map.

• Element& front Provides a reference to the element at the front of the map.

• const Element& front() const version of front().

• Element& back() Provides a reference to the element at the back of the map.

• const Element& back() Const version of back().

In general the methods of the container types have the same meaning as their counterparts in the C++ standard template library, with the exception of the remove method and the foreach methods. The remove method only removes the element from the container, it does not deallocate memory. The foreach meth- ods replaces the iterator mechanism of the standard template library. It iterates through all the elements in a container, with for each element executing the functor with a reference to an element as argument. This provides an easy interface without the need for inheritance. The functor is used by reference and can be used to collect data as it iterates through the elements. Following example shows the use of the foreach and functor feature:

Class ListFunctor { Private: MyAttr attr; Public: bool operator()(MyClass* p) { attr+=p->aMyClassmethod(); }

}

Esim::List myClassList; ListFunctor f; myClassList.foreach(f);

These container types are provided via the include file esim++tl.h, but users are advised to include esim++.h as it will include any other files needed and supports portability. Note that this current template library is designed to support hard realtime execution, as well as the recursive publication mechanism. It is mostly in line with the C++ standard template library but deviations do exist as for instance on the iterators and the EuroSim solution is considerably less efficient. EuroSim does not prevent the user from using the standard template library in his model code, however it’s usage may affect the realtime execution and it is up to the user to assess if that conflicts with his requirements.

230 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

16.6 Exception handling

The EuroSim CPP API provides a set of exceptions that can be thrown in user software. These excep- tions are caught in the context of the EuroSim CPP setup function esimCppSetup and the activation of entrypoints by the scheduler. Exceptions are derived from Esim::IException which mandates that the exception contains a handle function which is called in the catch to handle the errors. The following default exceptions are implementations of this mechanism and transform the exception in an esimReport handling.

• Report: In catching handles the exception by calling Esim::report using the message and severity provided via the constructor of the Esim::Report class. This also triggers the event in the schedule associated with the severity (e.g. ERROR)

• Message: Transforms to Esim::Report with severity message.

• Warning: Transforms to Esim::Report with severity warning.

• Error: Transforms to Esim::Report with severity error.

• Fatal: Transforms to Esim::Report with severity fatal.

The mechanism is extensible in that the user can create his own exceptions and determine how they are handled. Following fragment shows how the Report class is an implementation of the interface demanded by Esim::IException: class Esim::Report : public Esim::IException { public: Report(esimSeverity aSev, const char *aDescr): mSev(aSev), mDescr(aDescr){}; virtual ˜Report(){}; virtual const char* getDescription() const {return mDescr.c_str())}; virtual esimSeverity getSeverity() const {return mSev;}; virtual void handle() const { esimReport(getSeverity(),"%s",getDescription()); } protected: ::std::string mDescr; esimSeverity mSev; };

The standard library exception std::exception is caught and transformed to an error message that will go into the journal.

16.7 Simulator Integration

Simulator integration concerns the interconnection of models with eachother and with the platform into a simulator. Assuming the model developer follows an object oriented approach using the CPP api, this leads to the creation of model instances in the dictionary. Thereafter the integration or interconnection between the models is performed. Performing this after instantiation and publication of the models reduces the dependency between the models, supporting reuse and flexibility in the models.

c Airbus Defence and Space 231 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Traditionally model interconnection in EuroSim is performed by copying data variables from the outputs of a model to the inputs of another model. The data copy actions are entrypoints that are scheduled such that this copy action is executed mutual exclusive with the two models between which the data is copied. Since the copy is short this approach allows the computationally more expensive step functions of the models to execute in parallel with the copy. Additionally the copy allows the injection of errors which is essential in testing of systems. The copy approach thus clearly offers benefits, but there is also a downside; it leads to many more entrypoints in the schedule which becomes a burden in maintenance. Alreay with EuroSim Mk6 the concept of links was therefore introduced. The Link in Mk6 was a managed pointer to an input or output variable of another model. This means that in comparison to ports, these models can not run in parallel and there is no error injection. There are cases however where scheduling is such that parallel execution can not occur and error injection is not needed and then usage of the Link prevents the need for scheduling of the copy entrypoints. The Link implements a managed pointer, which allows its contained pointer to be set to point to a dictionary path after the publication of an object. This offers the ability to integrate the models independently of the model code and after all models are created and published in the dictionary. Finally, in an object oriented programming environment as provided with the C++ API, it is more natural to have a pointer to a model or model interface than to have a pointer to a variable. With a pointer to a model (interface) you don’t read a variable a model but invoke methods to get or set the data, or even invoke other kind of services in the model interface. It would even be possible to implement an object between the two models, which models a line between the equipment models which provides a dataflow with error injection and protection against corruption of data due to the parallel operating models. The latter would give the benefit of the data copy approach with ports and channels, however without the need to schedule the entrypoints as the actions normally triggered by the entrypoint can be performed on the method invocation from link to the intermediate line models. Support for the interface based approach as well as the extension with the intermediate line models is integrated with the EuroSim Mk7.1. This section will explain the APIs for classifying models in the dictionary and the above mentioned three approaches for model interconnection. Subsections 16.7.2 and 16.7.3 explain the mechanisms to establish the entrypoint based data copy approach. Subsection 16.7.4 elaborates the mechanisms to establish the managed pointer approach (Link), both to data as well as to objects. Subsection 16.7.5 provides the information on how to use the generic Line object to create a dataflow interface based on the usage of links.

16.7.1 Identifying Root Models The simulator integration interface is intended for developers that create models and interconnect these into an assembly of models. The to be interconnected models are root nodes which underneath may split out in different objects with individual entrypoints. Generally it gives a better view to be able to show the root models as the building blocks of a simulator. This can be achieved by the addModel interface. This interface is merely marking the object as a CPP model in the dictionary and subsequently makes it appear with a different icon, in reality it remains a CPP object. However it clearly shows to the simulator integrator that these are the independent building blocks that are to be interconnected.

MODEL ADDING FUNCTIONS

bool Esim::addModel( T& object, const char *name, const char *descr="");

bool Esim::addModel( T (& object)[N], const char *name, const char *descr="");

232 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The resulting view in the dictionare is shown in 16.3 (from thermoMra example)

Figure 16.3: EuroSim CPP models in dictionary

16.7.2 Port-Channel The implementation of the data copy approach is implemented using the port-channel concept. A model creates input and output port objects that are the entry and exit points for flowing data into and out of the model. The interconnection is then accomplished by creating a channel from an output port to an input port. The channel is an object that contains an entrypoint which triggers the transfer of a data sample from output port to input port. It is up to the simulator integrator to schedule the channel entrypoint such that it does not run in parallel with the models when they are accessing the ports. The ports are visible in the dictionary as an element of the model, whereas the channels are objects that are independently visible in the dictionary, often group in a folder. The channel object displays the source and target port between which it copies data such that it can be checked via the dictionary by the end how data flows between models. The Port objects have error injectors which allow the user to change the data that the model software stores in the port or retreives from the port. The injection is thus not performed on the copy between the models, but on the access of the port from within the model. This is relevant when the unit model is tested in isolation. All other models including th channels can be deactived in an integrated simulator, while the model is tested by driving data into the inports and measuring in the outports. Default error injectors exist and allow the injection to be configured through parameters of the port object in the dictionary. Additionally it is possible to install a user defined error injector in the port to define the overriding or tranformation of data from the port or to the port. When the simulator is integrated the ports can be used to adjust the incoming or outgoing data using error injection functions, or to override the values with for instance values set by the user or by some MDL script (including stimuli from file).

c Airbus Defence and Space 233 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

With EuroSim Mk7 the API for ports fundamentally changed from Mk6. In Mk6 the design avoided the declaration of port or link objects. Instead it provided functions that would create these objects from within the esimPublish function. This approach was driven by the desire to be able to still compile the model software outside the EuroSim environment. The isolation of all unique EuroSim code in the esimPublish accomplished this. This benefit however did not way up against the downside of the more complicated usage in the model software and the need to schedule three entrypoints to achieve the desired error injection. With Mk7 the ports are templated objects that the model developer creates as member variables. The publication is then performed in the same approach as all member variables, using the Esim::publish function. The Port is an object that implements an esimPublish method and hence knows how to publish its content in the dictionary. After publication a Port will show its error injection attributes and port value attributes in the dictionary tab as children of the port. In case of an InPort the variable attribute of a port shows the value received via a channel, unaffected by any activated error injection. In case of an OutPort, the value attribute of the port shows how the original value from the model software is changed by the error injection, if the injector is enabled. When declaring multi-dimensional ports, up to 5 dimensions can be set. You can create an array of ports, or a matrix of ports etc. The Esim::publish function will assure that you will get a port for every element. Note that this differs from a port on an array, such as a vector. In these cases it is best to create a C type struct and make a port on that struct type. EuroSim alread provided types for EsimVector etc. which work in this manner. These also show the relevance of making a struct with respect to error injection. A port on the vector has one set of parameters to control the error injection on all elements of the vector simultaneously. If an array of ports is created such that there is a port for each element of the vector there are multiple injectors and hence for instance multiple enable flags. Note that if a new struct is created for this reason, the error injector for that struct type needs to be written by the user. The default port will not have error injector support. It is easiest to look into the EuroSim header file esim+++inject.h and specialize a class ErrorInjector¡yourtype¿. The API for the model developer to interconnect ports is:

INPORT DECLARATION: //declare an inport for data type T[N], with PortMode M and injector I //Mode is NoInject, Passive, Active or ReadWRite. S is the StructMode and //allows informing the port that the type is an object (ObjectMode is deault)( //or C type struct (POD) Esim::InPort, S=ObjectMode > inport;

INPORT METHODS: //for N=1 bool read(T& v); //read data from port for mode Esim::ReadWRite //triggers error injection const T& peek(); //peek inside port, skipping error injection void poke(const T& v); //poke into port, skips injection

//for N>1 bool read(T v[N]); //read data from port, triggers error injection const T* peek(); //peek inside port, skipping error injection void poke(const T v[N]); //poke into port, skips injection

//for all N bool inject(); //Force error injection for mode Esim::Passive setInjector(ErrorInjectorBase* i); //replace default injector //with user defined injector //(see section error injection)

234 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

INPORT OPERATORS: //for N=1 operator T(); //read data from port if in ReadWrite, returns var operator T*(); //peek inside port , no error injection in ReadWrite InPort& operator=(const T& v); //poke into the port

OUTPORT DECLARATION: //declare an outport for data type T[N], with PortMode M and injector I Esim::OutPort, S=ObjectMode > outport;

OUTPORT METHODS: //for N=1 void write(const T& v); //write data in ReadWrite mode port, //triggers injection in const T& peek(); //peek inside the port, skipping error injection void poke(const T& v); //poke into port, skips injection

//for N>1 bool write(T v[N]); //read data from port, triggers error injection const T* peek(); //peek inside port, skipping error injection void poke(const T v[N]); //poke into port, skips injection

//for all N bool inject(); //Force error injection for mode Esim::Passive setInjector(ErrorInjectorBase* i); //replace default injector //with user defined injector //(see section error injection)

OUTPORT OPERATORS: Port& operator=(const T& v); //assign data to the port, //triggers error injection operator T(); //poke data in the port, no error injection operator T*(); //peek inside the port, no error injection

PUBLISH METHOD: bool esimPublish(); //This supports Esim::publish(port, name, descr)

The API above allows the ports to be used in three approaches:

• Read from and write to the port explicitly via the read and write entrypoints. When these methods are used to read from or write to the port, the error injection is triggered. The internal variable in the port that is filled or extracted by the channel is shown as attribute value of the port. The data that is returned by read is changed by the error injector from value into injector::inject(value). Likewise the parameterof the write is changed by injector::inject(parameter) and the result is copied into value in the port. Of course the default error injectors have parameters to configure the injection and if that injection is not enabled via the dictionary variable publish by the injector as part of the port then the method injector::inject(sourcevalue) will have no effect. The usual usage of read is to read the data into a local variable at the start of the step function of the model. The local variable is used in formula’s and checks and any output data is then written at the end of that step function using the write() method of an output port.

• If the user wants to access the data without the effect of the error injection in the port then the peek and poke methods can be used. The peek returns the content of port::value and the poke sets

c Airbus Defence and Space 235 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

the content of port:value without going through the error injector. Instead of copying into a local variable, the peek and poke can be used to access the value attribute of the port multiple times in a step function. • Finally the port has overloaded type conversion operators. This allows the above to be achieved throug the use of operators, giving a more compact coding style. For an InPort pin, copying the port to a type T such as in T a=pin, is the same as T a=pin.read(). Getting the content of the port without error injection (peek) is performed by T a=*p. Finally poking a value into the port is achieved by p=a. For the OutPort pout this is slightly different: assignment pout=a triggers the error injection (write). The peek is performed by a=*p and the poke by *p=a. The following snippets show the usage of the port in model sofware. Esim::inPort inport; Esim::OutPort outport;

outport=10.0; //the value in the port may differ from //the value 10 due to error injection //if the port is in ReadWrite mode output.write(10.0); //same effect, but different style

double myvar=inport; //the value in myvar may differ from the //data in the port due to error injection //if inport has ReadWrite mode output.read(myvar); //same effect, but different style

double a= 10.0+inport;//a is 10.0 plus the value in the inport //there is no error injection, even when the //injector is enabled double *p=inport; double a=10.0+(*p); //a is 10.0 plus the value //in the inport , there is no error injection //and no need to further use the inport in the //the software

double a=inport.var[0]; //direct access to the variable in the port //for an inport this is after error injection double a=inport.val[0]; //direct access to the value in the port //for an inport this the transfered data // before error injection

Esim::publish(inport, "inportname", "my inport"); Esim::publish(outport, "outportname", "my outport");

When the port is created it automatically has a default error injector. If the template type of the port is a base type, the default error injector probably provides all that is needed in error injection capability and the model developer does not need to do anything extra. If the template type of the port is not a base type, the mechanism assumes the type is a EuroSim compliant class that implements an esimPublish() and esimInject(const T&) method. For C type (POD) structs there is a convenient solution in EuroSim to use the C parser to get the struct in the dictionary. To use such a struct however in as the type of the data that flows through the port requires special handling. Default the port will assume that the data is an Object which will implment the esimPublish and esimInject methods. There are two different solutions to inform the port that the data is a C struct. The simplest solution relates to the last argument in the templated type of a Port, the S argument. This type can be set to PortMode, or more convenient one can define the port as Esim::InPortC where the extra C lets EuroSim know this is a C type.

236 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

//MyStruct is defined in a C header file with static variable in a C implementation file

//Following would be the declartion in a C++ header, note the extra C behind Port Esim::inPortC inport; //MyStruct variable passing through Esim::OutPortC outport; //MyStruct vector passing through

//Following would be the publication Esim::publish(inport,"inport","my description"); Esim::publish(outport,"outport","my description");

With the above approach the Port will not require an esimPublish and esimInject in the type. The alternative is to use the normal InPort with StructMode set to ObjectMode (default). In his case the Port will require that the struct is a class with an esimPublish() and esimInject() method implemen- tation. If the POD structure type is however known in the dictionary it will still publish itself correctly in the dictionary according to the POD definition in the dict. However the compiler still wants the presence of the esim methods, which can be silenced by defining the following macro and including it in the C (POD) struct.

#ifdef __cplusplus #define ESIM_PODSTRUCT() \ bool esimPublish(){return false;}; \ template bool esimInject(DONTCARE& __value) {(void)__value;return false;} \ operator double* () {return (double*)this;} #endif

With the above macro included in the C struct, the C parser will skip these functions, whereas the C++ compiler will change the text segment but not the data layout. The publication will automatically apply the known type layout in the dictionary. The new Mk7 approach thus prefers a C++ solution over a C solution, but still supports C struct usage. This approach makes Mk7 different from the Mk6 but taking a more appropriate route for a C++ API. The disadvantage of this approach is that enumerated types are not well supported, further improvement is investigated for subsequent EuroSim versions. When the model is sufficiently coded, an instance of the model is instantiated and its esimPublish call is invoked to display the model into the dictionary. Because the port objects are declared member variables of the model, this follows the same approach as for any other member variables of the model, using the Esim::publish() function on a port object in the esimPublish() method of the model. bool esimPublish() { bool result=rtue; .... //publish ports result = result && Esim::publish(portobject,"name","description"); .... return result }

The port object will appear in the dictionary with its distinctive inport or outport icon and when unfolded it will show the value that is contained in the port, as well as the error injection parameters. In Figure 16.4 the heat is an inport and the temperature an outport for data of type double. The error injection parameters of the default error injector for type double are shown.

c Airbus Defence and Space 237 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 16.4: EuroSim CPP ports in dictionary

16.7.3 Channel The interconnection of models with Ports using the Channels is accomplished by interconnecting ports using the addChannel function provided by the SimInt interface. It is possible to interconnect two ports of the same size, which copies the complete content of the outport to the inport, even in case the content is an array. It is also possible to copy the element of an outport to an element of an inport, which can aggregate or decompose data. Only in the latter case, the port should not be of type Esim::Active cause the error injection timing is not controllable.

CHANNEL ADDING FUNCTIONS

//Connect OutPort to InPort (port type of equal size) bool Esim::addChannel(const char* outport, const char* inport, const char* channelname, unsigned capacity=0, const char *description="");

//Connect OutPort element outidx to InPort element inidx //for port on arrays. bool Esim::addChannelByIdx(const char* outport, size_t outidx, const char* inport, size_t inidx, const char* channelname, unsigned capacity=0, const char *description="");

The channel represents the ability to flow data from the outport to the inport. The channel object contains a transfer entrypoint that can be scheduled to trigger such transfer. The ability to time the data transfer is required when using parallel and even concurrent scheduling techniques to ensure the proper execution of models. The channels display themselves in the dictionary with a distinctive icon, see 16.5

238 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 16.5: EuroSim CPP channels in dictionary

Wen creating channels the user can specify a capacity, which reflects the internal buffering in the channel. When zero, as in most cases, the data is transfered directly from the outport to the inport. When the capacity is one, a double buffering takes place in the channel and the user is provided two instead of one transfer entrypoints contained in the channel. The double buffering allows the models on both sides of the channel to run in parallel without running into data corruption. Higher capacity numbers implement a ringbuffer mechanism that prevents the loss of data as can occur with double buffering which always provided the consumer part the latest data. For convenience, the SimInt interface provides the ability to define sequences of entrypoints, such that a series of entrypoints can be controlled through a single name. The Sequence is typically used to bundle the execution of the channel trasnfer entrypoints. Quite often the presence of a model versus the presence of the equipment that the model simulates forces the scheduling of sets or sequences of transfer functions. Particularly in object oriented solutions the Sequence feature is usefule as OO solutions multiply the amount of transfers compared to the classic EuroSim C type solutions. SEQUENCE CREATION FUNCTIONS bool Esim::addSequence(const char *name, const char *description=""); bool Esim::addSequenceEntry(const char *source_entry_name, const char *sequence_entry_name, const char *descr=""); bool Esim::addEntryToTask(const char *taskname, const char *entrypath); The C++ Simulator Integration API also provides a built in schedule feature that has no counterpart in other APIs and is specifically usefull in the context of Object Orientation where many more entrypoints will occur. Where in a C API solution the entrypoint would work on an array of variables, the Object Oriented solution will have an array of objects each with a method working on one variable, requiring scheduling of an array of entrypoints. The addEntryTotask function therefore allows the model developer to add an entrypoint to a task in the schedule. This function is best called directly after the publication of a method, here assumed to be under the name ”entrypoint”. When a simulator starts, it reads in the provided schedule file. When the addEntryToTask method is encountered it then adds the entrypoint ”entrypoint” in the dictionary to the task ”taskname” in the schedule. In object oriented code multiple instances are created and thus multiple times the entrypoint ”entrypoint” is published (under a different parent object) in the dictionary. In the normal approach the entrypoint must be added the same amount of time as there are objects to a task using the ScheduleEditor. Using the addEntryToTask this is now done automatically from the code, avoiding discrepancies between code and schedule. The decisions on how the code is scheduled of the processors in time is still defined using the tasks and task properties in the schedule editor, but the schedule may contain only or mostly empty tasks. Note that the timing statistics and timebar feature of EuroSim will still collect and contain the timing statistics of all entrypoints, including those that are added using the addEntry function. The Simulation

c Airbus Defence and Space 239 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Controller however will not show entrypoints in the schedule tab, and no EuroSim schedule breakpoint can be defined on entrypoints. (But the symbolic debugger can be used to set a breakpoint on any function). Further details can be found in the manual page esim++simint Besides the above described addSequence solution there is also an alternative ussing the addXfer func- tions below, sometimes preferred as these are simpler to use as they are less generic. The addXfer call implements the dataflow and appears as an entrypoint in the dictionary that can be scheduled via the ScheduleEditor in order to precisely control the timing of the data copy action. The addXferGroup function is optional as this creates an entrypoint that when, activated, calls all entrypoints that are its direct children. (Thus first create the group, say X, then perform the addXfer with xfer_name argument X/name);

bool addXfer(const char* outport_path, const char* inport_path, const char* xfer_name)

bool addXferGroup(const char* groupname, const char* description="")

16.7.4 Link The port-channel solution involves copying variables by triggering a generated entrypoint. However this approach comes with an overhead of copying as well scheduling entrypoints which may be unnecessary complicating the maintenance of the schedule. A good example is when used in combination with the Front-End models which by itself already provide a buffering and copy mechanism including error injection. The additional copy via ports and channels only creates overhead and complicates the software for the model developer and simulator integrator. For this purpose the integration API also supports the concept of links. In the case of a link the API connects a pointer in one model to a dictionary variable in another model or to the model itself. With this approach there is no copy, nor is there an entrypoint to schedule. A direct interaction is created between models, which requires mutual exclusive execution. The pointer solution is wrapped in a Link object such that it is not the model developer that interconnects models, but the simulator integrator. The model developer programs the availability of the Link, much like the availability of ports. Then the integrator connects the Link to its target using a EuroSim dictionary part. With EuroSim Mk7, similar to the change in approach for the Port-Channel implementation, the EuroSim Link solution also changed from creation through functions t into declaring Esim::Link objects. The Esim::Link object wrappes the pointer such that the model developer can work with it as if it is the pointer but the actual setting of the pointer value is delayed to the simulation integration phase. The Esim::Link object is templated to wrap the real pointer that it containts. The usage of the link object is primarily through an interface based on operator overloading: DECLARATION:

Esim::Link linkname; //Wraps the pointer to type T

METHODS:

bool isConnected(); //check if the pointer is set

OPERATORS:

T& operator=(const T& other) operator T&() operator T*() T* operator->()

240 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The declaration creates a Link object that wraps a pointer to type T. This pointer either points to a plain variable of type T or an object that implements a class T. The first would be used to point to a member variable of another model, the second to an instance of type T, or at least an instance that implements an interface of type T. The Link object is then used by the model developer through its operators which allow the link to be used as if it is a pointer to type T, which creates a very intuitive interface as demonstrated in the following usage example.

USAGE AS POINTER TO PLAIN VARIABLE:

Esim::Link varlink: double myvar=*varlink; //get the contents of the wrapped pointer double myvar=varlink; //but its not needed to dereference, //the link does it for you varlink=10.0; //assign a value double myvar-10.0*varlink; //or use in a computation

USAGE AS POINTER TO PLAIN STRUCT VARIABLE:

Esim::Link varlink: field=varlink->field;

USAGE AS POINTER TO OBJECT:

Class Interface { public: T0 aMethod(T1 arg1, T2 arg2){ //do something }; }

Esim::Link objectlink; objectlink->aMethod(arg1, arg2);

Of course the use of the link requires that the link is connected to its target by the simulator integrator and this can even be checked in the model code using the isConnected() method. The connection of the Esim::Link is performed using the Esim::link function. This is normally done by the simulator integrator after he created all instances from within the esimCppSetup bootstrap function. The model developer then does not need to know which object it points to, but simply assumes that the Link is connected. Alternatively it is possible that the model developer already connects the Link to its target variable or object using the Esim::link function from the esimPublish() method in the model code. Though this is a less clean approach this linking from within the esimPublish() of a model is sometimes practical, for instance when the model developer connects to generic interface models that are allways instantiated before all other models. An example is the reading of the front-end hardware by the front- end models. In such case the model developer knows which lines should be read and that these models are published always before the user’s models and hence the dictionary path is available or the object pointer to the line can be retreived from the front-end model interface (singleton).

LINK CONNECTION OPTIONS: bool link(const char *link_path, const char *target_path); bool link(const char *link_path, T &target, const char *description=0); bool link(const char *link_path, T *target, const char *description=0); bool link(Esim::Link &aLink,const char *target_path); bool link(Esim::Link &aLink, const char* var_fmt, ...);

c Airbus Defence and Space 241 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

bool link(Esim::Link &aLink, T &target, const char *description=0); bool link(Esim::Link &aLink, T *target, const char *description=0);

The above functions provide the interface to connect the Link object to its target address. Either the Link is identified through the link path or through a reference to the Link object itself. Using the path to identify the link means that no access to the link object is needed and that makes this approach usefull for interconnecting the link with its target outside the scope of the model that contains the link. This is the cleanest approach because it allows the full creation of all the objects from the esimCppSetup() function first and then perform the interconnection at the end of that function. The version that allows the link_path and target path to be specified is easy to use in such context but beware that this does not work for linking the Link to a target object that has multiple inherintance or polymorphism. It is fine though for all plain variables and simple objects (for example such as the line objects in the next paragraph). The issue with complex objects as target is due to the underlying casting and can lead to calling a method object that is completely and silently ignored. If the target reference is provided the description is copied into the link in the dictionary, it is good practice to provide the path to the target as //name/name/ such that the link shows to which target it points. The alternative approach requires a reference to the link object. Normally the link objects will not be in the public interface and hence this is mostly used from within the model. A good example is linking to line objects in the Front-End models. These front-end models already exist and publish the lines they handle as objeects in the dictionary. This is normally done before the users models are created and published. In this case the linking can be done from within the esimPublish() of the user’s models. The variable format is then very convenient when there are multiple instances of the model as it becomes easy to parameterize the path in the code with the printf specifiers and argument approach. Note that when the target path approach is used though, it must be taken into acount that the target path solution is fine for plain variables and simple objects that do not have multiple inheritance or polymorphism. If the target_path points to a complex object with multiple interfaces the address that is found in the dictionary can be interpreted wrongly and the methods called will be silently ignored. In such cases you have to use the reference to the target model (or pointer). For front-end models such reference can be found via the instance call of the singleton. Also here, in the variant where the target object reference or pointer is passed, the description is what is written in the description of the Link and its good practice to provide the target path //name/name. The Esim::Link is a member variable that must be published in the dictionary. This follows the normal approach of publishing member variables using the Esim::publish() function from within the esimPub- lish() method of the model. The result is that the link appears in the dictionary with a distinctive arrow symbol to show that its a Link, and when unfolded it shows the internal pointer and the path of the variable or object that it points to. This is relevant to allow the end user that operates the simulator to understand and review the flow of data through models.

bool esimPublish() return result = Esim::publish(linkname, "name", "description"); }

The above publication creates a link object in the dictionary with its distinctive arrow icon. When un- folded it shows the internal pointer and with its description displaying the path in the dictionary to the pointer is connected. This allows the developer and end-user to verify that the link is correctly connected, see 16.6.

16.7.5 Line The Link object itself only wraps a pointer and hence does not have error injection or buffering capabil- ities as often needed in dataflows and as provided by the port channel combination. The solution is the use of a Line object between the models. Both the model that provides data and the model that consumes data point to the line object. The provider writes its data, the consumer reads its data, and the Line object

242 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 16.6: EuroSim CPP links in dictionary

performs the error injection and the buffering for data integratity if required. This is shown in figure 16.7.

Figure 16.7: EuroSim CPP line in dictionary

Figure 16.7 shows on the right the data producing model. This model calls the write() method of the Link to enter the data into the Link object. If the Line is created with capacity zero, the data is directly written in the value parameter. If the Line is created with a capacity of one or higer, a lockless buffering is automatically implemented to assure that the data is protected against parallel access by producer and consumer. If the capacity is one, the reader will always get the latest data. If the capacity is higher, a lockless ringbuffer provides a fifo. The consumer model triggers the processing of the data in the Line model when it calls the read() method. If the capacity is one or higher, the model first copies the data from the data integrity buffer into the local value parameter. Then it pulls the data from that parameter through the error injector to produce a possibly altered copy of the data on the consumer side. On creation a default error injector is always created for the type of the value parameter in the Line. These are configurable injectors that display their parameters as member variables of the Line object. If no suitable injector was found a default pass through injector is created. It is possible for the developer to create his own error injector and pass this when the Line object is created. In the above painted approach the initiative for the data transfer is in the producing and consuming model, which trigger a write and read call in the passive Line model. This initiave can also be changed through the producer and consumer links in the Line model. This allows one model to trigger another model with its data. The benefit is a reduced need to schedule models. The downside is that this easily leads to less predictable model performance. The pro’s and con’s need to be weighted by the simulation developer. The concept is visualized in figure 16.8. When the developer connects the consumer to a model that implements the Line::Consumer interface the result of the producer pushing data into the line is a trigger of the push() method implemented in the consumer model. The push method in the consumer has as parameters the line that triggers the push and the data that originates from the producer. The data when through the line model, through the capacity defined buffering and the error injector. Using this approach the producer can trigger an action in the consumer. Vice versa the developer can set the producer link to point to the Producing model, and as a consequence a read that is triggered from the consumer model will trigger the pull method in the producer

c Airbus Defence and Space 243 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 16.8: EuroSim CPP line push and pull

model and pull the data from the producer model through the line model capacity and error injector into the consumer model. The Line model is created as a variable and templated over the type of the data that passes through the Line as well as the capacity and the error injector type. The publication to get the Line in the dictionary is then performed as for all variables using the Esim::publish() method to store the link in the dictionary.

DECARATION: template > Line;

PUBLICATION: Esim::publish(linename,"linename","description); //show in dictionary

EXAMPLES: Esim::Line linename; //no data protection and //default error injector Esim::Line linename; //latest written data protected, //default injector Esim::Line linename; //ringbuffered data protection, //using developer written injector

Esim::publish(linename, "linename"); //show line model in dictionary

The publication will display the Line in the dictionary with the Line icon and the capacity, value and error injection attributes. The layout is shown in figure 16.9 In Figure 16.9 the producer and consumer links both have their pointers set to nil, they are not used. Links must then be connected to the Line and operate it using the ILine interface. The following usage example will clarify the approach for the case where the initiative is in the producer and consumer model.

PRODUCING MODEL: Esim::Link > producer; Esim::publish(producer,"producer");

CONSUMING MODEL: Esim::Line> consumer; Esim::publish(consumer,"consumer");

244 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 16.9: EuroSim CPP line in the dictionary

ESIM CPP SETUP: Esim::ILine *line=new Esim::Line(); Esim::publish(line, "line");

Esim::link("producerpath","linepath"); //or Esim::link("producerpath",line,"linepath");

Esim::link("consumerpath","linepath"); //or Esim::link("consumerpath",line,"linepath");

PRODUCER MODEL: producer->write(10.0);

CONSUMER MODEL: double data=consumer->read();

Note that the line is created as Esim::Line¡double¿ and assigned to Esim::ILine¡double¿. This is essen- tial for the variant where line pointer is given cause its type needs to match the declaration at the top. Furthermore in that variant where the pointer is passed instead of teh linepath, the ”linepath” is given as argument. That is only done to fill the description of the linepointer with that string which is a good practice and fits nicely in the document generation capability of the dictdoc uitility. If the developer wants to push the data from the producer through the line into the consumer or vice versa pull the data from the producer through the line into the consumer the setup is the following:

PRODUCING MODEL: class Consumer : public Esim::ILineConsumer { public: void push(const Esim::ILine& l, const double &v) { esimWarning("pushing %lf from line %s",v,l.getPath()); }; }; class Producer : public Esim::ILineProducer { public: void pull(const Esim::ILine& l, double &v) { v=0.1234; esimWarning("pulling %lf from line %s",v,l.getPath());

c Airbus Defence and Space 245 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

}; };

ESIM CPP SETUP: Consumer *consumer= new Consumer(); Producer *producer= new Producer(); Esim::ILine *line=new Esim::Line(); Esim::publish(line, "line"); Esim::link("producerlinkpath",producer); Esim::link("consumerlinkpath", consumer);

The above coding sets both producer and consumer links in the line model. This is to show the code to implement it, but such setup does not make sense. Either the producer or the consumer link is set. If the consumer link in the link model is set to the consumer model, the producer model should have its link pointer to the line model and call the write method. As a resul the push method is invoked in the Consumer model. If the producer link of the line model is set, the line consumer model should have its link pointing to the line model and invoke the read. As a result the pull method is invoked in the producer model. Figure 16.10 shows the layout in the dictionary for the situation where the producer is pushing the data to the consumer.

Figure 16.10: EuroSim CPP line in the dictionary

In Figure 16.10 the consumer link of the line model is set to the consumer model to forward the data pushed into the line model by the producer. Note that the type of the producer model pointer that is passed to the Esim::link call must match that of the consumer interface, a dynamic cast may be needed for a polymorph model producer model or a static cast for a non polymorph model (in case of the latter the dynamic cast generates a null pointer). The same applies for the consumer model pointer and the consumer interface.

16.8 Error Injection interface

The CPP Simulator Integration API provides default Error Injection classes for Plain Old Datatypes (the c types) and arrays thereof. Instances of the types are automatically installed in ports if the port operates on such type, similary this takes place with in the creation of lines. For classes or C++ structures the approach is different and there the error injection is based on the presence of an esimInject method that is to be implemented by the programmer, though the programmer can use instances of the default error injection classes for members. A special case are the structures defined in C, which are popular in EuroSim because the C parser will automatically fill the EuroSim dictionary if it encounters a dummy variable for them. These are first detected by the class approach, but when the type is present in the dictionary it will follow the POD handling.

246 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

16.8.1 POD Error Injection

ErrorInjection on POD types is default performed via an instance of the Esim::ErrorInjector. Ports and lines automatically create and publish default error injector instance of this type if no other error injector type is specifically provided in the declaration of the port or line. E.g. Esim::InPort means Esim::InPort >. See ports for further details on alternative error injector types. The esim++inject.h header class contains the definition of the default error injection class for pod types and its specialization for all the standard pod types (e.g. double, int). The non specialized case is defined as template ErrorInjector { public: ... bool inject(const T from[N], T to[N]) {....} ... }

This implementation is the default and performs the fallback of a simple passthrough, its inject function silently copies from from to to. However the concept is that there are specializations for a known type. Thus there is for instance a specialization for arrays of double which is written as: template ErrorInjector { ... }

The compiler will automatically take the most specialized implementation, thus for an array of 3 doubles it takes the specialization for double above, and with N=3. The esim++inject.h contains the specializa- tion for all standard types in C++ (e.g. double) as well as for EuroSim predifined types as EsimVector2, EsimVector3, EsimQuarernion, EsimMatrix22 etc. These specializations are for arrays so the range from 1 and hoger is supported, with 1 being default. In case of an array the error injection control is over the array, e.g. the enable switches on the error injection on the set of variables. Note that the ErrorIn- jector¡EsimVector3¿ is inherited from ErrorInjector¡double,3¿, it is not necessary to use EsimVector3 anymore, an array of 3 doubles does the same. The default error injector specialization contains a set of standard error injection functions. These are available for all scalar types. For the types bool and char there is a non scalar error injection capability available which provides the ability to mask. As for the classic EuroSim interface the default error injectors have the following parameters and func- tions.

• enable : enable the error

• type : type of the error,lock=1,linear=2,ramp=3,mask=4

• time[2]: a timeguard, with min time[0] and max time[1] as simtime in seconds

• a[N] : error function parameter

• b[N] : error function parameter

• n[N] : error function parameter

• reps : number of times the error is counted

• vtype: generic=0, unit=1, angles=2, quaternion=3

These parameters define the following type of errors (configured in the field type) which can be injected for reps number of times:

c Airbus Defence and Space 247 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• lock: y=a

• linear: y=a*x+b • ramp: if (n>0) y=(b-a)/n else b. (n counts down)

• mask: y=(x & a) | b

• n: error function parameter

A default error injector will then show itself in a port as in Figure 16.11.

Figure 16.11: EuroSim CPP API default error injector for double

The parameter N as in a[N], b[N] etc is the second template type of the class ErrorInjector. Default this is 1, and can be set higher to create vectors. When N>1 a number of array types have a special vector type (vtype) attribute. Normally the value will be zero, meaning type GENERIC which assumes there is no special relation between the elements. The error injection of element i in the array is controlled by paramaters a[i],b[i],n[i]. The error injection is executed in a loop over all elements of the array on each activation of the error injection function inject() of the EsimErrorInjector. However the value can be set to UNIT (1) or ANGLES (2) or QUATERNION (3). This makes the error injection behave in a special manner, assuming its a Unit vector, an Euler Angels vector or a Quaternion. The special cases are not often needed, please check the implementation in esim++inject.h if it matches your need. The time field implements a timeguard on the enabling and disabling. When time[0] is set to a value larger than zero, then after setting enable to one, the error injection will not start until the simulation time is larger than time[0]. After that it starts running down the repetitions variable. Likewise when time[1] is set larger than zero, the error injection will automatically disable when the simulation time is larger than time[1]. Note that this does not mean that the simulation will start at time[0], it will start at the first simulation time that the port is accessed at or after time[0]. Likewise the error injection does not disable at time[1], but at the first evaluation moment after time[1]. The main driver for adding this guard is that from an external interface such as batch scripting it is hard to time the error injection. An MDL script can be used to control it, but the timeguard is a very easy to use lightweigt mechanism. If the model developer adds a POD (C) structure that needs to be passed through a Port or Line, special measures must be taken because the Port and Line will assume a C++ Structure (class). The POD (C) structure is popular in EuroSim because the EuroSim C parser will automatically put all the details of the type in the dictionary and this was a major factor in the EuroSim Mk6 usage. The parser will auto- matically keep the structure information in line with each dictionary build, which is easier then writing

248 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

and updating an esimPublish()function. To avoid the clash with the C++ structure, leading to compiler errors that indicate that the esimPublish and esimInject method must be present, two measures must be taken: template <> class ErrorInjector : class IErrorInjector { bool inject(const MyPodStruct in[N], MyPodStruct out[N]) { ...transform in[i] to our[i] for 0

• A specialization of the ErrorInjector class should be written for this type. Thus an implementation of the following class:

• The Port or Line will try to treat your POD structure as a class, which means the compiler ex- pects that it has the esimPublish() and esimInject() methods. A structure in C can not have methods. It is perfectly ok to include these two methods without any further implementation then return false; protected by #ifdef __cplusplus, thus avoiding that the C compiler sees them. The object in memory remains to have the same layout. The Port and Line implementations will not call these methods if they see that the type MyPodStruct is already known in the dictionary and then treat the publication of the type as well as the error injection in the POD approach using the type ErrorInjector.

16.8.2 Class Error Injection Interface The error injection interface in classes is relatively easy and demanded when instances of the class are to be passed by the EuroSim Port and Line model integration mechanisms. The user written classes are required to have two methods: bool esimPublish() bool esimInject( const UserClassType&)

The esimPublish function is called by the port and line to show the instance created by the port or line in the dictionary. The esimInject is called by the Port or Line when the error injection is to be performed on the object. In case if an InPort for instance, the esimInject is called with the value that is provided via the channel. The programmer defines in the esimInject how that changes his object. If this requires control parameters for the end user, such as enable the programmer must publish such a variable in the esimPublish and use it in the esimInject. The programmer can utilize the default Error Injection class for a member of his class if that is a POD type. For instance if the programmer wants the default error injection capability on an array of 3 doubles, a member variable Esim::ErrorInjector¡double,3¿ can be added to the class, published in the esimPublished and using its inject function in the esimInject().

16.9 UML support

WARNING: Due to the restructured approach for Ports in Mk7 the UML transformer is not supported in Mk7.0. This feature is rarely used and precedence has been given to provide a Mk7 release in 2019 instead of delaying the EuroSim Mk7.0 release. EuroSim support is working on re-establishing this feature in a subsequent minor version upgrade.

16.9.1 Overview Often Object Oriented design that leads to implementation in C++ is defined in UML. Enterprise Archi- tect is a popular tool to support modeling in UML due to its affordability and abundance of features. An

c Airbus Defence and Space 249 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

extension has been built in the form of Enterprise Architect transformation and code generation templates that you can use to jump start your EuroSim projects. The process from Architecture to Simulator con- sists of a sequence of steps, where after each step the user can tailor the results further towards specific needs if desired. An overview of this sequence is shown in Figure 16.12

Figure 16.12: EuroSim UML transformation, generation and building process

In the top left of Figure 16.12 the class diagram defining the architecture is shown. Stereotypes are applied to identify models and their input-output variables, as well as their composition into a simulator. This simple diagram is input to the EuroSim transformation, which applies patterns to each model in the architecture, which results in a package per model with a detailed design and elements in UML. The user can enhance and elaborate the diagram as required, as long as EuroSim publishing related stereotyping is applied in order to allow the generation process to create code from these diagrams. The EuroSim tailored C++ code generation then results in source code files structured on the file system along the package structure in Enterprise Architect. These files can be included in the EuroSim ModelEditor for building. After a minor effort to add the EuroSim CPP setup routine, as well as coupling ports via dataflows, the EuroSim build can create the simulator with its objects, ports and transfers displayed in the EuroSim dictionary. From this point, schedules, scenarios and simulation definitions can be created to utilize the simulator in various simulations in the usual way.Of course at this point there is no functionality integrated in the code yet, it is an empty framework where algorithm developers and hardware interface developers can fill the entrypoints with C++ code. This is also a major benefit as the strcuture of code is provided, and that structure allows everyone to work in the same simulator software, yet only scheduling their own model and stimulating the ports with data for testing. The following sections provide more detail om each of the three processes.

16.9.2 Architecture and Transformation At the highest level a simulator as common in Electronic Ground Support Equipment (EGSE) or test systems in general is a composition of models that mimic the system under test. This can be described in a class diagram in UML as in Figure 16.13. The class diagram shows that the Simulator for the Satellite program is composed of an Obc, Thrusters(3), an Environment (dynamics) and a Radar altimiter. The stereotyping identifies classes as either Simulator or Model. The Simulator class must be named

250 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Simulator, for the Model stereotyped classes the name should indicate the function of the model. In each model you can define the input, output and input-output variables, by stereotyping the attributes as in, out or inout. Note that at this point we do not define the internals yet of models.

Figure 16.13: EuroSim UML transformation

The EuroSim transformation for test systems can be started by right clicking on the package symbol of the package that contains the drawing of Figure 16.13 in the browser window (on the right side in 16.13). The Transformation dialog in Figure 16.14 will appear.

Figure 16.14: EuroSim UML transformation dialog

Please set all checkboxes as in Figure 16.14 to prepare for the transformation. This includes selecting Child Packages and the ESimDetailedDesign. When the dialog is set up as inFigure 16.15, you can start the transformation. During the transformation the drawing in Figure 16.13 is analyzed and for each class that is stereotyped Model a package is generated that wil contain a design drawing for that model. Figure 16.15 shows the progress dialog, which shows how every dialog is being expanded in multiple classes, ports etc. After completion fo the transformation, you will see the list of packages in the browser on the right in Enterprise Architect under the package ESimDetailedDesign. If you change the Architecture diagram, a regeneration is needed to reflect the changes in the generated design diagrams. There is no incremental support at this point, you either delete the ESimDetailedDesign package and regenerate, meaning you loose all changes made in the design diagrams; or you make the change in the designs manually. The templates that perform the transformation are included in the Enterprise Architect database, thus available as source code. By modifying these templates in your database it is possible to tailor the transformations to create project specific designs. More information on transformation and templates can be found in the Enterprise Architect documentation. This documentation is not extensive, hence two

c Airbus Defence and Space 251 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 16.15: EuroSim UML transformation progress dialog

important tips: First the methodology of the transformation is that an intermediate text file is generated in the process according to the templates of the chosen transformation. The intermediate file is subsequently read back into the database to form the drawings. Second, to easily construct the template you want, draw the result in Enterprise Architect and use an emtpy transforamtion such as the C# transformation from Enterpise Architect. The intermdiate file that is specified in the transformation dialog then is close to what you need to write as template, except that you miss the references. For the latter you can study the EuroSim provided transforation templates. The design diagrams that are the result of the transforation are further discussed in Section 16.9.3

16.9.3 Design and Generation The Transformation process resulted in a series of packages, each containing a design of the model according to the EuroSim EGSE design pattern as shown in Figure 16.16. Note that the Enterprise Architect layouter is not able to drawn the diagram exactly as in Figure 16.16. To lay out the class diagram as shown, enlarge the class diagram on which the ports are located, move the ports to along the edges to the desired location and move the Data subclass to the bottom.

Figure 16.16: EuroSim UML generation

The design pattern used in the EuroSim transformation is rather Space domain and test system oriented, and follows the dataflow approach that fits with EuroSim’s multicore scheduling capabilities. The design reflects that a model has low-cohesion with its environment, communicating via ports with other models. The ports will be interconnected at a later stage using dataflows. Internally, the model has high cohesion. It consists functional subclass that contains the funcionality of the model, a TC subclass for telecommand handling, a TM subclass for telemetry handling and a HIL subclass to support the Hardware In the

252 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Loop interface. All these classes communicate in a shared memory approach via the Data subclass. In the resulting implementation the Data class will thus contains the state variables of the model. These variables are access by the other subclasses via a pointer, and from the outside world via the ports. The class diagram in Figure 16.16 has specific features that steer the EuroSim emhanced C++ code generation. The EuroSim stereotyping assures that members and entrypoints will be published via the EuroSim C++ API. Furthermore, the ports will assure that ports are created and published in EuroSim, which will be visisble in the EuroSim dictionary and may be enhance with error injectors when tailoring at the code level. Please follow the approach for ports exactly as generated. Because Enterpise Architect presently does not support code generation from Ports, the information needed by the C++ code gener- ation had to be added in a slightly complex manner, specifically the dependency between the port and data class and the attributes along the dependency. The user can further elaborate the class diagrams with additional design information, possibly to be taken into account in the code generation process. Alternatively it may be decided that elaboration is easier achieved at the code level. As a general advice, keeping the design clean and prevent clutter with to many details reduced maintenance. Also in the EuroSim team we found that elaboration is often quicker accomplished in the code using e.g. eclipse. To start the code generation process, right click on the ESimDetailedDesign package and select code generation. The dialog show in Figure 16.17 should appear.

Figure 16.17: EuroSim UML generation dialog

Please make sure that you select all checkboxes as shown in Figure 16.17. Specifically be carefull with settings that merge generated code back in your design as the generated code contains more details then your design due to the EuroSim enhanced C++ code generator (hence select Overwrite). When you start the code generation process by pressing Generate, the code deneration progress dialog appears as shown in Figure 16.18.

Figure 16.18: EuroSim UML generation progress dialog

You may need to move the resulting code to the proper location, especially when Enterpise Architect is used under Windows and the simulator is built under Linux, as will usually be the case for test system. Of course repositories can be of help, as well as shared directories. In any case, generally the source code ends up in a source code repository and is subsequently maintained at the source code level. The

c Airbus Defence and Space 253 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

generation process does not support a roundtrip engineering. The best approach is that in subsequent regenerations the changes are merged with the baseline code. Tools as meld can easily support this as the source code files result from the same generation process and does have comparable layouts. The EuroSim enhanced C++ code generation templates are included in the database. Please check the Enterpise Architect documentation on Code Generation for detailed information. The most interesting change that users can make to the templates is the replacement of the file header such that generated code contains the Copyright statements for the project that is worked on. Note also that the generated code takes all comments and other information in the diagrams into the source code and that the generation process adds Doxygen make up to the files. If you run Doxygen over the code you therefore automatically extract the design from your software.

16.9.4 Simulator Building The code generation process creates directories, source and header files along the tree of packages that code is generated from. This tree fits directly into the file browser part in the EuroSim ModelEditor as shown in Figure 16.19

Figure 16.19: EuroSim UML source files in ModelEditor

The code will normally not need any extra work, unless specific header files and types are added, which is a standard C++ coding type effort. In addition, every class will have an extra esimPublish method that is added in the generation process. This class automatically contains all the code for publication of member variables, entrypoints and ports along the stereotyping that was applied in the design. The additional work that is needed in this stage is writing the CPP kick off routine where the objects must be created and published, and the creation of the dataflows from out-ports to in-ports to interconnect the models. Previous sections in this chapter contain the information, however the code in the SatelliteUML example can be used as a starting point, in general the code required in your project will be very similar. Note that all automatically generated ports are active and have no error injector. Where such features are needed the user can easily change this in the generated code by adding default error injectors and switching to passive ports for ultimate timing control. Once the kick-off and transfers code is added, the user can built the simulator in the EuroSim Mod- elEditor with the BuiltAll button. As an advice on transfers it is recommended to group transfers in transfer-groups where possible as this prevents a lot of dragging and dropping of entrypoints in the ScheduleEditor, it even makes the scheduling independent of the number of instances of a class. The result of the built is a simulator and dictionary, the latter being visible in the Dictionary tab as show in Figure 16.20. From here on the process is as usual when applying the ScheduleEditor and SimulationController to define a simulation. Note that in the above approach the source code was integrated in the Simulator via

254 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 16.20: EuroSim UML build result in ModelEditor

the Files tab of the EuroSim ModelEditor. Many users, however, prefer to integrate the code in eclipse and possibly unit test in that environment. This is easily accomplished, the user can built a library in eclipse and link this library via the Built Options dialog to EuroSim. The result in the Dictionary tab is the same. For more details see Section 16.10.2.

16.9.5 Resources With your EuroSim distribution an example SatelliteUML is included. This variant on the Satellite example contains the Enterprise Architect database (.eap) with the templates included as described in previous sections. The class diagram for the Satellite model is included as well. The easiest start of your project is to copy this entire directory to your project (mind the read only protections due to the location where EuroSim was installed) and modify and expand the Satellite example to your project, including the provided Enterprise Architect database. If you already started your own database, it is also possible to incorporate the templates via the MDG technology files included in the MDG subdirectory of the SatelliteUML example. Please refer to the Enterprise Architect documentation for the method to include MDG technology files. Warning: Please note that the provided Enterprise Architect database has a modified C++ generation template set. The standard C++ code generation will not be availabel anymore and your C++ code generation will only be able to generate EuroSim tailored C++ code. The same holds for incorporation of EuroSim provided MDG files as these also permanently modify the C++ templates in your database. (The effect will be limited the database in use, hence making a copy before you incorporate MDG files is not a bad idea).

16.10 Tips, Tricks and Guidelines

16.10.1 Low level publication interface Generally users will find that all functionality needed for object, variable and entrypoint publication is provided by the publication interface defined in section 16.3. However there is a low level interface that advanced users may find usefull to further shape the publication in the dictionary. This interface is defined in the header file esimcpp.h, but simply including esim++.h is sufficient to gain access to these functions. The following low level functions support publication of pointers, objects and variables at the lowest level:

c Airbus Defence and Space 255 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

bool publishPointer( void *object_address, const char *object_path, const char *descr="")

bool publishObject( void *object_address, unsigned int object_size, const char *object_path, CppObjectType object_type, const char *descr="")

bool publishVar( void *var_address, const int length, const char *var_path, const char *var_type, const char *descr) The CppObjectType defines the icon that the object gets in the dictionary. The available object types are defined in esimcpp.h and set the icons for folders, C++ objects, input and output ports in the dictionary. The following low level interface support publication of methods and functions at the lowest level: class IEntryPoint { protected: IEntryPoint(){}; virtual ˜IEntryPoint(){}; public: virtual void execute(void) const=0; };

bool publishMethod( IEntryPoint *entrypoint, const char* name, const char* descr="")

bool publishFunction( void (*entrypoint)(void), const char *name, const char *descr="") There has not been any specific usage by users of this low level interface to date. Ports are of type IPort. When the address of the port is captured this type can be used to cast the type and use the virtual functions to manipulate the port. class IPort { public: virtual ˜IPort(){}; virtual void execute(void)=0; virtual bool isInput(void)=0; virtual bool isActive(void)=0; virtual bool esimPublish(void)=0; virtual void* getValueAddress(void)=0; }; Some utility functions are available in the low level interface that could be useful to the advanced user to interact gather information from the dictionary, such as addresses of obejcts and variables by specifying the dictionary path:

256 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Getting the address of elements by path: void* getObjectAddress(const char* dictpath); void* getVariableAddress(const char* dictpath);

Getting the name from a path: const char* getObjectName(const char* dictpath);

Create an absolute path, resolving all relative elements: bool resolvePath(char *destination, const char* source);

Create a path by connecting parent and child, hides path implemenation: bool makePath(char *new_path, const char *parent, const char *child); The getScope and setScope functions are better interfaces to change the scope of the publication. But if needed the following two low level utility functions are also available, their usage can be seen in the esim++publish header file.

//context management const char* getContext(void); bool setContext(const char*);

16.10.2 Usage of Eclipse Eclipse is a modern open source integrated development environment that is popular with many software engineers. With the C++ API the usage of eclipse for EuroSim models has become easier, and has been sucesfully applied by the EuroSim consortium in projects. The combination with code generation from UML provides a powerfull source code development approach. The model software can be written, compiled and linked into a library from eclipse, providing the en- gineer with the benefits of software development from within eclipse. The ModelEditor is only used to define the build options for EuroSim. In those build options you must specify the linking of your library. In addition it must contain one source file that defines the esimCppSetup function, which usually only contains the switch calls to configure the C++ API and a function call to the model software where the creation and publication of objects is further handled. Write a Makefile which takes care of compiling your code and linking it into the library that you specified in the EuroSim Model Editor. When in your make process your libraries have been linked, the following two lines must be executed to create an executable.

ModelMake modelname.model modelname.make make jN -f modelname.make all

This will have the same effect as pushing the Build All button in EuroSim. Note that the Build All button currently does not support parallel building, but the -jN option is supported by the build process and considerably speeds up your simulator build process. You can also clean up what EuroSim generated with make -f modelname.make clean. In eclipse you can now configure that when you active the build process it invokes your makefile. With this approach the ModelEditor will not be needed anymore after defining build options and inte- grating the C++ setup code. The Schedule Editor will still be needed to define the schedule and the Simulation Controller to define and execute simulations. When compiling a simulator within Eclipse, it is useful to let Eclipse highlight errors and warnings from EuroSim build tools in the Eclipse Console. This requires an extension of the Eclipse error parser. Such an extension is provided in /usr/EuroSim/etc/model.extensions.xml. To activate the extension, copy the file into your Eclipse workspace under .metadata/.plugins/org.eclipse.cdt.core/. Then start Eclipse and go to Window / Preferences / C/C++ / Build / Settings and enable ”EuroSim Regex Error Parser”. Finally,

c Airbus Defence and Space 257 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

go to your project’s properties, then to C/C++ Build / Settings / tab Error Parsers and enable ”EuroSim Regex Error Parser”. Now, Eclipse Console will highlight errors and warnings from EuroSim build tools such as dictmerge.

258 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 17

Model Reuse Architecture reference

17.1 Introduction

The Model Reuse Architecture (MRA) is a library of base classes that provide a structure and set of ser- vices for simulators that have models with asynchronously executing parts. Typical applications where this asynchronous behavior in models occurs are control systems such as Attitude and Orbit Control Systems (AOCS) in satellites, or robotic systems such as the European Robot Arm. These complex sys- tems incorporate control systems where an embedded computer uses sensors and actuators to maneuver a system in its environment. In the models of the sensors and actuators, the asynchronous execution occurs due to the fact that the telecommand/telecommunication parts of the models need to execute synchronous to the on-board com- puter, while the state and performance part of the simulation model relates to the physics behavior in the environment (the universe) and executes synchronous to the computer clock in realtime. The MRA is the result of years of experience of developing spacecraft test facilities using EuroSim. Where EuroSim avoids posing any requirements on models and focuses on importing models with as little modification from the original source as possible, the MRA defines a reusable architecture and a set of features that make it easier to develop new models. The MRA thus fills a gap between the modeler that is seeking direction on how to write models for a realtime simulator environment and the lower level features of EuroSim that allow the modeler maximum freedom. Although initially coming from the space domain, the MRA is applicable to any control system verification. An example is provided with EuroSim where the MRA is applied in combination with the Front-End Models in the context of a thermal control loop with heaters and temperature sensors as applied in the EuroSim courseware. This MRA chapter first starts with describing the application domain of the MRA in section 17.2 and provides the rationale for its construction. Subsequent sections elaborate on the architecture of the MRA class, providing a conceptual overview (17.3.1), a structural view (17.3.2) and behavioral view (17.3.3) on the MRA architecture. Section 17.4 introduce the programmers interface of the MRA, addressing for respectively the Model software developer and System software developer how to best use the provided software.

17.2 Application Domain

Space projects are a good example of projects that develop sophisticated and expensive systems where a high level of verification is acceptable as the cost of failures can be very high and options for a service repair after launch is usually not existing. The common approach is to develop a set of verification facilities or test benches with different levels of fidelity throughout the project life-cycle. A typical sequence of use of test benches or verification facilities is elaborated below:

• Software Verification Facility (SVF): The on-board software is executed on a simulator of the spacecraft computer which is integrated with a simulation of the spacecraft equipment. By means

c Airbus Defence and Space 259 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

of a simulation of the on-board computer, the developer can use the software non realtime and support debugging of the on-board software (the product under test).

• Hardware in the loop Facility (HILF): The on-board software is executed on a functional model of the spacecraft computer, which is very similar to the on-board flight computer, but using commer- cial grade components and using standard power interfaces. By moving to a hardware implemen- tation of the on-board computer the simulation gains fidelity, in particular introducing the correct timing, but the usage becomes more complicated and is usage becomes more time consuming.

• Special Checkout Equipment (SCOE): Here the actual on-board computer is integrated as well as a varying number of live equipment units to replace the simulated models to create even more fidelity. The introduction of live equipment requires extra interfaces and capabilities to stimulate this equipment in harmony with the execution of the simulation.

The above mentioned verification facilities share common elements. The models of the spacecraft equip- ment are reused, as well as certain more infrastructure related elements. This is both because it is de- sirable from a cost perspective to reuse resources, but also from the perspective that the reused models are validated and that the same test can be conducted on different verification facilities with different levels of fidelity. For example, a test can be developed on the SVF and for a crosscheck executed on a HILF. Using the same models in both facilities is important for being able to understand differences in results when they show up. The structure and services that the MRA introduces, guides the simulation developer into making models that are reusable from the soft realtime SVF to the hard realtime HILF. It also provides the features that are needed to have any mix of simulated and live equipment integrated in the simulation loop. With the above use case, it becomes clear that there is a gap between the needs of a simulation developer and the APIs and services offered by EuroSim. The services and interfaces provided by EuroSim are designed to not pose any interface on the model and are very generic. This is the gap that the MRA fills by defining an architecture for models that provides the model developer with a skeleton to fill with source code that models the IO and physics of models. Although the MRA is newly introduced in the EuroSim with the release of Mk6, this architecture and its implementation has its major development in the Gaia project and is based on experience in verification with real-time simulation that dates back to projects as Automated Transfer Vehicle and the Herschel and Planck satellites. By integrating the solution into EuroSim, the approach is available to the larger EuroSim community. An example called ThermoMra is included which combines the MRA with the Front-End models (see Chapter 29 and thereby provides a working basis for the development of flexible test benches that the user can start with and expand with more advances modeling. The ThermoMra example is available in two versions, ThermoMra1 and ThermoMra2. These are conceptually the same but ThermoMra1 utilizes a different approach in C++ API usage then ThermoMra2. ThermoMra1 uses port-channel and links to variables to integrate the models, ThermoMra2 uses links to objects and line models to integrate the models.

17.3 Architecture

17.3.1 Overview For the introduction into the Model Reuse Architecture (MRA) a thermal control cycle example is used that is provided in the source (src) directory of the EuroSim distribution. The example controls the tem- perature in four cells that are interconnected in an array and thus heat can transfer through the wall of the cells and be lost into the environment. To make the example more interesting (although not necessarily realistic) we have assumed that our heater is controlled via a Mil1553 bus, and the Temperature sensor has a serial line (RS422). The thermal control system is shown in Figure 29.1. The heater in every cell can add heat, the temperature sensors provide a measurement of the temperature in each cell back to the control computer. The algorithms in the control software in the on-board computer (OBC) have to drive the temperature to a set point for each cell based on the measurements received over

260 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 17.1: Thermal Control system overview

the serial line and subsequently switch the heaters on/off via the mil1553 bus. Figure Figure 29.2 shows the thermal control loop.

Figure 17.2: Thermal control system control loop

The MRA is based upon object oriented development paradigms for structure and behavior. The MRA is fully integrated with the EuroSim CPP API. When applying the MRA approach to the example, the EuroSim dictionary reflects this example with multiple model instances representing (E.g. Htr1, Htr2, Htr3, Htr4 for four heaters, and Ts1, Ts2, Ts3, Ts4 for four temperature sensors) the architecture of the system as shown in Figure 17.3. One of the model instances in this view is unfolded, exposing the components of an MRA model. As can be seen, the models of an MRA equipment model typically consist of 5 components:

• The State component (State) models the state behavior of the system as well as that it integrates the mathematical model. Typically such mathematical model is developed and tested in Simulink. After code generation via a tool such as Embedded Coder, the model is provided in C or C++ and integrated in the State model component. The State component receives its inputs from variables in the Data component and writes its output to variables in the Data component.

• The TeleCommand component (Tc) receives its data from variables in the Data object of the unit model where the data in these variables comes from the Front End (FE) models. It handles the low level FE model output and transforms it to engineering level data for the State component. The engineering level data is passed to the State component via the Data component.

c Airbus Defence and Space 261 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 17.3: Thermal control system dictionary

• The Telemetry component (Tm) reads the State component output from the Data object, encodes it to the signal or message level and forwards the result to the FE model.

• The HIL component (Hil) is only active when the corresponding live equipment is integrated as Hardware-In-the-Loop (HIL) verification facility. The functionality to be implemented in the Hil component highly depends on the unit specifics and provided Unit Check-out Equipment (UCE). It may also work on variables in the Data section and via these variables interfaces to the FE models. More unit specific solutions may also be required depending on the UCE of the equipment. The detailed interface must be agreed upon and defined as part of the unit model specialization.

• The Data component (Data) is not a functional component, but is a container for all variables that are shared between the unit components and are exchanged with the environment. These are also the items published in the EuroSim dictionary such that they are accessible for initialization, monitoring, recording, scripting and stimulation. The Data component acts as a datapool to keep the exchange of data between the components simple and effective. This approach requires that the components of the unit model do not run in parallel, which is normally the case and can be assured as part of the system level scheduling.

The TC and TM components are considered the IO part of the unit model, where the State part includes the mathematical part of the unit model. Key in the composition of a model from these 5 components is that they are independently asyn- chronously executing elements with different timelines, yet they are tightly related with the exchange of data which is the purpose of the Data class. The TM and TC elements are driven by the on-board computer which determines when it sends telecommand and when it acquires telemetry. The State com- ponent is executing independently of these elements and simulates the operation of the equipment, which represents its state and physics behavior. If for instance the computer stops and hence TM and TC are not activated, the State component still continues. The HIL component has again a different scheduling as it is timed such that test interfaces on live equipment are stimulated instead of executing the model.

17.3.2 Structural view The MRA architecture provides the base classes for an equipment model, which by Object Oriented derivation provides the above break-up in components as well as the services related to (amongst others)

262 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

scheduling. Figure 17.4 contains the MRA class diagram with respect to the Unit model decomposition and inheritance (note that the Unit specific component instances are to be derived from the corresponding SubModel classes provided by the MRA):

Figure 17.4: RTS architecture example

The MRA provides the skeleton implementation for the class diagram in Figure 17.4 as a C++ class with nested classes for the components. A nested class is in the scope of the outer class, but it is not part of the outer class. Therefore in each component a reference is included to the outer class called _parent, which is passed by the unit instance to its enclosed component instances on creation. The skeleton in- cludes the creation of the State, TC, TM, Hil and Data instances and other required code to enable the correct creation and setup of the unit model. This also includes. using the EuroSim C++ publication API, the insertion of methods and attributes of the unit model instance into the dictionary. The com- ponent classes are derived from the MRA base classes in order to add MRA services and configuration parameters to the unit model code without additional programming effort for the unit model developer. The provided services are documented in Section 17.4. Based on the elaboration of the unit model structure in this section, the objective for the Unit Model developer is to derive the sub classes for the unit model and to fill them with equipment specific unit model source code. The easiest is to achieve this, is to copy equipment model files from the ThermoMra example (either ThermoMra1 or ThermoMra2 depending on your preference in model integration). The unit model developer can then add fields in the structures in the Data class to introduce new dictionary variables. The effect of putting the model variables in the structures is that when you write the unit model code each variable is clearly distinguished according to its purpose. e.g. _data.input.varname and _data.config.varname. (it is often convenient to define e.g. a Macro CONFIG in the model header file such that you can write CONFIG.varname). There are seven structures in the Data class predefined to separate out the variables along their purpose and usage.

• constant: Model parameters that are set on simulator startup, e.g. loaded via an initial condition that is generated form a simulation parameter database. These should then not be changed by an operator.

• init: Model parameters that must be set in the initialization phase, changes have no effect thereafter,

• config: Model parameters that can be used during execution, changes do have effect,

• input: Input variable,

• output: Output variables,

• internal: Variables that are used to exchange data between the submodels or within the submodels of a unit model,

• port: The input and output ports used to exchange data with other models,

c Airbus Defence and Space 263 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• link: The links to variables or objects outside the unit model scope.

When fields of these structures are published using the MRAPUB publication macro (see Section 17.4.1.1), the constant, init, and config fields are put in a Parameters folder in the dictionary, whereas the other fields are in folders that match to their struct name. The rational for creating a param folder for different param- eter related structure is that lessons learned are that the qualifation of parameters in constant/init/config/ may change during the project. The full path names however locked the qualification intended for users into scripts and the change of the qualifation then invalidated proven scripts. For Ports the MRA prefers the variant using the ReadWrite mode. Thefore it derives MRA::InPort and MRA::OutPort from the Esim::InPort and Esim::OutPort which do not need the PortMode (M) template argument as it is fixed to ReadWrite. In addition it derives MRA::InPortC and MRA::OutPortC for POD datatypes. By adding the ports and links that are related to communication with other models a clear interface is created for model integration. Typically the C++ API Port-Channel feature is used between equipment models and dynamic environment that it supports generic error injection. The integration of equipment models with the embedded control computer is preferably achieved via the Front-End models and in such case the usage of the Esim::Link objects is the easiest because these front-end models already integrate the buffering and error injection so Ports would be an unnecessary complicating factor. The MRA is developed in C++ and is, for ease of use, fully integrated with the EuroSim native C++ API. No special library usage is enforced. It is however also possible to construct models using the MRA, but interconnect these using the Model Description and Data Exchange solution. Of course the C++ API can also be used without MRA, it is an optional library of classes that can be used at the discretion of the user. Note that although MRA is developed in C++ it is possible to use unit models programmed in C, as long as these unit models separate data storage between instances by means of the MRA Data component.

17.3.3 Behavioral view This section describes the dynamic behavior of the execution of the unit component entrypoints defined in the class structure described in the previous paragraph. A key aspect to understand is that all entrypoints are included in a single schedule, and that the MRA library determines which entrypoints are enabled for execution. Normally, the developer defines the order and parallelism of all entrypoint execution in the schedule. In the MRA architecture all entrypoints of a unit model instance should be in included in the same task to make sure that these entrypoints are not executed simultaneously: with this approach, the model developer can safely assume that the model components interact without risking data corruption. The schedule also allocates tasks to processors. As an example: If three processors are to be used, then three tasks should be defined, each allocated to another processor. The processing load can be balanced by distributing model instance entrypoint sets to these tasks (but make sure all entry points of a unit model instance are included in the same task). Finally, the order is controlled by typically letting first the actuators run in parallel, followed by a single dynamics and environment related task that gets all outputs of the actuators, integrates these physics rates to a state vector and distribute these to the sensors. As last step in the order of execution: there can be multiple sensors that execute over different processors again. Where the schedule contains all the entrypoints, the MRA library enables and disables the entrypoints on the basis of timelines and modelmodes. The model modes allow the activation to depend on the usage of simulated or real equipment in the loop. The timelines define the activation of the unit model entrypoints over time, depending on the required frequency and offset of the model in relation to a time source.

264 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

17.3.3.1 Timelines The structural decomposition of the unit model in the components State, HIL, TeleCommand (TC) and Telemetry (TM) is needed to support the different execution timing requirements for these components. The TC and TM components are considered the IO part of the unit model, where the State part includes the mathematical part of the unit model. The State component is normally scheduled against simulation time, whereas the TC and TM components often require an alignment with the embedded computer. When the simulator enters the execution state, the mathematical components of the equipment and the dynamics environment model should be running. The embedded control computer however may not be switched on yet, and once switched on will go through initialization cycles, before the communication with e.g. the Mil1553 bus is initiated. The IO components of the equipment model must be scheduled such that it makes data available on the output lines of the embedded control computer before they are acquired by it. Similarly, the inputs must be read after the control computer has made them available to prevent that old data is re-used. As drifts in clocks must also be considered, the IO components are therefore often on a timeline that executes synchronized with the control cycle on the control computer. In case of a mil1553 bus for example, the cycle generally is set up in communication frames, starting with a mode code that provides the frame number. The MRA infrastructure provides an abstract view of different timelines consisting of slots in a major cycle, where the models are registered for execution in a specific slot on a selected timeline. The ThermoMra example, for instance, defines and creates two timelines with 40 slots per second. The schedule file runs a sequence of tasks at the same rate, thus 40 Hz, that contains all entrypoints in the execution state. The Timeline mechanism switches the entrypoints dynamically on and off. The universal timeline will always run and hence its slot zero starts at the first entry into the Execution state of the simulator. The second timeline, relating to the embedded computer is not starting until a sync mode code is received from the Mil1553 bus, and will then start counting. In one minor cycle the slot of the universal timeline could be slot 4 and hence only the entrypoints in slot 4 are enabled. In addition in the same minor cycle, the mil1553 mode code may have been detected and all entrypoints that are defined to be active in relation to the second timeline slot zero are also enabled. The order of entrypoint execution and the processor they execute on are defined in the Schedule File. The user is thus in complete control of the sequence of entrypoints, where it is logical to run actuators, then the environment and then the sensors. Additionally the user can set the sequence of TC step, State Step and TM step to run on a single computer and hence they never run in parallel though they may run at in different cycles. It is also possible to schedule two instances of an equipment in parallel on different processors, as they generally can not affect each other. The timeline approach is shown in Figure 17.5.

Figure 17.5: MRA timeline

Figure 17.5 shows that the entrypoint X is scheduled on timeline 0 with offset 2 and period 5 and hence activated against the simulation time (which has a fixed offset to the wall clock). The entrypoint Y is scheduled on timeline 1 with zero offset and period 10. The MRA system knows the offset of the on- board time (OBT) and will assure that the first Y occurs in slot 6 of the first timeline, mapping timeline 1 into timeline 0. The API to subscribe the execution of sub model X step to the slots as shown in

c Airbus Defence and Space 265 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 17.5 is to add the following code to the constructor of component X of an MRA model, where X is either TC, TM, HIL or State: mEpSchedInfo[MRA::EP_TYPE_STEP].mTlId = 0; (timeline 0) mEpSchedInfo[MRA::EP_TYPE_STEP].mOffset = 2; mEpSchedInfo[MRA::EP_TYPE_STEP].mPeriod = 5; For component Y of an MRA model, where X is either TC, TM, HIL or State, the following code needs to be added to its constructor: mEpSchedInfo[MRA::EP_TYPE_STEP].mTlId = 1; (timeline 1) mEpSchedInfo[MRA::EP_TYPE_STEP].mOffset = 0; mEpSchedInfo[MRA::EP_TYPE_STEP].mPeriod = 10; Here mSchedInfo is an inherited variable available in the unit model code of every component to define in which slots the component should execute. We recommend to study the ThermoMra example heater model and the schedule file of the Software Configuration Facility (SVF) configuration to better under- stand the approach. By itself it is not complex and easy to use, but the concept is easier to understand in the context of a running simulator. The allocation of the generic MRA model components to that of the specific unit model components, the slots in which these components should execute (in terms of offset and repetition interval) and the timeline it is should be synchronized on, requires a system level analysis in which the frequency and offset requirements of a model components are to be taken into account and then a load balance is needed to distribute the model components over slots and processors to fit the available processing power.

17.3.3.2 Model modes The second element of the Unit model behavior is to support multiple configurations of real and simulated equipment within a single simulator (hybrid bench). This feature requires that models can be switched in different modes by setting the model mode member variable modelMode, provided through inheritance in each unit model MRA component to one of the following values:

• MRA_MODEL_MODE_DISABLED (0) : The model will not execute and be silent on interfaces,

• MRA_MODEL_MODE_SIMULATED (1) : The model is simulated, which means the step functions of the TC, TM and State components are executed as required,

• MRA_MODEL_MODE_HIL (2): The hardware in the loop component is scheduled instead of the TC, TM and State components. The unit developer can define the initial model mode upon instantiation of an MRA model as an optional constructor parameter to the MRA::BaseModel class. If not provided, the base model will set the mode to DISABLED. In development of testcases, the test developer will set the model mode either from a remote tool (e.g. the batch tools of EuroSim), or via the EuroSim Simulation Controller or via EuroSim scripts. By default, when the modelmode is SIMULATED the simulator enables the entrypoints of the TM, TC and State component and disables those of the HIL components of a unit model. Vice versa in HIL mode the HIL component entrypoints are enabled and the State, TM and TC component entrypoints are disabled. This default setting is often a good choice for sensors that either have a stimuli interface or come with dedicated stimuli equipment to support the use of the sensor in closed loop. For actuators this may be different, when included in the loop the output is a physical force that can not easily be fed into the control loop. An approach is then to run the model in parallel to the actuator, possibly using measurements as means for aligning the model. If this is the case it is more practical to integrate the HIL mode software in the TC and TM components. This deviation of the default is accomplished by changing the mode mask of a component. This mode mask is stored in a variable mModeMask similar to the mSchedInfo variables for defining the entrypoint execution on timelines. Initialize in the constructor the mModeMask variable to either

266 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• mModeMask=MRA_MODEL_MODE_DISABLED (0) : the entrypoints of the component will never be enabled

• mModeMask=MRA_MODEL_MODE_SIMULATED (1) : the entrypoints of the component will be enabled if the model mode is set to SIMULATED

• mModeMask=MRA_MODEL_MODE_HIL (2): the entrypoints of the component will be enabled if the model mode is set to HIL

• mModeMask=MRA_MODEL_MODE_SIMULATED | MRA_MODEL_MODE_HIL (3): the entrypoints of the component will be enabled if the model mode is either HIL or SIL

Setting the modemask for each component of the unit model allows fine grained tuning of the execution of the unit model in more advanced cases. If in a component entrypoint the model developer needs to differentiate depending on the model mode, the getMode() method can be called to detect the actual model mode.

17.3.4 Time The MRA models can access time via convenient getter routines provided by the MRA base model classes. An MRA modelcan retreive the time via the following inherited methods:

• getSimTime(): The simulation time, increased on every minor time step of the scheduler.

• getSysTime(): The system clock of the computer, as in time of day.

• getWallTime(): The wallclock time is the time provided by a EuroSim maintained clock which starts running at zero when the simulator is launched and increases synchronous with the system clock with the precision of the system clock. Sometimes users prefer to let EuroSim use the system time for timestamping but the usage of a wallclock time that starts at zero is beneficial as it is easier to compare results of different simulation runs in states where the simulation time is not running.

• getFacTime(): The test facility time, sometimes also referred to as bench reference time, is a clock slaved to a master clock in the test facility or bench. Some testfacility force the system clock to be equal to the facility time acquired over a hardware interface, but this is not required.

• getObcTime(): The time maintained by the onboard computer if distributed and if possible that it can be read.

It is advised that models do not use anything else then the simulation time as the usage of any of the other clocks generally require that the simulation always must run in realtime mode. Realtime execution limits the developers of the simulator and increase the need for resources. The simulation time, system time and wallclock time are always available to the model developer. The Facility time and Onboard time require that the user implements a class derived from the MRA::TimeManager which contains the code to read the facility time and onboard time.

17.3.5 Restrictions A very important restriction on the MRA is that all active entrypoints must complete in one cycle. This is generally not a problem, entrypoints for equipment simulation can be short and computation speed is high. The Modeler must also take this into account in writing the model software. The entrypoint can be scheduled more often to complete different parts of the model should the time consumption become a problem. This restriction applies to the effect on the basic cycle in EuroSim. It is possible to have tasks that do not have a deadline, for instance handling an event. Such tasks do not influence the basic cycle and are not checked, it is important to arrange in the model software that none of these tasks are running if for instance a snapshot is made. However for the MRA they are not relevant.

c Airbus Defence and Space 267 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

17.4 Interfaces

The MRA has three different types of users and hence three groups of interfaces:

• The Simulator developer uses the interfaces to setup the MRA and integrate it within the simulator, both in software as well as in the schedule file. He creates models and develops timelines and integrates these at system level of the simulator.

• The Model developer works in the context of a single model. Typically he is provided with a file setup by the simulator developer and is then tasked with filling the initialize, step and terminate methods in the components.

• Finally the end-user works with variables and events in the simulator to execute a simulation run.

The following sections group the interfaces used by these three users. First the Model Developer In- terfaces in Section 17.4.1, then the Simulator Developer Interfaces in Section 17.4.2, followed by the End-User Interfaces in Section 17.4.3.

17.4.1 Model Developer Interfaces 17.4.1.1 Services The MRA provides methods to the Model Developer via inheritance with a number of services in the form of methods available in the scope of the model software. For the Model Developer it is not so relevant which class provided them, as due to the inheritance the type of the class is not required. The following methods are available for use in the model software

• const char* getDictPath() provides the complete path of the location of the model in the dictionary.

• MRA::ModelMode getMode() provides the current model mode of the model, which can have the values MRA_MODEL_MODE_DISABLED (0), MRA_MODEL_MODE_SIMULATED (1) or MRA_MODEL_MODE_HIL(2). The value returned is what is set by the user in modelMode variable of the model in the dictionary.

• MRA::ModelState getState() provides the current state of the model. MODEL_STATE_CREATED (0), MODEL_STATE_PUBLISHING (1), MODEL_STATE_CONFIGURED (2), MODEL_STATE_CONNECTED (3). The value is set by the MRA library while going through the steps of creation, publication and con- nection.

• MRA::ModelState getModelName() provides the name provided to the model on creation. This is often used to discern between multiple instances in the model. It is advisable to pass a name that matches the name in the Front-End models.

• MRA::ModelState getTimelineSlotNr() provides the slot number of the timeline that the component calling this method is scheduled on.

• MRA::ModelState getSimTime() provides the simulation time of the current EuroSim minor cycle.

• MRA::ModelState getWallTime() provides the wallclock time of the current cycle, where the wallclock time starts at zero. Normally not used by the model developer as in non realtime us- age the wallclock time value at similar moments in time will depend on the speed of the simulation. Sometimes it can be useful in initialization where there is not simulation time.

• MRA::ModelState getSysTime() provides the time of the computer clock that EuroSim of the current cycle. As for wallclock time, this time should normally not be used by the model developer. The difference with the wall clock time is that the wallclock time starts at zero.

268 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• mraLog(severity,format, ...) provides the logging function that the user can control via the logLevel variable that is published in the dictionary. The severity can have the following values: LOG_ERRORS (0), LOG_WARNINGS (1), LOG_MESSAGE_STATE_CHANGES (2), LOG_MESSAGE_INFO (3), LOG_MESSAGE_DEBUG (4). The format and variable arguments part follow the printf interface. If at runtime the logLevel variable is set to a severity value, then messages with a severity in the mraLog call of the logLevel value and below will be printed.

• MRAPUB(variable,unit, description) is a macro that provides the user with an easy to use interface and standard manner to publish members of the Data class structures in the dictionary, potentially creating ports if needed. The interface is only applicable for members of the constant, init, config, input, output and internal structures in the Data class and to be used in the publication thereof in the Data::esimPublish function. The macro will look at the variable and determine which category it is and subsequently publish them in the group init, config, input, output or internal underneath the Data component. The macro includes mecha- nisms to determine the type of the variable and publish accordingly. For standard types this is based on overloading and always works. For user defined types we recommend to put these types in a C compliant include file and create a dummy static variable thereof. The EuroSim C parser automatically includes a definition of your type in the dictionary known to the C++ API which is much easier then defining it through an API. It is not needed to put the dummy variable in the API header of a file, its existence already is enough to trigger the parser when it parses the file. A common problem is that the underlying compiler is not properly provid- ing the type as c string to EuroSim and in these cases a function should be added to help Eu- roSim determine the type name of your variable through overloading. The function is simple, const char* eimTypeName(MyType arg){return "MyType";}; This function must be in the file where the MRAPUB is called for the variable of the type.

• MRAPUBDEV(variable, unit, description) as for the normal MRAPUB but hides the published variable for the operator. It will only be visible in e.g. the ApiTab of the simulation controller if the view is switched to developer. This allows the Operator to focus on relevant variables, but should it be needed the view can be switched to developer and all variables are visible again.

• MRAPUBX(variable,dictionary name, min, max unit, description) is a macro with the same features as the MRAPUB, however allowing the user to also add the unit, min and max description as strings.

17.4.1.2 Variables The model developer is provided with a number of variables to configure the behavior of the model. These variables are member variables inherited from other classes and are typically defined in the con- structor of the components. These variable setting then determine the execution of the entrypoints.

• mEpSchedInfo[MRA::EP_TYPE_STEP].mTlId defines on which timeline the step func- tion of the component is scheduled on, the value must be zero or higher, where zero is the standard timeline aligned with the tick of the EuroSim simulator. Higher numbers much match with the id provided when adding the timeline, which is part of the simulator developer interface.

• mEpSchedInfo[MRA::EP_TYPE_STEP].mOffset defines the offset on the selected time- line in the major cycle, which is the first slot in the major cycle in which the entrypoints are enabled

• mEpSchedInfo[MRA::EP_TYPE_STEP].mPeriod defines after how many slots after the previous activation the entrypoints are enabled again for one slot execution.

c Airbus Defence and Space 269 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• mModelMask defines in which model modes the component is active. Default the TM, TC and State components are active in the MRA_MODEL_MODE_SIMULATED (1) model and the Hil compo- nent is active in the MRA_MODEL_MODE_HIL (2) model mode. This can be adjusted for each com- ponent by changing the value. Beside the aforementioned two settings, also the value can be set to MRA_MODEL_MODE_DISABLED (0) and (MRA_MODEL_MODE_SIMULATED | MRA_MODEL_MODE_HIL) (3).

17.4.2 Simulator Developer Interfaces The Simulator interface works from outside the models to integrate it in the simulator including the development of timelines and creating channels between models to copy data from output port to input port. In the following sections the interfaces are therefore split according to the class they occur in.

17.4.2.1 BaseModel interface The unit model class is derived from the BaseModel class. Via this derivation the BaseModel class provides a number of services to simulator system developer to integrate the Unit models within the system with timelines and even front-end models.

• MRA::ModelMode getMode() provides the current model mode of the unit model, which can have the values MRA_MODEL_MODE_DISABLED (0), MRA_MODEL_MODE_SIMULATED (1) or MRA_MODEL_MODE_HIL (2). The value returned is what is set by the user in modelMode variable of the model in the dictionary.

• MRA::ModelState getState() provides the current state of the unit model. MODEL_STATE_CREATED (0), MODEL_STATE_PUBLISHING (1), MODEL_STATE_CONFIGURED (2), MODEL_STATE_CONNECTED (3). The value is set by the MRA library while going through the steps of creation, publication and con- nection.

• const char* getDictPath() provides the full path in the dictionary of the model after the model is published.

• MraTime getTime() provides the MraTime structure, which has as fields the simulation, wall- clock, system and facility time fields. This is a convenience function, see Mra::System description for more information.

17.4.2.2 BaseTimeline interface

To create timelines the simulator developer must implement a class that is derived from the MRA::BaseTimeline class. The objective of the BaseTimeline class is to update the value of its current slot number variable _slotNr when the MRA::System class update() method. The minimum that the developer must do in the derived class is to implement this update() which is pure virtual in the BaseTimeline class. The following code fragment shows BaseTimeline class and the most simule Timeline class which runs syn- chronized to the simulation execution:

class BaseTimeline :: public Log { public: // construct, destrcutor BaseTimeline(const char* pName="Timeline"); virtual ˜BaseTimeline();

// getters int getId() const { return _id; } int getSlotNr() const { return _slotNr; }

// initializing, updating and termination iface virtual int init() { return 0;};

270 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

virtual int update() = 0; virtual int term() { return 0;};

//! EuroSim publication interface virtual bool esimPublish();

protected: int _id; // unique timeline identifier int _slotNr; // the current minor frame number const Log& _parent; //reference to its parent for logging

}; class TimelineSim : public BaseTimeline { public: TimelineSim(); BaseTimeline("TimelineSim"){}; int update() { ++_slotNr ; _slotNr %= 40; return _slotNr ; }; bool esimPublish(){ BaseTimeline::esimPublish(); Esim::publish(_slotNr,"slotnr");

protected: unsigned _slots;

};

In the above derived TimelineSim class we assume that the update method is called at 40hz and we simply return the slotnr with a wrap at 40, thus we have 40 slots a second. To get the TimelineSim update method called, an instance must be created of this class and registered with the MRA::System class.

TimelineSim *tlsim=new TimelineSim(); MRA::System::instance()->addTimeline(0,tlsim);

By adding the TimelineSim instance tlsim to the MRA::System class, the System class will call the init, update and term of tlsim when the EuroSim scheduler executes the init, step and term entrypoints of the MRA::System class. The TimelineSim example’s simple slotnumber computation did not require an implementation of the init and term methods of the base class and hence the default implementation of the base class are used. The code fragment also shows that the addTimeline takes as first argument a number. This is the number of the timeline that is to be used in constructor of the model subclasses to assign step methods of the State, TM, TC and HIL classes to a certain timeline. More advanced timeline classes than the TimelineSim class will compute a slot offset on the basis of an external trigger. The ThermoMra example shows how this is performed when the trigger is related to sync modecodes on the mil1553 bus which are received through the Mil1553 front-end model. Because the synchronization to the simulator and the synchronization to the Mil1553 synchronization occur often, these two timelines are prebuilt available with EuroSim as the classes MraTimelineSim and

c Airbus Defence and Space 271 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

MraTimelineMil. These prebuilt classes are configurable at construction time and then added to the MRA::System class in the same approach as user defined classes. The ThermoMra example implements its own timeline classes to demonstrate how this is achieved, however the following use of the prebuilt MraTimeline classes in the esimCppSetup() function would have achieved the same result without any need to further program the timeline class.

//Timeline 0 runs in sync with the simulation, //time wrapping at 40 slots MRA::TimelineSim *tlsim=new MRA::TimelineSim(40); MRA::System::instance()->addTimeline(0,tlsim); //Timeline 1 runs in sync with the CDMU via the //sync modecode broadcast over the milbus/ //we are using the configurable EuroSim //TimelineMil class. We set it up for updating //on 40Hz /with 8 slots per minor cycle //(minor cycles starting with modecode 17 and //a frame number) and 5 minor cycles per major //cycle ( starting with mc1) MRA::TimelineMil *tlmil=new MRA::TimelineMil(40.0,8,5); MRA::System::instance()->addTimeline(1,tlmil);

The MRA::TimeLineMil class is an advanced class that uses the current test facility time from a time- keeper front-end model to establish how old an MC17 or MC1 synch mode code is to calculate the offset. When the sync modecodes stop arriving, a user configurable timeout (default 1 second) will allow the execution of the entrypoints connected to this timeline to continue such that the major cycle is com- pleted before it starts returning a value of -1 to stop the execution of these entrypoints. The execution is restarted when modecodes are received again. The TimelineMil example in the TermoMra example follows exactly the same approach and contains the same code, with the exception of the configurability through the constructor arguments.

17.4.2.3 TimeManager interface

The TimeManager interface is a class that implements the getSimTime(), getWallTime(), getSysTime(), getFacTime() and getObcTime() methods that are ultimately called when an MRA model invokes the methods with these names that it inherits from the MRA BaseModel classes. If no implementation by the user is performed, the MRA::System class implements this interface for the getSimTime(), getWallTime() and getSysTime() methods. The getFacTime() and getObcTime() methods will return -1 as a sign that these are not supported. This implementation is already sufficient for all normal simulations as preferably models only use the simulation time. However if access to the facility time is requried the simulator developer can implement a class that is derived from the TimeMan- ager class and register that with the MRA::System class such that it delegates the calls of the time getter routines to this TimeManager instance. The following code shows the TimeManager class:

class MRA::TimeManager { public: virtual double getSimTime() const =0; // return the actual simulation time (now) virtual double getWallTime() const =0; // return the actual wallclock time (now) virtual double getSysTime() const =0; // return the actual system time (now) virtual double getFacTime() const =0; // return the actual facility time (extrapolated) virtual double getObcTime() const =0; // return the actual distributed onboard time (extrapolated) };

The implementation of a TimeManager thus requires implementation of the time getter methods. The default implementation in the MRA:System class returns the EuroSim simulation time and wallclock

272 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

time in seconds as well as the value of the local clock as clock gettime function (which returns unix epoch). There is no assumption on the meaning of facility time and onboard time in for instance epoch. The registration of the an MRA::TimeManager implementation with the MRA system is accomplished in the following code:

MRA::TimeManager *timemanager= new MyTimeManagerClass(); MRA::System::instance()->setTimeManager(*timemanager);

As part of the Front-End models there are so called Timekeeper implementations. These Timekeeper models implement a TimeManager and connect the facility time and onboard time to specific interfaces at system level.

17.4.2.4 Data Exchange interface The parameter exchange interface of the MRA allows the user to define a list of parameters that are to be simultaneously transferred between models, and subsequently wrap this list in an exchangegroup which determines under which conditions the exchange it to be enabled. For example, the transfer of data from the OutPort x of model X to the Inport y of model Y should only happen when model X is in a certain mode and model Y is in a certain mode. The parameter list identifies the transfer of data from a port x to a port y. The list is an argument to the exchange group that combines this information with pointers to the model X instance and model Y instance and for both X and Y the mode that these models should have to enable the transfer. After creating the exchange group it is added to the MRA::system instance to which the MRA::System class provides an interface. The result is that a transfer is created in the dictionary which will show up in the XFER folder of the MRA system instance in the dictionary. The transfer is an entrypoint that must be added to the schedule and is enabled depending on the actual model modes of the output and output model that it relates to. We highly recommend looking into the ThermoMra example as this interface is not difficult, but complex to describe. The definition of a single parameter exchange is performed by creating a Param structure,

Param(const char* pName, const char* pFromPort, const char* pToPort);

The simulator developer must program an array of these exchanges as indicated in the following example, even if only one parameter is to be exchanged

const MRA::Param fromTo_params[] = { MRA::Param("heatFlux", "outport/mHeat", "inport/mHeat[0]") };

The next step is the creation of the exchange group by passing the array of parameters as argument

ExchangeGroup( const char* name, const char* fescr, MRA::BaseModel* from, unsigned long fromModelMask, MRA::BaseModel* to, unsigned long toModelMask, const Param params[], unsigned long sizeofParams, const EpSchedInfo& schedInfo)

Where

c Airbus Defence and Space 273 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• name is the name that the entrypoint to trigger the transfer will get

• descr is the description shown in the dictionary with the transfer entrypoint

• from is the pointer to the model that has the output where the data flows out of

• fromModelMask determines in which model modes the from model must be for the data to flow. Values are MRA_MODEL_MODE_SIMULATED (1), MRA_MODEL_MODE_HIL (2) and MM_MASK_HILSIL which is equivalent to the bitwise or of the previous ones (thus value 3).

• to is the pointer to the model that has the input port where the data flows to

• toModelMask is the same as fromModelMask but for the To model

• params is the array of params constructed in the previous call to create the MRA::Param array

• sizeofParams is always sizeof(params)

• schedInfo is a structure to be created using MRA::EpSchedInfo() which disregards the model modes and activates the data transfer whenever the transfer entrypoint is called in the EuroSim schedule. The alternative is to provide parameters to define on which timeline it is to be sched- uled: MRA::EpSchedInfo(tlID) make the copies every time the entrypoint is called by EuroSim according to the schedule, but in sync with the specified timeline instead of timeline zero and tak- ing into account the modelmodes of the in and output model. A further tailoring can be achieved using MRA::EpSchedInfo(tlId,offset,period,onoff). The additional arguments allow to set the offset and period on the timeline just as for components, and the onoff argument allows dis- abling of the model when set to false).

The created exchangegroup must be added to the system instance of the MRA, which is part of the System class description in this section.

17.4.2.5 System interface The MRA::System class is a singleton that manages the models, timelines and parameter exchanges in the dictionary. The setup of an MRA requires first the creation of models, timelines and parameter exchanges and addition thereof to the MRA::system instance. Once all are registered with the instance, Esim::publish can be used on the instance, which will publish all the models, timelines and exchanges in the dictionary.The system instance also publishes a number of entrypoints that are visible as members of the MRA system instance. These must be scheduled to activate the scheduling and mode handling of the MRA. The following methods can be called to interact with he MRA system instance object. The first method is the interface with the class to retrieve the singleton pointer to the instance,

• MRA::System* MRA::System::instance() return a pointer to the MRA::system in- stance and implicitly create it if it does not exist yet

• void addTimeline(unsigned int tlIdx, BaseTimeline* timeline) add a time- line instance to the MRA system with id tlId.This method must be used prior to publication (Esim::publish) of the MRA::system instance.

• BaseTimeline* getTimeline(unsigned int tlIdx) get a pointer to the timeline with id tlIdx

• void addModel(BaseModel &model) add a model instance to the mra. This method must be used prior to publication (Esim::publish) of the MRA::system instance.

• BaseModel* getModel(const char* name) get a pointer to the model with name "name"

274 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• void addExchangeGroup(const MRA::ExchangeGroup &pGroup) add an exchange group to the MRA system. This results in an entrypoint in the dictionary under system/XFERS with the name as defined in the exchange group definition after calling esimPublish. This method must be used prior to publication (Esim::publish) of the MRA::system instance and after all models have been created and added.

• const MraTime& getTime() const get the time structure for type MraTime. This struc- ture is intended to maintain times of different source recorded at the start of a EuroSim minor cycle. It is user responsibility to fill this structure.

• void setTime(const MraTime& t)set the MraTime maintained by the MRA system in- stance.

After publication the following entrypoints will be visible in the dictionary, with their specific scheduling criteria:

• init This entrypoint is to be scheduled in the initialization state of the EuroSim schedule and to be called after the user of the simulator has set the model mode variables and before calling any initialization routines of the unit models. Typically the schedule has a Configure event that the user or test script raises when all initialization variables have been set. The configure even then triggers a task which calls the MRA init entrypoint as first activity.

• stepStart This entrypoint calls the update method of all the registered timelines. It must be scheduled in the executing state of the EuroSim simulator, before calling stepSchedule and any unit model entrypoints in the executing state.

• stepScheduleThis entrypoint enables and disables the unit model entrypoints based on the model modes and timelines. It must be scheduled prior to activating any unit model entrypoints in the executing state

• stepEnd This entrypoint is to be scheduled after all unit model entrypoints completed. (It cur- rently has no content, but is reserved for future extension).

• end This entrypoint is to be scheduled in the Exiting state of the Scheduler. (It currently has no content, but is reserved for future extension).

17.4.3 End-User Interfaces The End-User of the MRA is the test developer or operator who needs to configure the simulator for a particular simulation run and monitors and analyzes the results. MRA compliant models publish a few variables that must be taken into account

• mode This is the model mode variable which is either DISABLED (0), SIMULATED (1) or HIL (2). The setting determines if the model is either simulated in the real-time simulator, or is attached as real equipment in the loop, support by the model in HIL mode. The model mode must be set prior to calling all the initialization entrypoints of the MRA models. This is normally setup by the Simulation developer in a specific simulator using the Configure event such as in the ThermoMra example. This allows the user to start the simulator, configure this mode variable, and then raise the Configure event which in the schedule kicks of an initialization task.

• state This is the output variable of the model that informs the end-user on the initialization state of the model. Its values are CREATED (0), PUBLISHING (1), CONFIGURED (2) and CONNECTED (3). The CONNECTED value will only be present if the model connected to front-end hardware that handles the electrical connection.

c Airbus Defence and Space 275 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• logLevel This variable is for debugging purpose and is an input variable that can be set any time during the simulation to increase or decrease the amount of logging that is printed to the Journal. It supports the following values: LOG_ERRORS (0), LOG_WARNINGS (1), LOG_MESSAGE_STATE_CHANGES (2), LOG_MESSAGE_INFO (3) and LOG_MESSAGE_DEBUG (4). The higher the value the more informa- tion is thus logged. What can be logged depends on the log statements that the Model Developer has added to the model.

Every Equipment submodel (State, TM, TC and HIL) also has a freeze vari- able, which when set to 1 will force that the the execution of the entrypoints of that submodel is skipped. This is feature that is useful in unit testing and is only visible when the user is in devel- oper view in the API tab. The feature allows for instance to freeze the State component such that it delivers a constant input to the TM model which makes it easier to test if the output is correct, while still using the output from the State model.

Besides setting these specific MRA variables the user should also set the parameters of the model as well as configure other components of the simulator such as the for instance the Front-End models (See Chapter 29). The model variables are defined by the Model Developer and should be documented in a project specific user manual. In the dictionary they will most likely appear as part of the Data subclass in an MRA model, or as member variable of one of the component subclasses (State, Tm, Tc, HIL). The Front-End models configuration variables to be configured are defined in the Front-End model chapter. The end-user can either set these variables by applying an initial condition file, activate an MDL script or manually set the variables via the API tab or via monitors/buttons on MMI tabs. Because it is relevant for the user to know which variables must be set at which time it is important that the model developer groups these variables to indicate that these variables either must be set before raising the Configure event, or can be set at any time during the simulation, or are input/output variables and hence normally overwritten by other models unless those models are disabled. The ThermoMra example operates in this manner, but this is entirely up to the Simulator Developer to decide and to document in a project specific user manual. Additionally, if the Simulation Controller set only the variables to visible that are allowed to be changed, then the end-user can set the Visibility filter in the API tab of the Simulation controller to Operator and will only see those variables. Furthermore, if a naming convention has been applied, the name filter can help the end-user to quickly find variables in the simulator.

17.5 Getting started

The MRA may be difficult to understand and look complex but in practice is surprisingly easy to use. Especially when starting from an example as ThermoMra that can be tweaked easily to the equipment that is to be modeled by the model developer. The same ThermoMra example is also a good basis for the system developer who develops the system level and has to set up the timeline handling, model intercon- nection and schedule file definition. In order to further assist in developing MRA based applications, this section provides some additional information on the ThermoMra example and a list of steps to be taken is defined as a checklist on the to be accomplished tasks. The easiest approach to setup models is to copy the unit model software from the ThermoMra example and adjust this towards the requirements for the new model. The unit model software in ThermoMra has a typical layout in files that is recommended:

• Model.h This file contains the class definitions for the State,Tm, Tc,Hil and Data components. The class Model is the encapsulating model that contains the State, Tm, Tc, Hil and Data components as nested classes of the Model class. Besides changing the modelname, the changes focus on the fields in the structures in the Data class.

• Model.cpp This file contains the implementation of the encapsulating model. This file assures that the Tm, Tc, Hil and State component have a member variable _data through which the structures and fields in the Data class can be accessed.

276 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• ModelTm.cpp implementation of the telemetry handling component of the MRA model. The model developer should fill in the init, step and term entrypoints.

• ModelTc.cpp implementation of the telecommand handling component of the MRA model. The model developer should fill in the init, step and term entrypoints.

• ModelHil.cpp implementation of the hardware in the Loop handling component of the MRA model. The model developer should fill in the init, step and term entrypoints.

• ModelState.cpp implementation of the state handling component of the MRA model. The model developer should fill in the init, step and term entrypoints.

• ModelData.cpp implementation of the data component of the MRA model. The data component is passive during a simulation as it has no entrypoints. The data component owns the variables that need to be in the EuroSim dictionary, which can be related to user input (init and config struc- tures), external model data exchange (input and output structures) or because the data is internally shared between the components of an MRA model (internal). If none of these apply it can still be necessary to publish the variables in the dictionary such that they are incorporated in the save and restore that is supported by EuroSim. The Data class therefore contains an esimPublish method in which the fields of structures can be published, and ports can be created. The macro MRAPUB is a convenience feature that reduces the amount of typing to publish the fields of the structure and enforces the storage in the correct folders. It is not required, the same can be accomplished with the CPP interface functions, but it will look very verbose while the MRAPUB reduces the amount of text.

Following is the list of steps to turn the ThermoMra example into your simulator. The steps are slightly different depending on the choice for ThermoMra1 or ThermoMra2 approach.

1. Copy the ThermoMra example and turn the unit models into your list of models underneath the folder UnitModels. Rename the type names towards your typenames, and comment out any code that is not compiling, the first goal is to make the instantiations of all models so you see the unitmodels in the dictionary.

2. Modify the file Constructor.cpp underneath System to create the instances you need. When you changes the type names in the unit models this file will already not have compiled an more and you had to comment out large parts of the code (use #if 0 rather the /* to comment out blocks). Comment out any code related to interconnection, first we want to see the instances in the dictio- nary.

3. Construct the transfers in the file Setup.cpp (ThermoMra1 only). You can use the ThermoMra1 transfer construction calls as an example, the approach is quite repetitive.

4. Update the schedule file towards the created instances. The entrypoints in the tasks will be incor- rect after updating the models. Furthermore, the master frequency and the clock in the executing state may need updating towards the frequency needed in the simulator. This depends on the size of the slots in the timeline, usually determined by timeline 0, that is the timeline that the State part is executed on.

5. Adjust the ThermoMra sim file. It may be wise to remove any mmi’s, they are typically project specific. The only mdl script relevant is the configure script which raises the configure event in the schedule.

At this point you should have an empty, but runnable, simulator, that contains all the instances of models that you anticipate and schedules their entrypoints in the schedule file. A next set of steps is needed for the interconnection of the models. This may be updated when the model developer starts elaborating the models, but it is usually already possible to make a first setup based in initial information or estimates. Thereafter the Model Developer can start adding behavior to the models and verifying this behavior in

c Airbus Defence and Space 277 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

a simulator that switches off all other models. If using the Front-End models the Stub can be used to trigger behavior on electrical lines, but it is also possible to fill in data in the FE or SIM side of the front end models. This can be performed for models in parallel, allowing multiple persons to work on modeling and testing simultaneously. Integration of the models with the front end models can be accomplished using the C++ port channel mechanism and using the C++ link mechanism. The link mechanism is mostly used to connect the equipment model to Front-End models. The latter are EuroSim provided models of generic front-end devices that incorporate buffering and error injection and hence linking is sufficient (see section Chap- ter 29). In this section the focus is therefore on the use of the port channel mechanism to interconnect models, which uses a copy approach with error injection capability to exchange data between models.

17.6 Unit Model programming guidelines

Following list of software constraints and coding rules shall be taken into account by the model software:

1. The model software shall not perform operating system calls or system IO function calls, and shall not create threads (other then through the esim.h interface for non realtime threads)

2. Execution of a single sub model step function shall be short as in a fraction of the minor cycle, typically less then 0.5msec. The sum of all models that will be active in a slot must fit in 75% of the size of the slot (as in milliseconds). Reading and writing to the Front-End hardware typically can eat about 2 msec, assuming that front-end model interfaces can be executed in parallel. These are estimates and depend on how much data is to be read per interface, henc eproject specific and must be estimated and monitored by the simulator developer.

3. The component entrypoint software software shall be re-entrant as instanced of models will be called in parallel

4. The model software shall not reference or execute software from other models to avoid that models can not be executed in parallel. This does not apply to unit components internally in a unit model. The State,Tm,Tc and Hil components of a unit model must be scheduled on the same processor such that they don’t conflict with each other.

5. The model software shall use the MRA API report functions to print messages. Though the Eu- roSim functions can be used, the MRA log interface allows the setting of the level.

6. The model step function call frequency shall in most cases be twice the frequency of the minor cycle on the mil1553 bus. The simulator developer needs to determine the optimum balance as the higher the simulator frequency, the lower the amount of time models and front-end interfaces have to complete.

7. Group the variables in the data class in initialization, configuration, input, output and internal. This is intended for the end-user to understand if a variable is to be set by him (init/configuration) or coming from other interfaces(input, output). The init group contains those variables that are to be set before the configure event. The configuration parameters are those that he is allowed to change in standby and executing state.

Using the model modes, the unit models can be tested in isolation while already integrated in the sim- ulator. The verification can stimulate inputs and measure outputs driven by test scripts and using error injection interfaces. If used in combination with the Front-End models, a stub is available with the Front- End models that supports the verification of the interfaces by stimulating the front-end models thus the telecommand interfaces on either Mil1553 or discrete lines.

278 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

17.7 Model documentation

The simulator and its corresponding unit models can be documentated using doxygen (www.doxygen. org). This documentation generator uses keywords and text placed in comments of the source code and builds html pages with references to the code. This section lists best practices on how to use doxygen to create clear and easily maintainable documentation on both system as unit model level.

17.7.1 System level documentation The landing page of the documentation can be easily customized by setting the \mainpage variable somewhere in the code comments. In order to make it easily retrievable, place a file rtsMainpage.dox in the simulator directory and place the \mainpage description in here. See example below.

/*! \mainpage RTS for Simulator Development

\section intro_sec Introduction

This is the RTS developer setup of the Thermo MRA example. In this simulator the onboard software executes as native compiled software in the simulator. The implementation is part of the CDMU model in this simulator.

The documentation of the unit models is most relevant and can be found in Modules.

\section dictdoc_sec Autogenerated documentation

Please see the EuroSim auto generated documentation. */ Do not forget to add the file rtsMainpage.dox to the model tree in the ModelEditor!

17.7.2 Unit model documentation The contents of a unit model (its source files, header files, classes and nested submodels) can be grouped in a module by defining a doxygen group (\defgroup). Consider a unit model MyModel. Place a file MyModel.dox in the unit model directory, and add the \defgroup description. See example below.

/*! \defgroup MyModel MYMODEL

\ingroup MyModel \section section_mymodel My Model Description

Detailed description of my model goes here. See RTS::MyModel. */ Do not forget to add the file MyModel.dox to the model tree in the ModelEditor! Each element can now be linked to the module using the \ingroup command. See example below (in file MyModel.h).

/*! * \file MyModel.h * \ingroup MyModel * \brief This header file contains the definition of MyModel * \details Detailed description of MyModel.h */

c Airbus Defence and Space 279 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

For clear documentation, please adhere to the following guidelines.

• Create a separate file with a group description using \defgroup for each unit model.

• Group all source and header files using \ingroup. Optionally add models and submodels to the group.

• Document all classes, structs and their member in the header file.

• Provide a \brief description for each class and struct.

• Document all (class) functions in the source files where they are implemented.

• Provide a \brief description for each function.

17.7.3 Linking to the autogenerated EuroSim model documentation. A html page listing all model instances rts.html, there variables and its data interchanges is automatically generated when building documentation for a model. However, this page is not automically listed in the doxygen documentation. By placing a manual link (in for instance the mainpage), the page becomes accessible in the documentation pages. See example below (please note the relative path in the href argument).

The page can be found here.

17.7.4 Requirements and to-do’s The documentation will provide a seperate menu item for requirements and todo’s when they are speci- fied in the code. For optimal documentation:

• List requirements using the \req command.

• List to-do’s using the \todo command.

An example is listed below:

\*! * \brief Entry point, initialize the model. */ void RTS::MyModel::init() { \\! \req REQ_OOO1_A The model shall properly initialize \\ the temperature measurement. mTemp = 21.0; }

\*! * \brief Entry point, do a step update of the model. */ void RTS::MyModel::step() { \\! \todo Implement step update of MyModel. }

280 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

17.8 Snapshot Save and Restore

A snapshot file captures the entire contents of the data dictionary at a certain moment in (simulation) time. A snapshot can be made at any moment during a simulation run. The snapshot can then be reloaded to quickly provide a starting point for subsequent simulation runs. The snapshot mechanism can be seen as an alternative way to establish an initial conditions file. In fact, the formats of snapshots and initial condition files are identical, see Section A.7. The difference between a snapshot and an initial conditions file is that a snapshot contains the value of each data dictionary variable; an initial conditions file usually contains only a subset of the data dictionary variables. A snapshot can be made and reloaded manually with the Simulation Controller, see Figure 12.9. There are also MDL commands to make and reload a snapshot; these are snapshot and reinit, see Table 23.5. A snapshot file contains the contents of the data dictionary but what if the data dictionary is not enough to capture the complete state vector of a simulation facility? This typically happens if a simulator is connected to external components whose state must be saved together with a snapshot, for example, the runtime state of a CDMU emulator. For this reason, the MRA extends the snapshot feature with pre- and post-functions to the snapshot and reinit commands. Each MRA model and equipment sub-model has empty implementations of these functions:

class BaseModel : public MRA::Log { public:

virtual bool savePrepare(const char* savepath); virtual bool saveFinish(); virtual bool restorePrepare(const char* restorepath); virtual bool restoreFinish(); };

class BaseEquipmentSubmodel { public:

virtual bool savePrepare(const char* savepath); virtual bool saveFinish(); virtual bool restorePrepare(const char* restorepath); virtual bool restoreFinish(); };

When making a snapshot, the savepath argument holds the name of the existing directory in which all (custom) snapshot files need to be saved. EuroSim will add its snapshot file to that same directory with the fixed name rts.snap. Likewise, the restorepath argument holds the directory from which to load a snapshot made earlier. Because EuroSim entry points cannot have arguments, the MRA system class publishes two data dictio- nary variables through which the test operator can set the savepath and restorepath arguments:

/CPP/Spacecraft/mra/savePath /CPP/Spacecraft/mra/restorePath

The ThermoMra example contains the boiler plate code to add the extended snapshot feature to an MRA simulator. The general recipe is as follows:

c Airbus Defence and Space 281 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

1. Implement the snapshot pre- and post-functions for those models or sub-models that need custom actions.

2. If the custom action is in a MRA::BaseEquipmentSubmodel, implement corresponding pre- and post-functions in the parent MRA::BaseModel that call the sub-model.

3. Add an MDL script with save and restore actions to the simulator definition file.

4. Add a task to the schedule that is triggered by the SNAPSHOT_END event and that calls the restore- Finish functions.

The MRA system class publishes four entry points for the snapshot pre- and post-functions. These entry points call the corresponding function for each MRA::BaseModel in the simulator. Since the presence or absence of equipment sub-models is hard-coded by the model developer, explicit boiler plate code is needed to forward the calls to the MRA::BaseEquipmentSubmodel objects. ThermoMra contains this boiler plate code for each MRA model, for example the heater in Htr.cpp:

bool Htr::savePrepare(const char* savepath) { bool ok = true;

Esim::message("%s: savePrepare", getName());

// nothing to do at model level, just cascade down to equipment // sub-models

if (_state.isEnabled()) { ok = ok && _state.savePrepare(savepath); } if (_tc.isEnabled()) { ok = ok && _tc.savePrepare(savepath); } if (_tm.isEnabled()) { ok = ok && _tm.savePrepare(savepath); } if (_hil.isEnabled()) { ok = ok && _hil.savePrepare(savepath); }

return ok; }

Note that the function call is only delegated down to equipment sub-models that are enabled; in other words, whose mode mask corresponds with the current model mode. When all snapshot pre- and post-functions have been implemented, two MDL actions need to be de- fined to call those functions. ThermoMra contains examples of these two actions in Simulator/Numeri- cal/rts.mdl. The actions are called “Save” and “Restore”. The “Save” action takes these steps:

1. savePrepare

2. snapshot

3. saveFinish

The “Restore” action contains only two steps:

1. restorePrepare

282 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

2. reinit

The restoreFinish call is not in the “Restore” action because reinit is asynchronous. Completion of the reinit command is signaled by the SNAPSHOT_END event, see Section 11.3.4.2. That is why the final step is to add a task to the schedule in the standby state that is triggered by SNAPSHOT_END and that calls the entry point /CPP/Spacecraft/mra/restoreFinish. For example, see the schedule file of ThermoMra/Simulator/Numerical/rts.sched.

Figure 17.6: Call restoreFinish after the SNAPSHOT END event

IMPORTANT: The MRA snapshot extension only works in standby mode. This is the only way to ensure that the simulator is in a stable situation that can be safely captured and restored.

c Airbus Defence and Space 283 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

284 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 18

Simulation Model Portability 2 reference

Simulation Model Portability (SMP) is ESA’s standard for simulation interfaces. The purpose of the standard is to promote portability of models among different simulation environments and operating systems, and to promote the re-use of simulation models. Although SMP2 is the successor of SMP, it is radically different from it’s predecessor. It adopts state-of-the-art techniques, and has a much wider scope than its predecessor. The way of working with this standard and its complexity demand tools for specification, development, integration, and storage of the SMP2 models. EuroSim incorporates a set of tools to accomplish many of these tasks. Knowledge of the SMP2 standard is a prerequisite for successfully using the SMP2 tools to create SMP2 models. For an overview of the standard, refer to [SMP05c]. For a comprehensive, formal descrip- tion of the standard, see [SMP05e] for the SMP2 Meta Model (or Simulation Model Definition Lan- guage, SMDL), [SMP05b] for the SMP2 Component Model, [SMP05a] for the SMP2 C++ Mapping and [SMP05d] for the SMP2 Model Development Kit (MDK). Almost all of the SMP2 (v1.2) standard features are supported in EuroSim. Additionally SMP2 mod- elling can be mixed with usage of other EuroSim API’s, allowing the use of EuroSim native capabilities in cases where SMP2 is not sufficiently equiped. This for instance is the case in realtime scheduling and hardware in the loop support. EuroSim is uniquely equiped for this domain, where its frame scheduling mechanisms support multiprocessor support, interrupt handling and preemption which far exceeds the SMP single threaded timeline scheduling. Other areas where mixed usage is useful is in the area of front- end modelling where the naticve C++ API offers configurable models with out of the box mil1553 and discrete signal hardware interfaces. Also typical are the use of legacy models that are not yet converted or that the standard does not (yet) foresee in a required functionality that is then temporarily implemented with native solutions, offering a path that allows gradual conversion to full SMP2. As an example all of the previous options are applied at ESTEC’s avionics test bench with hardware in the loop en route to a finally fully SMP compliant bench. Note that also in many areas, particularly related to running simula- tions and using the data, there is no difference in which API the model was coded as the operations only refer to EuroSim’s dictionary items which is language independent. When mixing the use of APIs the risk occurs that the models loose their portability, but the fit of SMP2 in EuroSim has been performed in such manner that the user’s models remain untouched, which keeps the SMP2 models portable. Examples are added to EuroSim to illustrate how to reuse models, as well as an architecture and support library for easier use of SMP2 in EuroSim. With the latter some features are used that are EuroSim specific, but those are also note required to be used if portability is essential. It is important though to note that SMP2 seems to support portability of models in binary format, but in reality this is problematic because the interconnection of a model to the platform typically is done using code generation, and that generated code that becomes part of the model is not standardised by SMP2 and as a result platform specific.

c Airbus Defence and Space 285 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

18.1 Using SMP2 in the EuroSim Environment

Following EuroSim’s concept, EuroSim focusses on import of SMP2 models and their use in combination with models in other languages and its wide array of realtime simulation features. This SMP2 support is offered through integration of SMP2 supporting functionality in EuroSim’s standard graphical user interfaces for simulation development and commandline tools. Supporting SMP2 model import means that EuroSim contains the tools to process the SMP2 artefact files, but that it does (currently) not offer a dedicated graphical editor for creating these artefact files. Of course editing can be performed with graphical text editors as for example gedit which provides highlighting for XML, which is helpful but does not have the context and crosschecking for SMP2 modelling. It is possible to configure the usage of an external editor through setting the SMP2EDITOR environment variable to the path of an SMP2 artefact viewer/editor to allow direct acces from the Model Editor to a more dedicated tool. One example is the UMF developed by ESOC on top of the UML modelling tool MagicDraw. The UMF provides a graphical UML interface to generate the XML files and potentially source code. For EuroSim on the XML files are relevant as the code generator is included with EuroSim. Another SMP2 modeling tool is MOSAIC from the National Aerospace Laboratory (NLR). This tool can convert models from specialized simulation tools as Matlab/Simulink to SMP2, generating both XML files and EuroSim compliant ready to use implementation software. Importing SMP2 models into a EuroSim simulator is performed by placing SMP2 files in the Model Ed- itor’s file tree. Defining and implementing SMP2 models ultimately results in compiled models located in binary libraries. EuroSim allows the generation of both shared and static libraries on Linux and static libraries only on other platforms. We will call such library an SMP2 library. In the model tree the user will organise all SMP2 models in one or more SMP2 lib nodes (see Section 7.3.3) which each represent an SMP2 library to be produced. Each SMP2 lib node can contain exactly one SMP2 package which defines the contents (implemented types) of the library. Each SMP2 lib node then produces a static li- brary and a dynamic one. Note that on platforms other than Linux, only the static library is used. More information on the user interface can be found in Chapter 7) The SMP2 model libraries implement the model types but that still requires the definition of the model instances and their integration. This is accomplished by the incorporation of the Assembly file in the Model Editor. These files can be anywhere incorporated as a file node to assure processing by the simu- lator build, but typically are included at the top level. Multiple assembly files can be present, instantiating multiple model instances, refering to the catalog files and package files in which the models are defined and implemented. Assembly files can also refer to eachother if an interconnection is needed between in- terfaces of model instances from different assembly files. Interconnection can be based on interface and dataflow links. The model assembly, its contained model instances, their fields and links are all visible in the data dictionary after a succesful simulator build under the SMP2 root node. When the model instances are visible in the dictionary their entrypoints can be scheduled. Their are two methodologies supported. First entrypoints can be defined and scheduled in SMP2 schedule files and these SMP2 schedule files can be imported in the EuroSim Schedule Editor. At that point the EuroSim schedule capabilities can be used. The second approach is when SMP2 model schedule themselves using the SMP2 scheduling API. In this case an SMP2 scheduler task can be place in a EuroSim schedule which supports the SMP2 scheduling API and executes the model similar to the SMP2 scheduling approach in a context of EuroSim scheduling. More detailed information on the first approach can be found in Section 18.4 Usage of SMP2 modelling in simulation execution (e.g. Simulation Controller, MDL and Batch scripting, Monitoring and Recording) is the same as for any other model. The operations apply to dictionary elements. The same holds for usage in post processing such as in the Test Analyzer and data conversion tools as r2a. When using SMP2 in the EuroSim environment, always turn on SMP2 support in the Build Options. On Linux, you may choose between SMP2 support with dynamic linking of generated libraries and SMP2 support with static linking of generated libraries. On other platforms, only static linking of SMP2 libraries is available.

286 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

18.2 SMP2 tools in the EuroSim Environment

Most of the workflow from importing catalogues to compilation and integration into a EuroSim simulator has been fully automated using the following tools:

• Model Editor The EuroSim ModelEditor allows to import SMP2 artefacts, generated C++ code, and even com- piled SMP2 libraries. It provides point and click acces to the underlying SMP2 command line utilities described below and allows automatic building of an SMP2-aware EuroSim simulator. See Chapter 7 for more information on the Model Editor.

• SMP2 Validator smp2val The SMP2 validator allows checking of SMP2 artefacts against the standard. This allows the user to check for errors in the XML files. When coming from an editor this will likely not be a problem, but quite often manual tweeks are made and then the validator usefulnes is simulator to that of a source code check by a compiler. The SMP2 validator is integrated in the Model Editor as well as accessible from the command line such that it can be operated from external make files and scripting.

• SMP2 Code Generator and Integrator smp2gen The SMP2 code generator allows (re-)generation of SMP2-compliant C++ code from the imple- mentations defined in an SMP2 package file (which connects a model implementation library to the specification of the included models in the catalogue). The results of a generation are header files and implementation files ready for the user to fill the generated empty methods with model specific functionality. This is generated in a directory structure according to standard SMP2 ap- proachs and including makefiles. The code generator puts markers in the header, implementation and make files, such that it can automatically re-align the user’s implementation with changes in the XML file. This is very important to allow the user to independently maintain and update the XML files and assure that the implementation remains consistent without manual effort or the risk of loosing work. The SMP2 code generator is integrated in the Model Editor as well as accessible from the command line such that it can be operated from external make files and scripting.

• SMP2 Glue code generator smp2glue The SMP2 Glue code generator generates source code from one or more SMP2 assembly files. These assembly files define the model instances in the simulator and how their interfaces are in- terconnected to form a simulator. The Glue code generator generates the source code that gets integrated in the EuroSim’s startup to instantiate the models and interconnect them. The result is a model hierarchy in EuroSim’s Dictionary. The SMP2 glue code generator is automatically invoked when builing an SMP2 simulator with assembly files in the ModelEditor. Although rarely required, it is also possible to call the SMP2 Glue code generator from the commandline.

• SMP2 default package generator smp2cat2pkg The SMP2 default package generator is an optional tool, typically used when XML files are written or updated manually. It creates a default package file for all the types in a specific catalogue file. From this point it can then be the basis for generating or updating the source code for a package (library). The tool is most often used from the Model Editor, but is accessible from the command line as well.

• Schedule convertor (Schedule Editor) smp2sched

• SMP2 schedule converter The SMP2 schedule convertor is also an optional tool, it automates conversion of one or more related SMP2 schedules to a EuroSim schedule. Whether this tool is useful to a user depends on his approach to scheduling. If however an SMP2 schedule XML file is provided, the contents of

c Airbus Defence and Space 287 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

such file can be converted to a EuroSim schedule file format and subsequently that can be the basis for further schedule elaboration in the EuroSim Schedule Editor. This tool can be used on the command line (smp2sched after which the resulting schedule file can be opened in the Schedule Editor, but can also be activated from inside the Schedule Editor to import an SMP2 schedule file. (See Chapter 11)

Apart from the tool and utilities described above, the EuroSim distribution comes with:

• lib/SMP2COMPLIANCE.txt describing details of SMP2 support for user reference.

• Smp.cat, the standard SMP2 catalogue defining some low-level details inside the Smp namespace. This file is included for reference by EuroSim when using SMP2 catalogues that refer to elements inside the Smp namespace (except the predefined types).

• Schemas of the SMP2 standard, at lib/schemas/smp2, for user reference.

• Compiled versions of the SmpCpp and SmpMdk libraries containing the MDK functionality, that are linked by EuroSim with an SMP2 simulator.

• A compiled version of the Component Model library that allows running of SMP2 models in the EuroSim run-time environment, linked by EuroSim with an SMP2 simulator.

For the command line tools described, on-line manual pages [MAN18] are available.

18.3 Modelling scenarios

Four different modelling scenarios are elaborated to illustrate what to do in situations that differ in the amount of artefacts and implementation that is provided for import into the Model Editor.

18.3.1 Importing an SMP2 catalogue The first way of using SMP2 in the EuroSim environment is by starting off with just one or more SMP2 catalogues, produced using some SMP2 modelling environment. This applies when no generated code and package are available, and when the user prefers to use the automatic package creation and C++ code generation and integration facilities of EuroSim. If there are multiple catalogues these may be related, i.e. one catalogue may contain dependencies to another. These dependencies consist of references of a type specification in catalogue A to a type in a catalogue B. Take care to import all related artefacts, or else elements will be missing from the generated C++ code and the simulator cannot be built. Do not import the Smp.cat catalogue, which defines the default SMP2 namespace. It is already installed as part of the EuroSim installation. It is assumed that the user has an SMP2 modelling environment for producing an SMP2 assembly based on the packages to be generated. The catalogue import scenario consists of the following steps: Define library For each SMP2 library to be created, the user adds an SMP2 lib node to the model tree. In this scenario, it is required that each catalogue results in its own SMP2 library. For each catalogue to be imported, create an SMP2 lib node with the same name as the catalogue (see Section 7.3.3 for more information on SMP2 lib nodes). E.g. for a catalogue named Mission.cat, an SMP2 lib node named Mission must be created in the model tree using the Add SMP2 Lib Node menu option (see Section 7.5.2).

288 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Import catalogue Attach the catalogue to the SMP2 lib node just created using the Add SMP2 Catalogue menu option (see Section 7.5.4). The catalogue file is expected to have the extension .cat. Option- ally, run the validator on the catalogue using the Validate SMP2 Artefact menu option (see Section 7.5.7). Note that the user may view and edit the catalogue from the Model Editor (using any SMP2 modelling environment) by double-clicking on the catalogue. See Section 7.3.4 for setting the SMP2 modelling environment of your choice. Generate package The contents of an SMP2 library is determined by the implementations defined in an SMP2 package. In this scenario, no package is available beforehand. For each SMP2 lib node, auto- matically generate a package from the catalogue that is attached to it using the Generate Default Package menu option (see Section 7.5.7). This generated package called the default package contains an implementation of all types in the catalogue from which it is generated (except the types that do not require an implementation in SMP2). Optionally, to be sure, run the validator on the generated package using the Validate SMP2 Artefact menu option (see Section 7.5.7).

Note that the user may view and edit the generated package (using any SMP2 modelling envi- ronment) by double-clicking on the package. See Section 7.3.4 for setting the SMP2 modelling environment of your choice. Generate C++ code and Makefile The next step is to generate code from the package attached to the SMP2 lib node using the Generate C++ Code menu option (see Section 7.5.7). A hierarchy of org nodes and file nodes will be attached to the SMP2 lib node. This tree has the same name as the SMP2 lib node and contains all code generated from the package attached to the SMP2 lib node. The code consists of a C++ header file (.h) for each type, a C++ implemention file (.cpp) for all types that need one, and for some types a C++ forward reference header file ( f.h). The C++ code is organised in a directory hierarchy which reflects the namespace hierarchy of the implemented types as defined in the attached catalogue. Apart from the type-related C++ code, three C++ files are generated for management of the types contained in the static and dynamic libraries that are built from the generated code. Finally, a Makefile is generated that manages the building of the libraries. This makefile is called at the start of the EuroSim Build All process and implements the all and clean targets.

On the file system, the generated files are located in a directory named after the SMP2 lib node which is generated inside the project directory. The directory hierarchy inside this directory is identical to the org node attached to the SMP2 lib node. Add model logic The generated files can be inspected and edited by double clicking the file node (see Sec- tion 7.3.4). The user may add logic between the unique markers that indicate that a user im- plementation is expected at that location (where $uuid$ and $id$ are replaced by an actual univerally unique identifier (which is the type’s implemention UUID as specified in the pack- age) and an additional identifier, respectively):

// START USER CODE $uuid$-$id$ // END USER CODE $uuid$-$id$

It is strongly recommended not to remove these markers. Code placed between them will be integrated in a new version of the file if the code is re-generated. Other code added by the user is lost on code re-generation. Note that these markers are also available in other locations in the source and header files and even makefiles to preserve e.g. extra includes or additional definitions

c Airbus Defence and Space 289 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Build library Build the SMP2 library using the menu option If compilation is successfull, the shared and static versions of the library are automatically installed in the central installation directory of the project by the generated makefile. If there are any compilation errors, fix them in the added code and retry. Import assembly Using an SMP2 modelling environment, create an assembly based on the implementations de- fined in the packages. Copy the assembly file conveniently to the project directory. Add an assembly file node to the model tree using the Add File Node menu option (see Section 7.5.2, select SMP2 Assemblies as file type). The assembly is expected to have file extension .ass, .asb, or .asm. Any number of assemblies can be added. Note that if multiple interdependent assemblies exist, all of these must be added to the model tree, or building the simulator will fail. Optionally, run the validator on the assembly using the Validate SMP2 Artefact menu option (see Section 7.5.7). Turn on SMP2 support Select the Tools:Set Build Options menu item. Go to the Support tab page and place a check mark on one of the SMP2 support items. On Linux, you may choose between SMP2 support with static linking of generated libraries and SMP2 support with dynamic linking of generated libraries. Choose the options which suits your needs best. Don’t choose them both. Build simulator The final step is to build the SMP2-compliant EuroSim simulator using the Build All menu option. Note that during this process, code is automatically generated from the assemblies. This code takes care of loading the shared libraries, creating instances, and interconnecting them as spec- ified in the assemblies. (see Section 7.5.6).

18.3.2 Importing an SMP2 catalogue, package, and assembly The second way of using SMP2 in the EuroSim environment is by starting off with one or more SMP2 catalogues, packages, and assemblies, produced using some SMP2 modelling environment. Either no generated code is available, or the user prefers to use the C++ code generation and integration facilities of EuroSim. Note that the difference with the first scenario consists of the fact that a package is available (and an assembly can be created before the import as the package is available). Take care to import all related artefacts, or else elements will be missing from the generated C++ code and the simulator cannot be compiled. The catalogue, package and assembly import scenario consists of the following steps: Prepare import See Section 18.3.1, step Prepare import. Define library For each SMP2 library to be created, the user adds an SMP2 lib node to the model tree. In this scenario, it is required that each package results in its own library. For each package to be imported, create an SMP2 lib node with the same name as the package (see Section 7.3.3 for more information on SMP2 lib nodes). E.g. for a package named Mission.pkg, an SMP2 lib node named Mission must be created in the model tree using the Add SMP2 Lib Node menu option (see Section 7.5.2). Import catalogue Each package implements types specified in one or more catalogues. Attach these catalogues to the SMP2 lib node just created for the package using the Add SMP2 Catalogue menu option (see Section 7.5.4).

290 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Note that any number of catalogues may be attached to an SMP2 lib node. If a package imple- ments types from more than one catalogue, these can all be attached to the package’s SMP2 lib node. See Section 18.3.1, step Import catalogue for more information. Import package Attach a package to each SMP2 lib node using the menu option Add SMP2 Package (see Sec- tion 7.5.2). The package is expected to have file extension .pkg. See Section 18.3.1, step Generate package for more information.

From this point on, the scenario is exactly as the one described in Section 18.3.1, step Generate C++ code and Makefile and further.

18.3.3 Importing an SMP2 catalogue, package, assembly, and generated code The third way of using SMP2 in the EuroSim environment is by starting off with one or more SMP2 catalogues, packages, code generated from it (with model logic added), and assemblies, produced using some SMP2 modelling environment. The user wants to import an externally produced SMP2 library at the source level and an assembly. Note that the difference with the second scenario consists of the fact that generated code is available and model logic is added to it. The following steps are needed such that this code can be used from EuroSim:

• There must be an SMP2 lib node with a package file in the ModelEditor. If such package file is present, EuroSim knows that is must load a library at runtime with the basename of the package and extension .so (Linux) or .dll (Windows). Thus on Linux, the presence of Mission.pkg, forces the load at build and runtime of the dynamic library libMission.so. The file libMission.so must be in the search path, thus its location must be known either as part of ld.so.conf, LD_LIBRARY_PATH setting, or its location must be known by passing pWl, -rpath= as linker option via the EuroSim Build Options. Note that this rpath solution is performed automatically for the directory where EuroSim builds the executable and dictionary (.). When code gener- ation is used, the resulting libraries are copied into this directory by default to assure it is found by the loader.

• A Makefile can be added to the libnode to assist in building the library software as part of the EuroSim Build All (prior to any other activities of the Build All or Clean All actions). Such makefile is can be added via the Insert or context sensitive menu of an SMP2 libnode. The user has to expand the all and clean targets.

• The generated code must not incorporate calls to unsupported ComponentModel interfaces. See the file SMP2COMPLIANCE.txt which is part of the EuroSim distribution.

• The generated code must be equivalent to code that would be generated by EuroSim for the pro- vided artefacts.

Therefore, in practice this way of importing is limited to code generated by another instance of EuroSim and for code generated by an external tool that is specifically targeted at EuroSim. Take care to import all related artefacts, or else elements will be missing from the generated C++ code and the simulator cannot be compiled. This import scenario consists of the following steps: Prepare import See Section 18.3.2, step Prepare import, on how to prepare import of catalogues, packages, and assemblies. Copy the generated code including the Makefile to the project directory. Define library See Section 18.3.2, step Define library.

c Airbus Defence and Space 291 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Import catalogue See Section 18.3.2, step Import catalogue. Import package See Section 18.3.2, step Import package. Import generated code and Makefile Using the menu option Add Generated C++ Code (see Section 7.5.2), attach the tree of gen- erated code to the SMP2 lib node. You may have to edit the Makefile to make it compliant to EuroSim. Also, the name of the model file is used in the Makefile if the Makefile is originally generated by EuroSim. Change it to the actual name of the model file.

At this point, the scenario becomes identical to the first two from the step Install library onward. See Section 18.3.1.

18.3.4 Importing an SMP2 catalogue, package, assembly, and library This final import scenario is comparable to the previous one, except that no source files are available, but only catalogues, packages, assemblies and shared libraries. This is the case e.g. when the originator of the executable model wishes to hide the model sources. The user wants to import an SMP2 library at the binary level. This way of working in practice is limited to binaries generated by another instance of EuroSim, or by an external tool that specifically supports EuroSim SMP2, on the same platform as the import platform such as MOSAIC. This import scenario consists of the following steps: Prepare import See Section 18.3.2, step Prepare import, on how to prepare import of catalogues, packages, and assemblies. Create a directory with the same name as the package inside the project directory. Inside it, copy the shared library. Define library See Section 18.3.2, step Define library. Import catalogue See Section 18.3.2, step Import catalogue. Import package See Section 18.3.2, step Import package. Assure libraries are found The simulator during build and run dynamically loads the SMP2 model libraries in a dynamic linked simulator. The loading of the libraries requires that the libraries are in the dynamic library search path. This path can be set in three different ways: ldconfig, LD_LIBRARY_PATH, the pWl, -rpath= link option. An alternative and easy to use option is to copy the libraries to the . directory where the simulator executable also resides and which path is already included via the rpath solution. This can be automated by putting a makefile (with extension .mk) in the model tree, which then has to implement the all and clean options which subsequently should copy the library to the mentioned folder and remove it from there. These makefiles will get invoked at the start of a simulator build prior to all other build actions and will have similar effect as the use of static libraries which become integrated in the simulator executable. menu options are not available for this scenario.

At this point, the scenario becomes identical to the first two from the step Import assembly onward. See Section 18.3.1.

292 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

18.4 SMP2 scheduling scenarios

There are three different approaches to scheduling of SMP2 models, depending on the available SMP2 artefacts, the SMP2 model implementation and the required scheduling needs. Of course these ap- proaches can be mixed in one simulator if desired. First the simulator developer can schedule the entry- points published by SMP2 models in tasks in the Schedule Editor. Second, the simulator developer can import an SMP2 schedule into the Schedule Editor to preload it with the SMP2 schedule information and then be able to adapt that to the needs. Third, one or more SMP2 scheduler tasks can be placed on the Scheduler canvas which supports the SMP2 scheduling API used by self scheduling SMP2 models. The three methods are elaborated in the next sections.

18.4.1 Native scheduling The native scheduling solution applies when no SNP2 scheduling file is present, for instance because the models are self scheduling by calling the SMP2 scheduling API functions, or simply only model artefacts were provided. Since the SMP2 models publish their entrypoints they are present in the the dictionary and can be invoked just like any other entrypoint in EuroSim. Similar to other entrypoints their timings are recorded and available afterwards.

18.4.2 Importing an SMP2 schedule The Schedule Editor allows to import an SMP2 schedule artefact. Such a schedule is converted to an equivalent native EuroSim schedule by the command line tool smp2sched. From the File menu, use the Open. . . menu option and select SMP2 Schedules as file type. An SMP2 schedule is expected to have the file extension .sed. After conversion, the schedule can be inspected (and possibly edited) in the Schedule Editor. It is recommended not to change the converted schedule as any changes will be lost on when a future change in the original SMP2 schedule requires a new conversion to a EuroSim schedule. Note that the result of the conversion is a simple, non real-time, single-processor EuroSim schedule. SMP2 schedules lack the semantics to express complex, hard real-time time scheduling. For details on the conversion, see the on-line manual page of the smp2sched tool. This manual page also describes some limitations that apply to the schedule conversion. An SMP2 simulator’s schedule need not be limited to a single file. It is possible to specify a schedule using multiple SMP2 schedule files. EuroSim allows converting such a coherent set of SMP2 schedule files into a (single) EuroSim schedule. This can be achieved by using the smp2sched tool from the command line. See the manual page of smp2sched for details.

18.4.3 Self scheduling SMP2 models In the previous section, it was explained how to import an SMP2 schedule file into EuroSim. This is what the SMP2 standard refers to as a “dynamically configured” schedule. A “statically configured” schedule is also possible; this means that the SMP2 schedule is configured from source code. To set up a statically configured schedule, two steps need to be taken:

1. Add events to the scheduler by calling IScheduler::AddSimulationTimeEvent from within the model source code.

2. Schedule the SMP2 system tasks among the other EuroSim tasks. This is done with the Schedule Editor.

This two-step approach is necessary because of the differences between the parallel, hard-realtime Eu- roSim scheduler and the inherently single threaded, non-realtime SMP2 schedule. SMP2 events are executed by special SMP2 system tasks because SMP2 events are not native EuroSim entry points.

c Airbus Defence and Space 293 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The first step is to have each SMP2 model add SMP2 events to the schedule. This is done in the IModel::Connect() function that needs to be implemented by each SMP2 model. EuroSim generates boiler plate code for the Connect() function when importing an SMP2 catalogue — see section 18.3.4. Based on the class based Counter example from the SMP2 Handbook, a simple implementation of the connect function could look like this:

void (::ClassBased::Counter::Connect)(::Smp::ISimulator* simulator) throw (::Smp::IModel::InvalidModelState) { // START USER CODE 6bf35670-29f4-4a1e-9a5e-deb3638c206f-Connect ::Smp::Mdk::Model::Connect(simulator); // call first to perform state transition simulator->GetScheduler(0)->AddSimulationTimeEvent(Count, 0, 1000000000, -1); simulator->GetScheduler(1)->AddSimulationTimeEvent(Reset, 0, 10000000000, -1); // END USER CODE 6bf35670-29f4-4a1e-9a5e-deb3638c206f-Connect }

In this example, two entry points of the Counter model are added to the schedule: the entry point Count() will be executed every second and the entry point Reset() will be executed every 10 seconds. Two remarks about this example: First, EuroSim only supports simulation time events; it does not support Zulu time events. Second, the integer argument to GetScheduler() is a EuroSim specific extension of the SMP2 standard. EuroSim uses a parallel, realtime scheduler that can utilize any number of realtime processors. The argument to GetScheduler() specifies the index of the realtime processor on which the SMP2 event will be executed. For compatibility with the standard, the argument is optional and defaults to 0. The second step of setting up a statically configured SMP2 schedule is done with the Schedule Editor. As mentioned earlier in this section, SMP2 events are not native EuroSim entry points. Instead, they are executed by SMP2 system tasks. The Schedule Editor automatically defines an SMP2 system task for each realtime processor, much like it does for the action manager. The SMP2 system tasks are named SMP n where n is the index number of the realtime processor. Each time an SMP2 system task is activated, it executes the events that are due before the next call to that SMP2 system task. Those events are executed immediately and as fast as possible. This means that a simulation time event can only ever run as often as its SMP2 system task. It is therefore important to schedule an SMP n task at a frequency that is at least as high as the highest frequency of the simulation time events that have been scheduled for realtime processor n. It is not obligatory to schedule each SMP n task. Only if an SMP2 model adds simulation time events to realtime processor n, then the corresponding SMP n task must be scheduled. Even though it is possible to schedule SMP n tasks in each stage, it is only useful to do so in the executing stage.

294 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 19

Java interface reference

19.1 Introduction

The purpose of the Java interface is to allow EuroSim users to program simulation models in Java. The setup required for the integration of Java models into EuroSim are described in the Section 19.2. Publication of Java model variables, entrypoints and annotations are described in Section 19.3. The Java data types supported by EuroSim are listed in Section 19.5. The Java models are executed by the Java Virtual Machine from Sun. There are a couple of limitations that the user must be aware of.

1. The garbage collector may start at any time and may result in unpredictable execution times of Java models.

2. When a Java entry point is executed, the state of the variables as present in the data dictionary is copied to the Java model, then the Java method is called, followed by a copy of the data from the Java model to the data dictionary. The copying may be quite expensive in terms of execution time if the entry point is from an object that has many sub-objects. The entire tree will be traversed and copied twice.

In the EuroSim installation directory you can find a directory Java with a Java example project, in the src directory. This is a very simple test simulator which shows you a working example. In EuroSim just make a new project and add the model and use the Model Editor to open it.

19.2 Setup procedure

A EuroSim Java model is not quite the same as a normal Java application, there are some differences one should be aware of. Normally one would start a Java application with a main method in some class, in EuroSim however this is not the case. Instead there should be a class “main” that instantiates all the instances of the models:

Listing 19.1: Example of a Java main class import nl.eurosim.model.*; class main { @eurosim(description="Model Instance 1") public model m1 = new model(1, 2, "one");

@eurosim(description="Model Instance 2") public model m2 = new model(3, 4, "two");

@eurosim(description="My New Red Car")

c Airbus Defence and Space 295 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public car c1 = new car("red"); }

In the example above, note the absence of the “main” method, the class itself assumes the task of the absent “main” method. Also note the import nl.eurosim.model.*; statement at the beginning of the example. This statement imports a number of classes associated with the EuroSim Java interface. These classes are necessary when using eurosim annotations or calling EuroSim run-time methods discussed next. It is not necessary to instantiate these classes, or any other class that does not contain an entry point method, in the main class. Access them in the normal way.

19.3 Publication interface

Because of the way Java is supported by EuroSim, it is not possible to see any member variables or entry point methods in the Model Editor. This makes it impossible to add descriptions or give units to these methods and variables like the way it is done with the other supported languages. Using the eurosim annotation, however, it is possible to do the same job in the model code. Information in the annotation is not shown in the Model Editor, but does show up in the EuroSim data dictionary. Member variables and entry point methods may be annotated with an eurosim annotation, for example: @eurosim(description="Calculates distance",unit="[m]"). A variable can have the following annotation fields:

• description: A description of the variable

• unit: The physical unit

• min: The minimum value

• max: The maximum value

• ignore: Boolean flag, if true, the variable or entry point is not published in the data dictionary.

An entry point method, however, can only have the description and ignore annotation. It also must not have any arguments, but must have the void return type. Published data and entry points are placed under the JAVA org node in the EuroSim data dictionary.

Listing 19.2: Example of a Java model class import nl.eurosim.model.*;

class model { @eurosim(description="some variable", unit="m", min="0", max="10") public int var = 2;

@eurosim(description="another variable") public double other = 3.1415;

model(int x, int y, String name) { }

@eurosim(description="this is an entry point") void compute() { double x = var * other; } }

296 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

There are a number of EuroSim run-time methods you can use in your Java model. They are listed in EuroSim Manual pages and in Section 19.4. As all of these methods are static, it is not necessary to make an instance of the appropriate class. Just use the class name itself. For example: if you would like to get the simulator time, you would call the esimGetSimtime() method and use the class that gives this method, i.e., EsimRuntime. Your code would look like this:

Listing 19.3: Example of calling a run-time method import nl.eurosim.model.*; class example { void someMethod() { // Get the simulator time double time = EsimRuntime.esimGetSimtime(); } }

The publication mechanism uses reflection to determine all the fields and methods of the classes. It stores the extra information given by the annotations in the data dictionary. The default initial value is automatically determined. Java source files shall be stored in a hierarchical directory structure reflecting the package hierarchy in the same directory as where the model file referring to these files is stored. When the model is ready to be build the user has to enable the Java capability support. This is done by selecting the “EuroSim Java integration library” option on the Support tab of the Build Options dialog in the Model Editor. It is possible to add class-paths in the usual manner in the Build Options dialog box. Each element must be separated by a colon. You can specify directories with class files or jar files, however, when referring to a jar file the complete name of the jar file should be given, not just the directory the jar file is in. After this the user just has to run the Build All command to compile the model source into a runnable simulator.

19.4 Service interface import nl.eurosim.model.*;

Do not forget to check the ‘EuroSim Java integration library’ option in the Model:Options window of the Model Editor (see Figure 7.5). The Java model interface currently does not cover the full range of run-time functions. This will be improved in future releases. The available functions are listed below. For an explanation of the function please check the C-Fortran-Ada reference.

19.4.0.1 Real-time timing functions package nl.eurosim.model; public class EsimRuntime { ... native public static double esimGetSimtime(); native public static int esimSetSimtime(double simtime); native public static double esimGetWallclocktime(); ... }

c Airbus Defence and Space 297 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

19.4.0.2 Real-time simulation state functions package nl.eurosim.model;

public class EsimRuntime { ... public enum esimState { esimUnconfiguredState(0), esimInitialisingState(1), esimExecutingState(2), esimStandbyState(3), esimStoppingState(4); } public static esimState esimGetState(); public static boolean esimSetState(esimState state) ... }

19.4.0.3 Real-time task related functions package nl.eurosim.model;

public class EsimRuntime { ... native public static int esimDisableTask(String taskName); native public static int esimEnableTask(String taskName); native public static double esimGetTaskrate(); native public static String esimGetTaskname(); ... }

19.4.0.4 Event functions package nl.eurosim.model;

public class EsimRuntime { ... native public static int esimEventRaise(String eventName, byte[] data); native public static int esimEventData(byte[] data); ... }

19.4.0.5 Real-time clock functions package nl.eurosim.model;

public class EsimRuntime { ... native public static int esimSetSpeed(double speed); native public static double esimGetSpeed(); native public static int esimGetRealtime(); native public static int esimSetRealtime(int on); ... }

298 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

19.4.0.6 Real-time recording functions package nl.eurosim.model; public class EsimRuntime { ... native public static int esimGetRecordingState(); native public static int esimSetRecordingState(int on); ... }

19.4.0.7 Real-time reporting functions package nl.eurosim.model; public class EsimRuntime { ... native public static void esimMessage(String msg); native public static void esimWarning(String msg); native public static void esimError(String msg); native public static void esimFatal(String msg); ... }

19.4.0.8 Auxiliary functions package nl.eurosim.model; public class EsimRuntime { ... native public static void esimAbortNow(); native public static String esimVersion(); ... }

19.4.0.9 Trace functions package nl.eurosim.model; public class EsimRuntime { ... native public static void esimTracePause(); native public static void esimTraceResume(); native public static void esimTraceResume(unsigned type_mask,unsigned proc_mask); ... }

19.5 Supported data types

The EuroSim Java model library supports (arrays of) the following Java data types. The table below show how they are mapped to a type in EuroSim:

c Airbus Defence and Space 299 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Java type EuroSim type Description boolean jboolean 8 bit unsigned integer type byte jbyte 8 bit signed integer type char jchar 16 bit unsigned integer type short jshort 16 bit signed integer type int jint 32 bit signed integer type long jlong 64 bit signed integer type float jfloat 32 bit floating point type double jdouble 64 bit floating point type java.lang.Boolean jboolean 8 bit unsigned integer type java.lang.Byte jbyte 8 bit signed integer type java.lang.Character jchar 16 bit unsigned integer type java.lang.Short jshort 16 bit signed integer type java.lang.Integer jint 32 bit signed integer type java.lang.Long jlong 64 bit signed integer type java.lang.Float jfloat 32 bit floating point type java.lang.Double jdouble 64 bit floating point type java.lang.String char[] string class1 java.math.BigInteger jlong 64 bit signed integer type java.math.BigDecimal jdouble 64 bit floating point type java.util.Date char[] Date/time string in the format yyyy-MM-dd HH:mm:ss.SSS java.util.Calendar char[] Date/time string in the format yyyy-MM-dd HH:mm:ss.SSS Table 19.1: Supported Java data types

EuroSim also supports List<>’s of objects and arrays of object. Objects inside other objects are pub- lished as sub-objects in a hierarchical fashion. Arrays and Lists are published as hierarchies with the individual elements as leaves. Each leaf element is published under the array node with the same name as the parent but with a post-fix in the form index. It is possible to rename array and list elements to a user defined name by implementing the Renamable interface. The Renamable interface class defines one method: public String getEsimId(). The example below demonstrates the use:

Listing 19.4: Example of using the Renamable interface to rename an instance of an object import nl.eurosim.model.*;

public class model_renamed implements Renamable {

@eurosim(ignore=true) String name;

1java.lang.String may contain a Unicode string. EuroSim supports only ASCII (UTF-8) type strings.

300 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

int value;

public model_renamed(String nm, int v) { name = nm; value = v; }

public String getEsimId() { return name; } }

c Airbus Defence and Space 301 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

302 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 20

Matlab Simulink interface reference

20.1 Introduction

Matlab and in particular its graphical modeling component Simulink is a popular modeling environment from the Mathworks corporation. Simulink is often the tool of choice for a control engineer to develop the control algorithms in a so called Engineering Simulator. Such simulator models the behavior of a control system and its interaction with its physical environment. The engineering simulator thus combines the control laws and the simulation of the system it controls in the Simulink environment. In subsequent steps in the project life-cycle more fidelity is added by encapsulating the control laws in executable software running on a control computer and interfacing this to a Realtime simulation running the models of the system actuators, sensors and environment. The latter simulator is then built with EuroSim. The actuators and sensors equipment modeled in this realtime simulator consist of an IO and a Mathematical (Simulink) component. The IO component models the interface with the control computer at the electrical level and associated equipment behavior such as warmup delays and mode behavior. The Mathematical component models the physics part of the equipment and preferably is reused from the engineering simulator. Figure 20.1 illustrates the above described transition and the reuse of blocks from the engineering simulation in Simulink into the higher fidelity realtime simulator.

Figure 20.1: From Simulink to EuroSim models

The reuse of the models from the engineering simulator in Simulink to the mathematical part of equip- ment models in the realtime simulator is performed via the code generation tools provided by Mat- lab/Simulink. This code generation has evolved over the years into two products that are called Simulink Coder and Embedded Coder. The main difference between these tools is that Simulink coder is focused

c Airbus Defence and Space 303 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

on transforming a Simulink simulator into an executable to achieve faster execution. Therefore the for- mat of the generated code does not has to be well readable, nor does the interface has to remain the same over versions of the software because the envisioned user is not interested in the source code but in the executable. The later developed Embedded Coder aims at providing source code that the end-user can integrate into his application, as for instance the control laws in the example above, or the equipment models in the EuroSim simulator. The Embedded Coder has therefore many more tuning options to con- trol the format of the generated code, and the generated code is readable to the end-user. However, this does not imply that the Simulink Coder cannot be used. It is significantly cheaper than the Embedded Coder and therefore usually is the prefered tool. The ThermoMRA example uses the Simulink Coder to generate C code from Simulink models. The simulink models are coming from the simulink engineering simulator provided under ThermoESE in the examples directory. Regardless of the selected Coder, the general process is to transform each equipment model indepen- dently and reintegrate the models in EuroSim via dataflows. In this transformation process the user must select the solver and frequency for each equipment model in EuroSim. Please be aware that thus in Eu- roSim the solver thus does not run over the complete state vector of all models, but is included in each separate model and only integrates over the state vector of that model. And the stepping is of course a fixed step because your are going from the simulink environment where you like to go as fast as possible to a simulator that is oriented towards interfacing with the real world (hardware/human in the loop), thus running realtime. Additionally, seperating out models provides in EuroSim the ability to distribute the model (instances) over processors and execute models at different frequencies to be able to execute the entire simulation realtime. Over the years EuroSim has adapted to the available code generation capabilities provided with Matlab. At this point different solutions exist, of which the user has to choose the one that is most beneficial to his program and which also relates to the APIs in EuroSim that the user has selected. The first approach, fitting with the classic approach using the C code parser and integration via parameter exchanges, is the use of the MOSAIC tool from the National Aerospace Laboratory (NLR). The alternative approach generally used with the CPP API is to directly integrate the generated code in the equipment models using a function call. This chapter first provides general advice on issues to consider when integrating Matlab/Simulink code into EuroSim, including what kind of information is needed in an Interface Control Document (ICD) that controls the transfer of the models from the engineering simulator to the EuroSim realtime simulator. Thereafter an elaboration on the use of MOSAIC is provided, followed by a detailed introduction into the direct integration of code from Simulink Coder, including the verification of the models against sample data obtained from the engineering simulator in Simulink.

20.2 General considerations

20.2.1 Coder type As mentioned, Simulink has two tools for generating code out of your models. The type of coder can be selected under Configuration Parameters / Code Generation / System target file. Select ‘grt.tlc’ for the Simulink Coder and ‘ert.tlc’ for the Embedded Coder. It is adviceable to set the language to ‘C’, there is not much benefit to C++ for this kind of code and the EuroSim parser can automatically derive type information from C code.

20.2.2 Parameters Both Coders will create a parameter struct. Autogenerated parameters that you did not intend to tune can be added by the coder to this struct. In order to prevent this to happen, set the default behaviour of to ‘Inlined’ (which can be found at Configuration Parameters / Optimization / Signals and Parameters / De- fault parameter behaviour) and explictely define each parameter on the workspace as ‘SimulinkGlobal’. See the ThermoESE example for details.

304 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

20.2.3 Reusable functions A choice can be made in how models in Simulink are used and how code is generated from them with respect to multiple instances. Generally the approach chosen is to have a library of models in Simulink and make instances of when incorporated in a system simulation. For example a Satellite has multiple reactions wheels, all of the same type. The code generation in this case should be done from the library model. The Simulink simulation should already be set up in this manner. In both Simulink and EuroSim multiple instances of the equipment should then be created, each with its own instance of the generated physics models. Note that for this approach the generated code used in EuroSim should be re-entrant as multiple models will call the physics model, quite often in parallel. The alternative is to generate code for every instance in Simulink, however that creates many copies of the model and the risk of using different versions of the physics model in one simulator. This setting can be found under Configuration Parameters / Code Generation / Interface / Code interface packaging.

20.2.4 Memory allocation The allocation of memory for the generated source code of a Simulink model must be performed by Eu- roSim for two reasons. First to assure that real-time performance is feasible, EuroSim preallocates and locks heap memory to avoid the generation of page faults during the simulation. If the model allocates memory through standard malloc, such page faults may occur and cause jitter in the realtime behavior. Second, to allow EuroSim tools access to the variables, these variables must be publishable in the dictio- nary. Of course a static variable could be found by the EuroSim parser, but such construction would be difficult in the case of multiple instances of a model. In some cases and under some settings the coder might use malloc, which would render your model useless. One can simply postprocess the generated code and replace all malloc’s by esimMalloc which is defined in esim.h. A similar step must be done for free and esimFree. The ThermoESE example shows how a PostCodeGenCommand can be used to automate this step.

20.2.5 Solver type The selection of the integration method and integration step size when generating code needs special attention. In EuroSim each model must have its integration method included, unlike Matlab where the solver is applied over the complete state vector. In EuroSim the models can run on different frequencies and in parallel, end its included integration will compute the next state of that model. The integration step-size determines the frequency that a model must be scheduled on in the EuroSim schedule and the selection is affected by the selected integration method as lower order methods need smaller timesteps. Selection of a higher order method such as Runge Kutta 4 is popular in Simulink, but of course that consumes more processing power while your timestep may be determined by other factors. You can start with for instance a Forward Euler integration method, the simplest solution and see from there the effects. This setting can be found under Configuration Parameters / Solver / Solver options.

20.3 MOSAIC integration

The Mosaic tool, produced by the National Aerospace Laboratory (NLR) can work will all code gener- ation features from Matlab, thus the old Realtime Workshop that has been turned into Simulink Coder, as well as the Embedded Coder. The generated model is either a native EuroSim C model, or an SMP2 model. Mosaic generates a wrapper at the EuroSim dictionary level, thus the model will immediately show its interface in terms of variables and entrypoints in the dictionary. In EuroSim the solution of Model Descriptions and Parameter Exchanges (classical model integration) can be used to reintegrate the various equipment models with the DKE model. For further information on the the use of MOSAIC the reader is referred to the National Aerospace Lab- oratory (NLR). This includes which version of Matlab/Simulink is to be used as changes in Simulink and the Coders affect the working of MOSAIC. The user manual of MOSAIC provides the details on how to

c Airbus Defence and Space 305 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

tailor the Simulink environment and code generation settings for model transformation to EuroSim with the MOSAIC tool. The MOSAIC tool is independent from EuroSim. To obtain a MOSAIC installation and license the reader is referred to the National Aerospace Laboratory information email address for MOSAIC: [email protected].

20.4 Direct Integration

Rather then depending on the MOSAIC tool for transformation of the model, it is also possible to directly integrate the generated code at the level of function calls to the API in the generated model. With the advent of Simulink/Embedded Coder the interface of the generated code is quite suitable and easily usable in EuroSim. Additionally conversion tools for Matlab data files to EuroSim stimuli files are available with EuroSim that can be used in verifying that the generated model code is performing similar to the Simulink models in the Simulink based Engineering Simulator. For EuroSim Mk7.1 we currently advice to use the Simulink Coder in Matlab to generate C code (setting Configuration Parameters / Code Generation / Language). The primary reason is that the generated code uses C-type structs (also for C++) which are easiest picked up by the EuroSim C parser and can then be reused in the C++ interface via the CPP API. The EuroSim team uses this approach in EuroSim Mk7.1 in combination with the Model Reuse Architecture solution incorporated in the CPP API. It is the responsibility of the user to tailor the settings in the Matlab environment to generated code suit- able for realtime simulation. This also applies to the tailoring of the code generator, which should be set such that it generates an API compliant with the memory allocation and multiple instances consideration in section 20.2. As starting point though EuroSim comes with the ThermoESE example provided with EuroSim to show how the Simulink Coder can be configured to generate code which can be used for EuroSim integration. Please note the following:

• Each model is defined inside a Simulink library. Each model is instantiated in its own model object and is accompanied by a Matlab scripts which loads parameter objects into the workspace (see section 20.2).

• Each model sets the default parameter behaviour to ‘Inlined’ (see section 20.2).

• Each model sets the coder type to Simulink coder (see section 20.2).

• Each model sets the interface to ‘Reusable function’ (see section 20.2).

• Each model has a PostCodeGenCommand defined (see EsimPostCodeGenCommand.m, which prepends a few lines to the main model code to redirect memory allocation to the EuroSim manager and appends a few lines that forces the EuroSim parser to collect type information in the dictionary. These prepended and appended fragments are only active when the source code is compiled in EuroSim context due to its enclosure with #define __eurosim__. The prepend- ing and appending does not alter the original model code and the file remains fully usable outside EuroSim context.

• Each model packs the coder output to a zipfile, see Configuration Parameters / Code Generation / Package code and artifacts. The generated zipfile contains all the code needed for integration in EuroSim.

• The Simulator.mdl and Units.mdl model instantiate the models in a Simulink simulation.

• The file build_all.m subsequently builds each model.

The ThermoMRA examples contain the actual integration of the coder output of the ThermoESE models into a realtime simulator. Please note the following:

• The generated code is nested under MathModels (these are unpacked zipfile generated by Ther- moESE).

306 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• The shared Matlab code is only include once (originates from the zipfiles).

• The unit models contain pointers to the model, inputs, outputs and parameters structs. In the constructors of the ModelState classes the Math Model’s allocation is called. The pointers are set to the allocated data and subsequently published into the dictionary (in ModelData).

• The MODEL_intialize, MODEL_step and MODEL_terminate functions are called from within the unit model.

Generally the above process works fine for models, but we have observer over time some occuurances where some minor adaptation was needed manually. These are listed below. In most cases these are modifications that only need to be made once.

• global variables: The code generated as in the ThermoMRA example, allocates its memory via dynamic memory allocation. In some cases it seemed not to be possible to generate the code in this manner. In this case the coder generates a global variable, for instance for the data. This limits than the number of model instances to one. In all observed cases this happened in the dynamics and environment model and typically there is only one instance of such model hence it did not create a major issue. When the model is coded in this manner, the code generation will include a file _data.c which can be integrated as well in the simulator.

• nested structures: When in combination with the global variable the model may include nested structures and the EuroSim C parser then runs into limitations. The observed error was generated on the global realtime model while the EuroSim parser only needs to scan the structures that this model includes, such as inputs, outputs and parameters. The solution was to wrap the specific model declaration fragment with #ifndef __ESIMAPI__ which prevents the EuroSim parser to scan the specific piece of code. Unfortunately this will be overwritten on an update of the model and hence the user should use merge tools like meld to preserve this adapted fragment.

• name clashes: Because each equipment model is transformed individually to generated code, the Coder may generate code that occurs with every model. The resulting code may contain therefore some support functions with a standard name and these will clash when building a simulator that integrates multiple of these generated models. This was observed with older versions of Simulink (pre 2019) specifically in the fileMODEL_private.h file. The problem was easily resolved by making these functions static. Once adapted this file usually does not change.

• include prevention: Another issue specifically encountered when using an older version is that the generated code pulled in too many types and thereby require fields that EuroSim can not handle. We have seen this occur in the data files, generated as MODEL_data.h. In observed applications it was found that the include of the _private.h was the problem and could simply be commented out.

• library defines: The final problem is related to the Matlab library files, found in the R20XXx directory (e.g. R2019a), and needed by EuroSim when building the simulator. These files may require some defines that ideally are set in the EuroSim build options but the naming is to generic and will cause conflicts that are hard to find. In such case we advice to modify the source files. This has been observed in particular with a file simstruc.h and was solved by adding #define RT at the start of the file, directly after the #define __SIMSTRUC__.

• asynchronous communication: Another define that can be set is MULTITASKING. This flag ensures extra buffering to avoid data corruption in case of asynchronous communication between a realtime and non realtime part. In our observation we have not seen a need to define this MULTITASKING flag as EuroSim based simulations nominally execute the mathematical models in a single entrypoint call and have a controlled synchronization of data with its environment that is explicitly scheduled. The user however is advised to consider defining this variable similar to the RT flag for his specific usage of the generated mathematical models in his simulator.

c Airbus Defence and Space 307 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The manual modifications mentioned above are not required repeatedly if solved in the indicated way. The changes are rarely in the header files or library files, rather the updates are in the MODEL. h and MODEL.c c files. We therefore have not provided an import script or tool, but for a project it will be easy to create an import script that performs the necessary changes. The user will know when things have changed outside what was foreseen as then the compilation and linking of the simulator will likely fail. The process for transformation of simulink model to C model as described in this paragraph is verified with R2019a, but should work for subsequent versions as long as the Coder does not generate a different interface. If the latter is the case it generally requires some minor changes in the PostCodeGenCom- mand,m script that is included with the ThermoESE example.

20.5 Model verification

This section applies to directly integrated model code, however similar solutions can also be constructed when using MOSAIC. Please contact the mosaic helpdesk of the National Aerospace Laboratory for advice in such case. The goal in verification of the generated model is to check if the model after code generation and incor- poration in EuroSim still behaves as in the Engineering Simulator in Simulink. This behavior could be compromised for instance when for a specific model a different integration method or integration stepsize is selected due to the constraints of the realtime simulator, or a parameter is not identified and properly set, or a code generation parameter is not properly tailored. The verification capability has proven quite valuable to catch errors in an isolated setup at an early stage. The verification approach for the generated models is to record input and output data of a model running in a Matlab simulation, transform this data to EuroSim stimuli files and then plot both the computed response of the generated model with the converted reference output in a single plot. Generating inputs for these plots involves making a dedicated simulator which instantiates each model, excites them with the stimuli and records the response to a file. The Embedded Coder creates a file ert_main.c, which can be used as a template for a C based simulator. The Math example contains such files for a simple model. The ThermoMRA example builds a C++ based simulator on code generated by the Simulink Coder.

20.5.1 Generating stimuli files Simulink is able to store simulation data to a HDF5 file format, which can be used as input and reference for this dedicated simulator. Note, make sure that the data is stored in ”Array” format and not in ”Time- Series” format and that you select (at least) MAT file format 7.3. The m2r utility, included in the EuroSim distribution, is then able to generate EuroSim stimuli from such files. The EuroSim m2r tool uses the hdf5dump tool included in the hdf5 tools package on Linux distributions to extract this data in ASCII format. Subsequently the utility then converts this ASCII output of hdf5 to EuroSim ASCII recording format and glues a user supplied header in front. In its final step m2r then uses a2r to process that ASCII file into a EuroSim stimuli file. The header file that m2r glues to the ASCII data must be manually written by the user, or alternatively can be created by defining a EuroSim recorder for the variables that are input into the to be verified model (the inputs and reference output). This header defines which variables are contained in the simulator by referring to their path in the dictionary. An example can be found in the ThermoMRA example provided with the EuroSim release. The following line illustrates the use of the m2r tool.

m2r -o outputfile -i headerfile -m formatspec -d debuglog matlabfile

where: outputfile: This is the desired name of the stimulation file headerfile: This is the user written headerfile that identifies

308 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

the variables contained in the data formatspec: The conversion in m2r uses the h5dump tool with %.15e format specifier to achieve a high precision. This can be adjusted by the user with the -m argument as input to m2r. The m2r utility passed the -m argument string formatspec as -m argument to h5dump to allow the user to adjust the h5dump precision. Note that m2r is a script itself the user can if needed even adapt the script. debuglog : Because m2r generates a file that is input to a2r the cause of a reported error is not obvious without knowing the intermediate result that was input to a2r. The -d option supports the copying of the intermediate result to the file with filename debuglog. This intermediate file is an ASCII text file that contains the glued header and the data in readable format. matlabfile: The .mat file that contains the data that is to be converted The following is an example of a EuroSim compliant headerfile: # EuroSim recording file Mission: ../Math/rts.mdl SimTime: /simulation_time TimeFormat: relative ByteOrder: 1234 Number of variables: 5 /simulation_time: struct timespec /MathModels/TDE/Inputs.heat1: double /MathModels/TDE/Inputs.heat2: double /MathModels/TDE/Inputs.heat3: double /MathModels/TDE/Inputs.heat4: double The following mdl script can feed this data into the simulator: # # definition of action "TDE Input Stimulus" # action "TDE Input Stimulus" [type="Stimulus",bitmap="stimuli_stub", actionmgr=0,index=3,show+active+Executing, 176 0, 0 ] action_begin #generated script stimuli "soft" "Data/TdeInputs.stim" :CPP:MathModels:TDE:Inputs.heat1, :CPP:MathModels:TDE:Inputs.heat2, :CPP:MathModels:TDE:Inputs.heat3, :CPP:MathModels:TDE:Inputs.heat4 action_end when ( freq(40) )

Note that m2r is a relatively easy shell script, the user can change it if needed. It uses the mat2rec and a2r programs. The tool has been used in a large program and can handle various types such as unsigned char, int, unsigned int, float and double, though double is the most often used type in typical stimuli files. The ThermoMRA example shows how a script can be build to automate this process. This allows the user to rapidly iterate and verify model.

c Airbus Defence and Space 309 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Because the m2r tool is a script that calls other programs, the error notifications may not be clear as they depend on the content of intermediate files. In case of errors, it is usaually quite helpful to use the -d option to log the intermediate data to file. As an example, an error that happened in projects was that the data from mat2rec did not have enough values per line in comparison with the header. This resulted in the following errors:

Building Stimulus file....fss.stim a2r -F -o fss.stim /tmp/tmp.KtEcMMa9nc a2r warning: datadict ’/tmp/../../rts.Linux/rts.dict’ not found a2r error: line 14: unexpected end of line for double a2r warning: line 14 not complete, stopped for /MathModels/FSS/test/FSS_test.c/inputs.spacecraftAttQuaternion Done!

20.5.2 Recording data At this point, the stimuli files are generated and used as input in the dedicated verification simulator. By adding a recording to the mdl script, the outputs can be written to a file:

# # definition of action "TDE Recorder" # action "TDE Recorder" [type="Recorder",bitmap="recording_stub", actionmgr=0,index=1,show+active+Executing, 0 0, 0 ] action_begin #generated script record "Tde.rec" :CPP:MathModels:TDE:Outputs.temp1, :CPP:MathModels:TDE:Outputs.temp2, :CPP:MathModels:TDE:Outputs.temp3, :CPP:MathModels:TDE:Outputs.temp4 action_end when ( freq(40) )

Note that the outputs of the simulation are also dependent on the parameters during simulation. This can be achieved by setting an initial conditions file for the EuroSim simulator:

# EuroSim initial condition file # dict = rts.Linux/rts.dict # format = ascii # contains only explicitly set values #

InitialCondition: /CPP/MathModels/TDE/Parameters.capacity = "{10,15,25,30}" InitialCondition: /CPP/MathModels/TDE/Parameters.emisFac = "0.5" InitialCondition: /CPP/MathModels/TDE/Parameters.condFac = "1.5" InitialCondition: /CPP/MathModels/TDE/Parameters.initialtemp = "{120,120,120,120}"

The ThermoMRA example shows how this is done for multiple models. An important feature in this example is that the actual Simulink outputs are also fed to the model and recorded from there. This is convenient for two separate reasons. Firstly, it allows all data to be recorded in the same format, which makes its easy to postprocess (see next section). Moreover, it prevents a timestep delay to occur between the Simulink and EuroSim output, which would make verification very hard. On the downside, users may be surprised to see that the first step in the recorded output is zero.

310 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

20.5.3 Verifying the output A convenient approach is to first use MMI plots in the Simulation Controller to assess if the computed data matches the reference output before evaluating these with the TestAnalyzer. A convenient plotting approach in these MMIs is to use the normal line with a specific color for the computed data and diamond symbols instead of a line for the reference data. This way differences can be easily spotted as the lines and diamonds should overlay. The online displayed graphs are not a final verdict however as the sampling frequency is normally 5 Hz. If the graphs in the Simulation Controller match, the user should still make recordings of the variables to file such that the plots can be displayed in the TestAnalyzer as this data can be sampled at much higher frequency. Again, the ThermoMRA example contains an example plot file for the TestAnalyzer.

20.5.4 Analyzing recordings in Matlab In the context of Matlab/Simulink models there are many users who prefer to process the data from a EuroSim simulator in Matlab. A Matlab Script has been contributed which can convert EuroSim binary recordings to Matlab. The script is provided with the ThermoESE example in the ”src” directory of the EuroSim distribution where also the EuroSim post generation model export script can be found. Note that the script was developed for internal use and has been kindly contributed to EuroSim. Some improvements are planned by EuroSim support to improve error handling and usage documentation in the near future. Users that improve the script are also asked to sahre their improvements to the EuroSim support desk for integration in the EuroSim baseline. Some comments from the developer to assist users can be found below:

• A brief online help is included, (type help readRecorderFile in Matlab)

• The function is capable of handling nested structures and arrays. All array dimensions are shifted to the end (thus a[0].b1/c[2] in C becomes a.b.c(1, 2, 3) in Matlab

• You can read entire arrays or individual elements. If you record individual elements in EuroSim, Matlab will allocate an array that is large enough to contain all elements and will initialise the members with NaN. Thus if you record a[1] and a[3] you get [ NaN, a(2), NaN, a(4) ] in Matlab

• EuroSim can create a tree structure for variables, which allows to have two tree leaves with the same name, thus a/b/x and c/d/x. The Matlab function does not handle this at the moment. Thus in this example you end up with a conflict as in Matlab they both would be x.

c Airbus Defence and Space 311 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

312 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 21

Calibration Library reference

21.1 Introduction

This chapter provides details on the Calibration Library. The Callibration library provides an API that allows the user to callibrate values based on a calibration curve that has been defined using the Calibration Editor (Chapter 10). The calibration library API is typically used from the model code that interfaces with the external hard- ware such as electrical front-ends. Through the API the user selects which calibration curve to use by refering to the calibration curve name. This name must refer to a calibration curve that is enclosed in a loaded calibration file, which can be enforced either by including the file in the ModelEditor or by adding it to the Input Files tab of the simulation controller (which means it is referenced from the .sim file). Using the calibration function, the user can then apply the selected curve to an input value in order to get the calibrated value in return.

21.2 Application Programmers Interface

The API of the library has the following synopsis:

#include const EsimCalibration_t *esimCalibrationLookup(const char *name);

EsimCalStatus_t esimCalibrate(const EsimCalibration_t *cal, double in, double *out); const char *esimCalibrationErrorString(EsimCalStatus_t stat);

The esimCalibrationLookup function looks up the calibration curve with the given name in the list of loaded calibration files, as mentioned in the Simulation Controller. The returned value is a calibration curve handle that can then be used in esimCalibrate as parameter to perform the actual calibration. The input value in esimCalibrate is then calibrated into the output value out. The return code of the function esimCalibrate indicates success or failure of the calibration and can be converted to an error string with the function esimCalibrationErrorString. The following error status may occur:

• esimCalibrationErrorString always returns an error string. If you pass it an unknown status value, the string contains ”Unknown error occurred during calibration”. • ESIM_CAL_OK: Calibration succeeded, no error. • ESIM_CAL_LOOKUP_FAILED: Lookup calibration failed, lookup value was not in the lookup table.

c Airbus Defence and Space 313 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• ESIM_CAL_INPUT_TOO_SMALL: Input value below allowed minimum.

• ESIM_CAL_INPUT_TOO_LARGE: Input value above allowed maximum.

Beware that esimCalibrationLookup will return NULL if the calibration curve with the given name does not exist, thus allways check this return value for a NULL before passing the handle to esimCalibrate.

314 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 22

PUS library reference

22.1 Introduction

The Packet Utilisation Standard is defined by the European Space Agency to operate spacecraft. It is defined in the ECSS document Telemetry and Telecommand Packet Utilization: ECSS-E-70-41A, (January 2003). The PUS standard completes the protocols defined by the CCSDS packet standard and the ESA ECSS-E-50 standard for the transport of telemetry and telecommand data with defining the application level interface between ground and space. The EuroSim PUS library provides a C function oriented interface to encode and decode the PUS packets. The PUS defines a set of standard monitoring and control services expressed in terms of:

• The operational concept that determines the requirements,

• The service model (i.e. how the on-board Application Process which hosts the service should behave) and,

• The structure and semantics of the associated telemetry and telecommand packets.

The typical structure of a PUS packet is a primary and secondary header with essential fields to define the routing and purpose of the packet and size of the payload, followed by a checksum. The purpose is expressed using a service and subservice identifier. Other bits are defining versions and required handling. The packet is big endian coded and allows the packet designer to pack data efficiently with the minimum number of bits.

Figure 22.1: PUS Packet Headers

c Airbus Defence and Space 315 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 22.2: PUS Data Field Headers

The PUS library contains the functions needed to pack and unpack PUS packets. It currently only supports little endian machines (contact the helpdesk is you need it to work on a Big Endian system). To use the library, the model developer can enable PUS support as a build option in the ModelEditor.

22.2 Application Programmers Interface

The PUS library provides an interface for encoding packets and decoding packets. Note that PUS pack- ets are big endian encoded and the PUS library is intended for usage on little endian machines (where bitfields are not an easy solution because the offsets are little endian interpreted). The interface supports the encoding and decoding of the header, the data payload and the insertion and checking of the check- sum. The design of the interface is to pass a bitoffset which contains the bit offset from the start of the packet on which a function is to operate. The function will update the bit offset to the next field after it performed its operation on the indicated bit offset. The following subsections describe the API content. De detailed synopsis can be found in the manual pages, which are also bundled in the ICD provided with the EuroSim documentation.

22.2.1 Packet Header functions The Packet Header functions allow the encoding and decoding of both the 48 bits Packet Header which provides the ability to route the date to its destination, as well as the Data Header which defines the purpose and additional data. Following table shows the function and their service. The details can be obtained from the manual pages (type man 3 functionname on commandline) or the see the EuroSim ICD documentation).

Function Description esimPus(Decode—Encode)PacketHeader Extract/Pack the entire pus packet header from/into the packet in one call esimPus[Decode—Encode]PacketID Extract/Pack the packet id from/into the packet esimPusDecode—EncodePacketSequenceControl Extract/Pack the sequence control parameters id from/into the packet esimPusDecode—EncodeTCPacketDataFieldHeader Extract/Pack the parameters from/into the DataField Header in a telecommand packet esimPusDecode—EncodeTMPacketDataFieldHeader Extract/Pack the parameters from/into the DataField Header in a telemetry packet

316 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Function Description esimPusEncodeTCPacketHeaderWithDefaults Pack the parameters from the DataField Header in a telecommand packet with default arguments esimPusEncodeTMPacketHeaderWithDefaults Pack the parameters from the DataField Header in a telemetry packet with default arguments

22.2.2 Data Field functions The data field functions support the encoding and decoding of the PUS data field using the PTC and PFC format specifiers defined in the format specifiers section of this chapter. The detailed function synopsis can be obtained from the manual pages (type man 3 functionname on commandline) or the see the EuroSim ICD documentation).

Function Description esimPusTMPacketDataOffset Compute the bit offset to the start of the data fields in a telecommand packet. This value must be passed to the bitoffset in the first data field encodding/de- coding function esimPusTMPacketDataOffset— Compute the bit offset to the start of the data fields in a telemetry packet. This value must be passed to the bitoffset in the first data field encodding/decoding function esimPusIntegerDecode—Encode Extract/Pack an integer value from/into the packet using the PTC/PFC format specifiers esimPusUIntegerDecode—Encode Extract/Pack an unsigned integer value from/into the packet using the PTC/PFC format specifiers esimPusLongLongDecode—Encode Extract/Pack a 64 bit integer value from/into the packet using the PTC/PFC format specifiers esimPusULongLongDecode—Encode Extract/Pack a 64 bit unsigned integer value from/into the packet using the PTC/PFC format specifiers esimPusDoubleDecode—Encode Extract/Pack an double floating point value from/into the packet using the PTC/PFC format specifiers esimPusOctetStrDecode—Encode Extract/Pack an octet string value from/into the packet using the PTC/PFC format specifiers esimPusBitStrDecode—Encode Extract/Pack a bit string vanlue from/into the packet using the PTC/PFC format specifiers esimPusUNIXTimeDecode—Encode Extract/Pack a unix time value from/into the packet using the PTC/PFC format specifiers esimPusStrLen Return the length of the string field in the packet

22.2.3 Checksum functions The checksum functions support inserting a Checksum, either based on CRC16-CCITT or on ISO. Their are three functions, an Insert variant computes the checksum and puts it at the provided bitoffset in the packet. A Check variant can do the reverse and verify the checksum in a given packet. Finally the Generate variant is a convenience function that computes the checksum and returns it as function result. The base function requires a parameter to identify which checsum math (CRC-16, ISO) applies,

c Airbus Defence and Space 317 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

convenience functions have this specification in the function name. The detailed function synopsis can be obtained from the manual pages (type man 3 functionname on commandline) or the see the EuroSim ICD documentation).

Function Description esimPusChecksumInsert Insert checksum in the packet according to the method provided as argument esimPusChecksumCheck Check the checksum for the packet according to the method provided as argument esimPusChecksumGenerate Return a checksum for the packet according to the method provided as argument esimPusChecksumCrcInsert Insert checksum in the packet using CRC16-CCITT esimPusChecksumCrcCheck Check the checksum for the packet using CRC16- CCITT esimPusChecksumCrcGenerate Return a checksum for the packet using CRC16- CCITT esimPusChecksumIsoInsert Insert checksum in the packet using ISO checksum esimPusChecksumIsoCheck Check the checksum for the packet using ISO check- sum esimPusChecksumIsoGenerate Return a checksum for the packet using ISO check- sum

22.2.4 Utility functions The utility functions are convenience functions that can help the user to identify the size and type ar- guments given the PTC/PFC arguments. Usage of these functions is normally not needed for packing and unpacking. The detailed function synopsis can be obtained from the manual pages (type man 3 functionname on commandline) or the see the EuroSim ICD documentation).

Function Description esimPusGetBooleanSize Return the length of the type defined by PFC esimPusGetEnumeratedSize Return the length of the type defined by PFC esimPusGetUnsIntSize Return the length of the type defined by PFC esimPusGetIntSize Return the length of the type defined by PFC esimPusGetRealSize Return the length of the type defined by PFC esimPusGetOctetStringSize Return the length of the type defined by PFC esimPusGetAbsTimeSize Return the length of the type defined by PFC esimPusGetRelTimeSize Return the length of the type defined by PFC esimPusGetBitSize Return the length of the type defined by PFC esimPusIsInteger Return if the PTC argument defines an integer type esimPusIsDouble Return if the PTC argument defines a double type esimPusIsOctetStr Return if the PTC argument defines an octest stream type esimPusIsBitStr Return if the PTC argument defines a bitstream type

318 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Function Description esimPusIsTime Return if the PTC argument defines a time type esimPusIsGood Return if the PTC/PFC are valid numbers

22.3 PUS type specifiers

Extraction and packing of data in PUS packets is based on the parameter code, which exist of a parameter type code (PTC) and a parmater format code (PFC). Following table shows what these type codes define (based on PUS standard from 2003)

PTC PFC Type 1 0 Boolean 2 1-16,24,32 Enumerated (length in bits) 3 Unsigned Integer 0-12 PFC+4 bits 13 24 bits 14 32 bits 15 48 bits 16 64 bits 4 Signed Integer 0-12 PFC+4 bits signed 13 24 bits signed 14 32 bits signed 15 48 bits signed 16 64 bits signed 5 Real 1 32 bits IEEE 2 64 bits IEEE 3 32 bits MIL 4 48 bits MIL 6 Bit string 0 variable, int length+data >0 length in bits 7 Octet string 0 variable, int length+data >0 length in bits 8 Char string 0 variable, int length+data >0 fixed length 9 Absolute Time Parameter 0 explitic CUC or CDS with P-Field

c Airbus Defence and Space 319 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

PTC PFC Type 1 2 octets day CDS without usec field 2 2 octets day CDS with usec field 3-18 CUC with ((PFC+1)/4 course time+((PFC+1) mod 4) fine time, no P-Field 10 Relative Time Parameter 0 explitic CUC or CDS with P-Field 3-16 CUC with ((PFC+3)/4 course time+((PFC+3) mod 4) fine time, no P-Field 11 0 Deduced parameter

22.4 Example

Following source code snippet is an example of the usage of the library

int32_t bitoffset=(packetlength+7-2)*8; //output parameter if(!esimPusChecksumCrcCheck(INPUT.tcPacket.bytes,&bitoffset)) return;

//decode the CCSDS Packet Header uint8_t versionnr; uint8_t type; //TM=0 TC=1 uint8_t datafieldheaderflags; int32_t apid; //7 bits process id and 4 bit packet category uint8_t sequenceflags; uint32_t sequencecount; uint16_t packetlength;

esimPusDecodePacketHeader( INPUT.tcPacket.bytes, &versionnr, &type, &datafieldheaderflags, &apid, &sequenceflags, &sequencecount, &packetlength);

uint8_t secondaryheaderflag; uint8_t crcflags=0; //0=no crc,1=crc uint8_t ackflags; int32_t servicetype; int32_t servicesubtype;

esimPusDecodeTCPacketDataFieldHeader( &INPUT.tcPacket.bytes[6], &secondaryheaderflag, &crcflags, &ackflags,

320 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

&servicetype, &servicesubtype); esimPusTCPacketDataOffset(&bitoffset); uint32_t srcid, modeid,actpar; esimPusUIntegerDecode(&srcid,3,4,aPacket.bytes,&bitoffset); esimPusUIntegerDecode(&modeid,3,12,aPacket.bytes,&bitoffset); esimPusUIntegerDecode(&actpar,3,12,aPacket.bytes,&bitoffset);

c Airbus Defence and Space 321 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

322 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part IV

Scripting Reference Guide

c Airbus Defence and Space 323

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 23

Mission Definition Language reference

The Mission Definition Language MDL is a simple yet versatile language for real-time simulation script- ing. It allows users to write simulator control scripts in a “C-type”, or—alternatively—in a limited “free-text” language. The language has all the facilities one can expect of a programming language, including if-statements, for-loops, global and local variables. Besides that, the user has full access to the variables in the EuroSim data dictionary. Direct simulation control commands can also be used in the language.

This appendix first starts with a primer in MDL, followed by a number of sections providing detailed information on the various language elements. A description of the built-in functions and a concise formal definition of the MDL language can be found in the last two sections of this appendix.

Note that the majority of MDL scripts in EuroSim will/can be made via the GUIs, for which the user doesn’t need to know much about the MDL language. So this appendix is primarily intended for EuroSim users who want to do ‘advanced’ things, not supported via the predefined GUIs. Throughout this section, it is assumed that the reader has programming experience.

23.1 MDL primer

An MDL script (or “scenario”) is normally created with EuroSim’s Simulation Controller and interpreted during simulation by EuroSim’s Action Manager (ACTION_MGR). An MDL script contains (amongst other things) a collection of actions. An MDL action consists of four parts:

1. Action name.

2. Action attributes (optional).

3. Action body.

4. Action condition (optional).

Each action in the MDL script is represented by an icon on the Simulation Controller’s tree or icon view. The four parts of each action can be edited via the Simulation Controller (Section 12.10.3). A simple example which prints a message 10 seconds into the simulation: # # action name and attributes action "Primer" ["description",bitmap="script_stub",show+active+Executing , 50 50, 1] # # action body { print "Hello at t=10"

c Airbus Defence and Space 325 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

} # # action condition when (time() == 10) The action attributes are used to:

• Give a description of the action.

• Manipulate the appearance of the action on the Simulation Controller tree or icon view.

• Set the initial1 status of the action.

The action status can either be active or nonactive. Furthermore, one can specify in which of the four simulation states the action has to be evaluated when active: Initializing, Executing, StandBy or Stopping. EuroSim maintains for each of these states a list of active actions. The action conditions of these actions are checked each time the ACTION_MGR is activated (in that state and normally at the end of each simula- tion step2). The action body is executed by EuroSim when the action condition evaluates true. When the action has no condition part, this never happens; these actions can only be activated manually (by double clicking the action icon on the Simulation Controller scenario tab page).

The MDL script is executed in the real-time part of EuroSim. In order to safeguard the real-time execution of a EuroSim simulator, error conditions within MDL actions are handled in the following way:

1. The execution of the action causing the error condition is suspended.

2. An error message of this event is reported to the Test Controller and the journal log.

3. The specific action is deactivated so the action will not be executed again.

4. The execution of remaining actions in the MDL script is resumed.

Run time error conditions include:

• MDL or data dictionary array bound overflows.

• Errors in MDL math functions or expressions (e.g. sqrt(i) with i<0).

• Errors in action condition frequency specification (e.g. frequency higher than the ACTION_MGR frequency).

• Trying to read stimuli from nonexisting or exhausted stimuli files.

• Observers (which have “read only” access) trying to change the data dictionary variables from actions, apply stimuli or raise events.

• MDL scripts accessing undefined (external) MDL variables or functions.

• MDL scripts trying to execute an undefined action.

An MDL action body consists of statements separated by newlines or by a semicolon. The latter may— however—only be used to separate multiple statements on a single line. MDL is case sensitive. Everything following a ‘#’ sign until end-of-line is considered comment.

MDL is a powerful languages, but remember that it is an interpreted language, running in the real-time part of the simulator. Hence keep your scripts as simple and small as possible. Don’t write large loops and keep computation to a minimum. If you have to do serious programming and/or computation, consider adding an extra sub-model and associated tasks to you model.

1Initial, as this can change during the simulation. 2See Section 11.3.5 for scheduling of the ACTION_MGR.

326 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

23.2 MDL constants, types, variables, operators and expressions

Variable names are made up of letters, underscores and digits. Upper and lower case letters are distinct. MDL has four basic variable types:

• int representing an integer value.

• float representing a floating point value3.

• string representing a character string.

• datetime representing a time value.

Variables which are explicitly declared as one of the above are called ‘static’ variables. Static variables are, in the absence of an initializer, always initialize at zero or the empty string. Variables need not be declared in MDL. Undeclared variables are created automatically the first time they are used as a left hand value in an assignment. These variables are called ‘automatic’ variables. The scope of variables is that of the enclosing action body (or function; see below). By prepending the action or function name, the static variables from other actions and functions can be accessed. Static variables retain their values in between different action or function invocations. Automatic variables are recreated each time their scope is entered and disappear when that scope is left. Automatic type conversions are applied when needed between all the basic types. Constants can be given either in decimal, octal or hexadecimal form, as in ‘C’. Constants are of type int, except when the constant contains a decimal dot or is given in scientific notation (e.g. 3e-9), in which case they’re of type float. A string constant consists of a number of characters between double quotes.

Some examples with MDL variables and constants: action "action1" { int a_variable # a static variable of type int b_variable = "100" # an automatic variable of type string a_variable = b_variable # type conversion from string to int } action "action 2" { string a_variable = "hello" + " world" # an initialised static variable } action "two_externals" { float f = action1:a_variable print f # prints: "100.0000" print action1:a_variable # prints: "100" print "action 2":a_variable # prints: "hello world" } action "externals_from_another_file" { print "common_actions.mdl":action1:b_variable print "common_actions.mdl":"action 2":c_variable } action "showtime" {

3int and float are implemented as C doubles; check the documentation of your platform to see the valid range for that type.

c Airbus Defence and Space 327 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

# NB: No UTC selected datetime t = 5.900 print "time = ",t + 15.2 # prints: "time = 21.1000" }

action "showtimeUTC" { # NB: UTC selection in model options datetime t = 2001-02-24 16:10:05.900 print "time = ",t + 15.2 # prints: "time = 2001-02-24 16:10:21.1000" } Arrays of basic types can be constructed using square brackets. Arrays must have fixed dimensions and type (no automatic arrays). Assignments are between basic types only. action "sum" { int a[10] for (i = 0; i < 10; i = i + 1) a[i] = i

# compute sum of array i = 0; sum = 0 while (i < 10) { sum = sum + a[i]; i = i + 1 } }

MDL has all the usual (C) operators, except for the address operator, which doesn’t exist in MDL. Expo- nentiation is written as 3ˆ4. In addition, the equivalent English words can be used as operators, e.g. and, or, not, less_equal, greater_equal, equals, not_equals, less_than, greater_than, minus, plus, times, pow.

23.3 Control Flow

MDL statements within an action body are executed in order from top to bottom, except as modified by control flow statements. MDL has the usual (C) keywords for control flow: break, continue, do, else, for, if, while, return. There’s no switch-construct (yet), although the words ‘switch’ and ‘case’ are reserved words4. A conditional block (sequence of statements) may be delimited by either curly braces ‘{}’ or by the keywords begin and end. The action body may be delimited by the keywords action_begin and action_end. These latter two keywords may thus not be nested, and help (when used) to find nesting problems, which are then confined to a single action in the MDL script. Below two examples are given, one in C-like syntax, and one in the alternative, free-style syntax. action "looptest2" { j = 0 N = 100

print "" print "# forloop test2, expect loopcount=", N

for (i = 1; i < 10 * N; i = i + 1) { j = j + 1 if (i == N) break; } print "loopcount=", j }

4See Section 23.6 for a complete list of reserved, but unused words.

328 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

# free-style syntax action "looptest5" action_begin N = 3000 k = 0

print "" print "# forloop test5, expect loopcount=", N

for i is 1 to N/10 loop begin for j is 1 to 10 loop begin k is k plus 1 end end

print "loopcount=", k action_end

23.4 Functions

MDL has an extensive set of built-in functions for simulation support: see Section 23.6. It also supports user defined functions. Functions return simple values and can be used freely in MDL expressions. User functions can be defined and used within the action body. Function arguments and return values must be basic types and behave like automatic variables. Within the function body the complete MDL syntax can be used (e.g. to define local variables or other functions). The type of the function arguments and the type returned by the function may vary from invocation to invocation, as is shown in next example. action "my_action" { int i float x error = 0

function sqr(n) { return n * n }

for (i = 0; i < 5; i = i + 1) { # sqr with int if (sqr(i) != i * i) error = error + 1 }

for (x = 0.0; x < 5.0; x = x + 1.0) { # sqr with float if (sqr(x) != x * x) error = error + 1 }

if (!error) print "function test OK" else print "Error !!!" } The scope of the function name is that of the enclosing action. As with variables, one can use a function defined in another action, by prepending that action’s name and a colon (‘:’) to the function’s name. It is also possible to refer to functions in actions in another MDL file by prepending the basename of the MDL file and a colon to the name of the action and the function.

c Airbus Defence and Space 329 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

# simple external function call action "object" { float velocity = 10.0 # static variable function speedup() { velocity = velocity * 2.0; } function slowdown() { velocity = velocity * 0.5; } function current() { return velocity; } }

action "accel" { object:speedup() print "speed=", object:current() # prints: "speed=20.0" }

Warning: because all MDL variables have static storage, recursive function calls may have unexpected results.

23.5 Input/Output and Simulator Control

In MDL, input and output can be done in two ways, each having a particular purpose:

1. Via variables in the simulation model.

2. Via specific built-in commands.

An example of the latter is the print command, already shown in many of the previous examples. It prints the given expression on the Simulation Controller’s message pane and in the simulation log.

MDL provides access to variables in the simulation model via the model’s data dictionary. Array elements are selected using square (C) or round (Fortran) brackets. More dimensional array indexing follows the conventions of the sub-model language. Members of user defined type variables in C sub-models are selected using a dot: action "position" { # print three elements of an array in a Fortran style loop N = 3 for i is 1 to N loop begin print "position(", i, "): ", :source.f:position(i) end }

action "clear" { # clear all elements of an 2-dim. array in a C style loop for (i = 0; i < 10; i = i + 1) for (j = 0; j < 10; j = j + 1) :source.c:matrix[i][j] = 0

# clear a member of a C struct :source.c:vector.xcoord = 0.0 } A combination of both mechanisms is used to stimulate and record certain data dictionary variables with the stimulate or record built-in commands. action "register three" { int n float x

330 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

function f() { x += 1.0 return x }

n++; record "file1" n, f(), :A:B:C:source1.c:work1:local1 record "file3" :A:E:C:source2.c:work4:localUdt record "file2" :A:E:C:source2.c:work4:localUdt[0].count } when (freq(100))

Note that also MDL variables can be recorded; this can be used e.g. for recording a derived variable (derived from one or more data dictionary variables).

From within MDL, the user has full control over the simulator by means of functions like go, freeze, stop, etc. (see Table 23.5) Also, from one action, one can activate other actions but also tasks and entry points within the model.

23.6 MDL Built-in functions and commands

MDL has built-in functions and commands for the following applications:

• Mathematical functions (see Table 23.2).

• Signal processing functions (see Table 23.3).

• Auxiliary functions (see Table 23.4).

• Input, output and control commands (see Table 23.5).

Functions return a value, whereas commands do not. Functions can be used in expressions. The MDL built-in functions all take numerical (or no) arguments. Required arguments are indicated as follows:

func() This function takes no argument. func(x) This function takes one argument. func(x, ...) This function takes one or more arguments.

Arguments may be functions themselves. Non-numerical arguments are automatically converted to nu- merical.

Function Description atan(x) Compute arc tangent of x and return it. Return value will be between −π/2 and π/2. cos(x) Compute cosine of x and return it. x is in radians. exp(x) Compute the x‘th power of e and return it. e is the base of natural logarithms. fabs(x) Compute the absolute value of x and return it. log(x) Compute the natural logarithm of x and return it. If x is less than or equal to 0, a run time error results. sin(x) Compute the sine of x and return it. x is in radians. sqrt(x) Compute the square root of x and return it. If x is less than 0, a run time error results. tan(x) Compute the tangent of x and return it. x is in radians. Table 23.2: Mathematical functions.

c Airbus Defence and Space 331 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Function Description acos(x) Compute the arc cosine of x and return it. Return value will be between 0 and π. If x is not between -1 and 1, a run time error results. asin(x) Compute the arc sine of x and return it. Return value will be between −π/2 and π/2. If x is not between -1 and 1, a run time error results. ceil(x) Rounds up x to the next highest integer and return it. cosh(x) Compute the hyperbolic cosine of x and return it. floor(x) Rounds down x to the next lowest integer and return it. log10(x) Compute the (base 10) logarithm of x and return it. If x is less or equal than 0, a run time error results. sinh(x) Compute the hyperbolic sine of x and return it. tanh(x) Compute the hyperbolic tangent of x and return it. Table 23.2: Mathematical functions.

1 frac(x) 1 sin(x)

0 0

-1 -1 -2 -1 0 1 2 -4 -3 -2 -1 0 1 2 3 4

2 fabs(x) 3 floor(x) 3 ceil(x) 2 2 1 1 1 0 0 0 -1 -1 -1 -2 -2 -3 -3 -2 -3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 -2 -1 0 1 2

Figure 23.1: Some of MDL’s mathematical functions.

Function Description doublet(x) Compute the doublet of x and return it. If x is between 0 and 1 return 1, if x is between 0 and -1 return -1, else return 0. ramp(x) Compute the ramp of x and return it. If x is less than zero return zero, if x is greater than 1 return 1, else return x. jigsaw(x) Compute the jigsaw of x and return it. If x is less than 0 return 0, if x is greater than 1 return 0, else return x. step(x) Compute the step of x and return it. If x is less than 0 return 0, if x is greater than 0 return 1. frac(x) Compute the frac of x and return it. Frac is the remainder of x from its nearest integer value. Table 23.3: Signal processing functions.

332 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

1 doublet(x) 1 jigsaw(x)

0 0

-1 -1 -2 -1 0 1 2 -2 -1 0 1 2

1 step(x) 1 ramp(x)

0 0

-1 -1 -2 -1 0 1 2 -2 -1 0 1 2

Figure 23.2: Some of MDL’s signal processing functions.

By combining (or modulating) the various functions in expressions, many types of signals and if-type functions can be constructed. For example:

• step(x+1)-step(x-1) or doublet(x)*doublet(x) results in the box function which is only 1 in the range [-1, 1], and 0 everywhere else.

• x*step(-x)+x*x*step(x) results in a line for x less than zero and a parabola for x greater than zero.

Function Description catch(x) Reserved for future use. changed(x) Return 1 if x has changed with respect to the previous invocation, else return 0. Typically used in the condition part of an action in combination with data dictionary variables: freq(100) & changed(:model:var) duration() Return the elapsed simulation time (in seconds) that the action has been continuously (i.e. at each activation of the ACTION_MGR) executed. Elapsed time is reset to zero when the action is not executed. This function can be used to have an action run for a certain period of time. eventcount(x) Return number of times event x has been raised in the schedule. Returns -1, if the event name is unknown. format(x,...) Return formatted string, using printf like format specification. E.g. str = format("Hex value=%4x", :model:var) Table 23.4: Auxiliary functions.

c Airbus Defence and Space 333 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Function Description freq(x, y) Use this function to have an action executed at a given frequency with a given offset. The offset argument is optional and defaults to 0 (i.e. no offset). It returns 1 if desired frequency x (in Hertz) is met by internal basic frequency and with the given offset y (in ms), else freq returns 0. The basic frequency is the frequency with which ACTION_MGR is scheduled. Depending on the scheduling table used, this frequency may differ from the scheduler basic frequency. If the basic frequency is not an exact multiple of the desired frequency x the desired frequency will be approximated in the long run. When parsing an action with a freq function, the ACTION_MGR will issue a warning if this is the case (provided x is a constant). getenv(x) Return the string value of shell environment variable x. main cycle() Return the main cycle time of the schedule in seconds. realtime() Return the current real-time mode of the simulator. Returns 1 if scheduler is in real-time mode, or 0 if it is in non-real-time mode. simstate() Return current simulator state as string value, e.g. "standby". Can be used by actions which can execute in different simulator states in expressions like if (simstate() = "executing") count = count + 1 simtime boundary() Return simulation time of last state transition in seconds. time() Return the current simulation time in seconds. wallclock() Return the current wallclock time in seconds. wallclock boundary() Return wallclock time of last state transition in seconds. enable entrypoint(x) Enable entry point x. disable entrypoint(x) Disable entry point x. trace(mode) Pause (mode=off) and Resume (mode=on) the timebar tracing. Only works if tracing was enabled prior to the start of the Simulation. tracemask(typemask processormask) Limit which events are to be traced and for what processor tracing is to be enabled. Table 23.4: Auxiliary functions.

The last table explains the MDL commands. The commands take numerical or string arguments. Contrary to functions, the command arguments are not to be given between parenthesis and commands do not return a value. Hence they cannot be used in expressions.

Command Description abort request abort of the simulator Table 23.5: Input/Output and Control commands (do not return values)

334 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Command Description activate action | task activate an action (i.e. make its state active) or enable a task. Actions from other MDL files may also be used. The action name must be prepended with the MDL file name (basename only). Actions and tasks must be specified as strings:

activate "Inject Error" activate "other.mdl:Enable Power" activate "task:Thruster"

deactivate action | deactivate an action or disable a task. Actions from other MDL task files may also be used. The action name must be prepended with the MDL file name (basename only). Actions and tasks must be specified as strings:

deactivate "Inject error" deactivate "other.mdl:Enable Power" deactivate "task:Thruster"

exec action | execute action or model entry point or model task from within entrypoint | task another action. Actions from other MDL files may also be used. The action name must be prepended with the MDL file name (basename only). Action, entry points and tasks must be specified as strings:

exec "Trigger action" exec "other.mdl:Inject error" exec "entry:do_step" exec "task:my_task"

health check internal diagnostics and report it to the journal file mark [expression] Produce a mark in the message pane and journal file. When expression is omitted, the mark looks like: MARK-n, with n being a sequence number. When expression is given, the mark looks like: COMMENT-n comment, with comment being the value of expression converted to string. Table 23.5: Input/Output and Control commands (do not return values)

c Airbus Defence and Space 335 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Command Description monitor [options] Please note that this command is obsolescent. dictlist Pop-up a monitor on the “Script Monitors” tab pane. This command can be used to start monitoring of a (set of) variable(s) when a certain condition during simulation is met. Information on the variables is derived from the data dictionary. The options argument is a single string containing a comma separated list of options. Valid options are: type alfa|time|xy: type of monitor point cross|line|both: line style of monitor xsize number: xsize of monitor window ysize number: ysize of monitor window xmin number: minimum x value of monitor plot range xmax number: maximum x value of monitor plot range ymin number: minimum y value of monitor plot range ymax number: maximum y value of monitor plot range Example:

monitor "type=time, point=cross, xsize=1, ysize=2, xmin=3.0, xmax=4, ymin=5, ymax=6" :A:B:C:source1.c:work1:local1

pause (or freeze) request change simulator state from ‘executing’ to ‘standby’. print expression list5 Evaluate the expressions in the expression list and print them on the message pane and journal file. raise event raise an input event as defined in the EuroSim schedule, e.g.:

raise "HARDWARE_FAILURE"

record [per switch] Record one sample of a given set of variables to an optionally [filename] dictlist6 named file. The simulation time is recorded implicitly and need (or registrate, not be specified. The optional per switch argument specifies the datalog) time (in seconds or hours) in case a recorder file should periodically switch. The filename argument is optional. It can be used for “named” recording. If filename is not specified, the action’s name suffixed by .rec will be used as file name. In case of a periodic switch the filename becomes filename-00n (with switch counter n). reinit ["soft" | "hard"] Reload the data dictionary with the values from a snapshot file. filename (or If the “hard” option is given the simulation time will be set to the initialise, init) value defined in the snapshot file. The “soft” option is the default. When this option is used (or no option) the simulation time in the snapshot file is ignored. After the loading of the file has finished the scheduler event SNAPSHOT_END is raised so that a task can be triggered to use the values to reinitialize external hardware for instance. Table 23.5: Input/Output and Control commands (do not return values)

5An expression list is a comma-separated list of expressions. 6A dictlist is a comma-separated list of data dictionary variables.

336 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Command Description run (or go) Request change simulator state from ‘standby’ to ‘executing’ schedspeed expression Set the scheduler speed to result of expression. schedspeed("AFAP") sets the scheduler in ‘as fast as possible’ mode. This function only has effect if the scheduler is in non-realtime mode. set realtime Change the real-time mode to result of expression. expression set time expression Change the simulation time to result of expression. snapshot [filename] Make a snapshot of the current data dictionary and save it to a file. Default file name is snapshot-n.snap, n=0, 1, 2, ... stimuli ["soft" | "hard" Stimulate the specified set of data dictionary variables with the | "cyclic"] filename next record of values contained in filename. If the “hard” option dictlist is given, the next record in the stimuli file will be applied when the given timestamp (value in first column in the stimuli file) matches the simulation time. In the default case “soft” the timestamps are ignored. With the “cyclic” option the stimulation is applied periodically, ignoring the timestamps. stop request change simulator state to ‘stopping’ Table 23.5: Input/Output and Control commands (do not return values)

23.7 MDL syntax

The syntax below is specified in a Backus-Naur Form. ’:’ indicates the start of the definition of the item listed before the colon. ’|’ indicates an alternative and ’;’ terminates the definition. So A: B|C|D; means that ’A’ can be ’B’, ’C’ or ’D’. Bold words are literal strings. string is a placeholder for an actual string, i.e. a sequence of characters, delimited by double quotes. Example: "this is a string" identifier is a placeholder for an actual identifier of a variable or function. Identifiers consist of a sequence of letters, digits and the underscore and dollar character. Examples: var1, _var2 and block$var3 external-identifier is a placeholder for an actual identifier of a variable or function coming from another MDL action. It consists of the name of an action followed by an identifier of a variable or function separated by a colon. The name of an action may contain spaces and therefore it is possible to enclose the name of the action in double quotes. If there are no spaces in the name of the action the double quotes are not needed. Examples: action1:var1 and "action two":var2 dictpath is a placeholder for a data dictionary path name. A data dictionary path consists of a list of orgnodes followed by an identifier separated by colons. Example: :system-A:subsystem-B:source.c:variable_d {Decimal} is a decimal number. {Octadecimal} is an octal number. It starts with a 0 and consists of one or more numbers in the range 0-7. {Hexadecimal} is a hexadecimal number. It starts with 0x and consists of one or more numbers in the range 0-9 and letters in the range A-F or a-f.

c Airbus Defence and Space 337 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

{FloatingPoint} is a floating point number. It can have a decimal point and/or an exponent. {Time} is a time specification. It has the following format: YYYY-MM-DD hh:mm:ss optionally fol- lowed with a decimal point followed by fractions of a second. YYYY is the year in four decimal digits. MM is the month of the year in the range of 1 to 12. DD is the day of the month in the range of 1 to 31. hh is the hour of the day in the range of 0 to 23. mm is the minute of the hour in the range of 0 to 59. ss are the seconds of the minute in the range of 0 to 59. You can specify sub-second precisions by adding a fraction to the seconds. Example: 2003-06-05 10:11:12.131415

#grammar: MDL /* MDL action scripts */ : MDLscript tEOF | MDLfuncs Cont MDLscript tEOF | tEOF ;

MDLscript : Action | MDLscript Action ;

MDLfuncs : FunctionDeclaration | MDLfuncs Term FunctionDeclaration ;

Action : action string /* CONTINUED */ Attributes Cont /* CONTINUED */ ActionBody Cont /* CONTINUED */ ActionCondition ;

ActionBody : CompoundStatement | action begin Cont StatementList Cont action end | action begin Cont action end | { Cont } | begin Cont end | action begin Cont StatementList tEOF | { Cont StatementList tEOF | begin Cont StatementList tEOF ;

Attributes :/* no attributes */ | [ AttributeList ] ;

ActionCondition :/* no condition */ | When ( Cont PossibleCondition ) Term ;

When : when ;

PossibleCondition :/* nothing */ | Condition Cont ;

Condition : Expr ;

338 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

/* * ActionAttribute are used to manipulate: * - appearance of Action in Action Sheet (GUI) * - initial status of action, when condition is specified * */ AttributeList : ActionAttribute | AttributeList , ActionAttribute ;

ActionAttribute : ActionStateAttribute /* state attributes */ | PixelCoord PixelCoord /* x y position on action Sheet */ | {Integer} /* icon # on action Sheet */ | bitmap is string /* bitmap */ | bitmap = string /* bitmap */ | index is {Integer} /* index */ | index = {Integer} /* index */ | folder is string /* folder */ | folder = string /* folder */ | actionmgr is {Integer} | actionmgr = {Integer} /* action mgr nr */ | type is string | type = string | string /* description field */ ;

ActionStateAttribute : identifier | ActionStateAttribute || identifier | ActionStateAttribute or identifier | ActionStateAttribute + identifier | ActionStateAttribute plus identifier ;

CompoundStatement : { Cont StatementList Cont } | begin Cont StatementList Cont end ;

StatementList : Statement | StatementList Statement ;

Statement : DeclarationList | for ( Assignment ; Condition ; Assignment ) Cont Statement | for Assignment to Expr loop Cont Statement | while ( Condition ) Cont Statement | do Statement while ( Condition ) Term | do CompoundStatement while ( Condition ) Term | continue Term | break Term | return Term | return Expr Term | Assignment Term | BuiltInCommand Term | FunctionCall Term | ; Term | IfStatement | CompoundStatement Term ;

IfStatement : if ( Condition ) Cont ThenStatement ElseStatement | if ( Condition ) Cont ThenStatement ;

ThenStatement : Statement ;

c Airbus Defence and Space 339 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

ElseStatement : else Cont Statement ;

Assignment : Lvalue is Cont Expr | Lvalue = Cont Expr | set Lvalue to Expr | set Lvalue Expr | ComplexAssignment ;

ComplexAssignment : Lvalue += Expr | Lvalue -= Expr | Lvalue *= Expr | Lvalue /= Expr | Lvalue %= Expr ;

Lvalue : Variable ;

Expr : MdlExpr | Variable ;

Argument : MdlExpr | Variable ;

MdlExpr : Constant | FunctionCall | ( Expr ) | Expr + Expr | Expr plus Expr | Expr - Expr | Expr minus Expr | Expr / Expr | Expr * Expr | Expr times Expr | Expr % Expr | - Expr | minus Expr | Expr ˆ Expr | Expr pow Expr /* conditions */ | Expr == Expr | Expr equals Expr | Expr != Expr | Expr not equals Expr | Expr >= Expr | Expr greater equal Expr | Expr <= Expr | Expr less equal Expr | Expr > Expr | Expr greater than Expr | Expr < Expr | Expr less than Expr | Expr && Expr | Expr and Expr | Expr || Expr | Expr or Expr | Expr & Expr | Expr | Expr | Expr << Expr | Expr >> Expr | ! Expr | not Expr ;

FunctionCall

340 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

: BuiltInFunction | UserFunction | ExternalFunction ;

UserFunction : identifier () | identifier ( ExprList ) ;

ExternalFunction : external-identifier () | external-identifier ( ExprList ) ;

BuiltInFunction : wallclock boundary ( ) | realtime ( ) | time ( ) | duration ( ) | simstate ( ) | wallclock ( ) | main cycle ( ) | simtime boundary ( ) | disable entrypoint ( Expr ) | atan ( Expr ) | cos ( Expr ) | exp ( Expr ) | fabs ( Expr ) | log ( Expr ) | sin ( Expr ) | sqrt ( Expr ) | tan ( Expr ) | acos ( Expr ) | asin ( Expr ) | ceil ( Expr ) | cosh ( Expr ) | floor ( Expr ) | log10 ( Expr ) | sinh ( Expr ) | tanh ( Expr ) | doublet ( Expr ) | ramp ( Expr ) | jigsaw ( Expr ) | step ( Expr ) | frac ( Expr ) | catch ( Expr ) | eventcount ( Expr ) | getenv ( Expr ) | enable entrypoint ( Expr ) | format ( ExprList ) | freq ( ExprList ) | changed ( Expr ) ;

BuiltInCommand : activate Expr | deactivate Expr | exec Expr | raise Expr | set time Expr | set realtime Expr | trace Expr | mask {Integer}{Integer} | schedspeed Expr | print ExprList | monitor string ExprList /* string contains options (obsolescent) */ | monitor ExprList /* no display options (obsolescent) */ | stimuli string ArgumentList /* first arg is file name */ | stimulate string ArgumentList /* first arg is file name */ | stimuli string string ArgumentList | stimulate string string ArgumentList | record string string ArgumentList | datalog string string ArgumentList | registrate string string ArgumentList | record string ArgumentList

c Airbus Defence and Space 341 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

| datalog string ArgumentList | registrate string ArgumentList | record ArgumentList | datalog ArgumentList | registrate ArgumentList | initialise Expr | reinit Expr | init Expr | initialise string Expr | reinit string Expr | init string Expr | AtomicAction ;

AtomicAction : run | go | pause | freeze | stop | abort | snapshot Expr | snapshot | mark Expr | mark | health ;

ExprList /* list of simple expressions */ : Expr | ExprList , Cont Expr ;

ArgumentList /* list of generic (may contain complex types expressions */ : Argument | ArgumentList , Cont Argument ;

IdentList : identifier | IdentList , identifier ;

Constant : string | {Integer} | {FloatingPoint} | {Time} | zero | off | on ;

PixelCoord : {Integer} | + {Integer} | plus {Integer} | - {Integer} | minus {Integer} ;

Variable : identifier | identifier ArraySelector | ExternalVar | DictVar ;

ExternalVar : external-identifier | external-identifier ArraySelector ;

DictVar : DictPath

342 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

| DictPath DictSelectorList /* ctype selectors */ | DictPath ( ArgumentList ) /* fortran array */ ;

DictPath : dictpath ;

DictSelectorList : DictSelector | DictSelectorList DictSelector ;

DictSelector : RecSelector | ArraySelector ;

RecSelector :.identifier | RecSelector .identifier ;

DeclarationList : Type identifier Term | Type identifier is Expr Term | Type identifier = Expr Term | Type identifier ArraySelector Term | FunctionDeclaration Term ;

FunctionDeclaration : function identifier ( IdentList ) Cont CompoundStatement | function identifier () Cont CompoundStatement ;

ArraySelector : [ Expr ] | ArraySelector [ Expr ] ;

Type : int | float | string | datetime ;

Cont :/* nothing */ | tNEWLINE ;

Term : tNEWLINE | ; ;

#tokens: tAND ASSIGN: &= (reserved) tCASE: case (reserved) tDEC OP: -- (reserved) tDEFAULT: default (reserved) tEOF: end-of-file tINC OP: ++ (reserved) tNEWLINE: newline character tOR ASSIGN: |= (reserved) tSWITCH: switch (reserved) tUSED OP: used | ? (reserved) tXOR ASSIGN: ˆ= (reserved)

c Airbus Defence and Space 343 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

344 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 24

Perl batch reference

24.1 Introduction

This chapter provides details on the batch utility for the perl scripting language1. Various perl modules have been created that provide an interface to existing EuroSim libraries. This means that a batch script is no more than an ordinary perl script using EuroSim modules. The EuroSim modules can be combined with the built-in features of perl itself or with one of the many perl modules which are freely available on the internet. A complete overview of all available perl modules can be found on the Comprehensive Perl Archive Network( CPAN). The EuroSim perl modules consist of a Session module, a Simulator Definition module, an MDL module, a Dict module, an Initial Condition module, a Linke module and a Connection module. These modules follow the perl object-oriented design features, which means that given an object you can call methods in the following manner: $object->method($arg1, $arg2);

The EuroSim perl modules are located in /usr/EuroSim/lib/perl5 or /usr/EuroSim/lib64/perl5 depending on the architecture of the platform. To use the modules you must set your PERL5LIB environment variable to point to this directory. (The EuroSim package installation will have attempted to set this variable for you as part of the system log on). The perl batch utility also includes an interactive shell which can be used to type commands directly on the command line to start and manipulate simulators. This tool has been implemented in perl using the EuroSim modules and a few other helper modules for the command line interaction. This chapter first decribes the EuroSim perl modules in more detail in section Section 24.2 up to Sec- tion 24.8. Thereafter section Section 24.9 describes the usage of the interactive shell. Section Sec- tion 24.10 demonstrates the use of the modules in an example script. Finally, section Section 24.11 provides essential design information to enable advanced users to integrate the batch utility in a larger system. and Section 24.12 contains commandline utilities to monitor and control smiulator processes.

24.2 Session module

The Session module is the central module used to run simulations and can be seen as the perl replacement of the Simulation controller. The Session module can fully automate anything that can be perfomed with the simulation controller. The Session module supports the client/server protocol with the running simulator executable. For each command that can be send to the simulator over the Event Connection protocol there is a function in this module to send such event. Vice versa, for each message sent from the simulator to the application a callback can be installed to handle the event. A function is provided in the Session class to allow

1Not supported on the Windows platform.

c Airbus Defence and Space 345 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

the script to synchronously wait for any or for a specific message, including a timeout capability. The messages and responses are documented in detail in Chapter 31. To start a simulator using the Session module all that is needed is: use EuroSim::Session ’:all’;

$s = new EuroSim::Session("some.sim"); $s->realtime(1); $s->init;

This command will use the information defined in the simulation definition file to start the simulator. The realtime flag results in a real-time run of the simulator. As shown in the example, the information passed as argument to the function call is similar to what is needed by the simulation controller. In the simulation controller a simulation definition file is opened. It can then be sected whether the runs is to be executed in real-time mode. Hitting the Init button then launches the simulator. The Simulation Controller then starts attempting to connect to the simulator. The init function performs the same process. This function also sets up a number of callback functions for incoming events. The information carried by each event is stored in the session structure. The user can at any moment print the contents of this structure by calling print_session_parameters. To handle events from the simulator in the perl session module, it is required to install event handlers. To install a new handler the function event_addhandler must be called with the name of the that is to be habdle and the perl callback function to call for that event. You can install more than one handler for each event. Handlers are called in the order they were installed. The name of the event is the same as the name of the enumeration identifier, e.g. rtExecuting. To remove the handler, call event_removehandler with the same parameters. Each callback receives the following parameters:

1. Session object, reference to the session hash (see Section 24.2.4)

2. Name of the event (name of the enumeration identifier)

3. Simulation time (sec)

4. Simulation time (nsec)

5. Wallclock time (sec)

6. Wallclock time (nsec)

7. Parameters (event specific)

Example: sub cb_standby { my ($session, $event_name, $simtime_sec, $simtime_nsec, $wallclock_sec, $wallclock_nsec) = @_; print "going to standby at $wallclock_sec\n"; } $session->event_addhandler("rtStandby", \&cb_standby);

# or a bit more compact $session->event_addhandler("rtExecuting", sub { print "going to executing at $_[4]\n"; });

It is possible to synchronously wait for an event you expect. In this case you call wait_event with the name of the event (same name as used to install a handler) and an optional time-out.

346 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

To synchronously wait for some time to pass, you can call wait_time. This function takes the number of seconds you want to wait as an argument. An overview of available events can be found in the EuroSim C client interface description ,section Section 31.3. A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::Session(3).

24.2.1 Monitoring variables

In order to monitor variables you must call the function monitor_add with the variable you want to monitor. The variable parameter is in the form of a valid EuroSim data dictionary path. This function will add the variable to the list of variables monitored in EuroSim. The value of each variable will be updated with a frequency of 2 Hz if they change. If there is no change, no update is sent. The values of the variables are stored in the monitored_vars hash array of the session hash array. To access the value of a variable use the following expression: $s->{monitored_vars}->{var_path}. To stop monitoring a variable you must call the function monitor_delete with the variable you want to stop monitoring. If you only want to get the value of a variable once, it is better to call the function monitor_get. This function retrieves the value of the variable immediately from the simulator, but only once. The value of the variable is in the return value.

24.2.2 Modifying variables

If you want to change the value of a variable in the simulator you can simply call monitor_set with the name and value of the variable. The value will be set as soon as possible in the simulator. Calling monitor_set also works on an array variable or struct in its entirety and will set these values atomically.

24.2.3 Method reference

EuroSim::Session [SIMFILE [, HOSTNAME]] Description Creates a EuroSim simulation session by loading the given simulation definition file simfile. The simulation run will be started on the host with the given hostname or on the current host if not specified. The method returns the session hash, which is a hash structure as described in Section 24.2.4. realtime [FLAG] Description Return the realtime flag to indicate if the simulation is running real-time or not. If FLAG is passed to the function the realtime flag is set to the new value. If FLAG is set to 1 realtime is enabled. If FLAG is set to 0 the next run will be non-realtime. Non-realtime is the default. auto init [FLAG] Description Return the auto init flag to indicate if the simulation performs automatic state transition to initializing or not. If FLAG is passed to the function the auto init flag is set to the new value. If FLAG is set to 1 automatic state transition to initializing is enabled. If FLAG is set to 0 the simulator will wait in unconfigured state until an explicit state transition to initializing is commanded. Automatic state transition to initializing is the default. sim hostname [HOSTNAME]

c Airbus Defence and Space 347 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Return hostname where the current simulation session is running. If HOSTNAME is passed as an argument to the function, the hostname is set. The hostname will be used for future simulation runs.

prefcon [PREFCON] Description Return the connection number of the current simulation session. If PREFCON is passed as an argument to the function, the connection number is set. This can be used in a situation where you need to reconnect to an already running simulator. To start new simulation runs, this number is not used.

workdir [WORKDIR] Description Return the work directory name of the current simulation session. If WORKDIR is passed as an argument to the function, the work directory is set for the next run. This directory is where all input files are found and where the output directory is created. By default the directory is set to the current directory at the moment of starting a new simulation.

outputdir [OUTPUTDIR] Description Return the output directory name of the current simulation session. If OUTPUTDIR is passed as an argument to the function, the output directory is set for the next run. This directory is where all output files will be stored. Output files are recorder files, snapshot files, the timing file and the journal file. By default the directory is set to date/time at the moment of starting a new simulation.

alias [ALIAS] Description Return the alias file name of the current simulation session. If ALIAS is passed as an argument to the function, the alias file is set for the next run. The alias file is used to create aliases of data dictionary variables.

journal Description Return the journal file name of the current simulation session. The journal file name is date/- time/EsimJournal.txt. Where date and time are equal to the time of starting the simulator.

clientname [CLIENTNAME] Description Return the client name of the current simulation session. If CLIENTNAME is passed as an argument to the function, the client name is set for the next run. The client name is the name under which the application calling this function will be known to the simulator. By default this is ”esimbatch”.

startup timeout [TIMEOUT]

348 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Return the startup timeout in seconds of the current simulation session. If TIMEOUT is passed as an argument to the function, the startup timeout is set. The startup timeout default is 5 seconds. If starting up a simulator takes longer than this you must change that default to a higher value. initconds [INITCONDS] Description Override the initial condition file(s) specified in the SIM file. INITCONDS is a reference to an array of initial condition file names. If no INITCONDS parameter is passed it only returns the an array with the current initial condition file names. calibrations [CALIBRATIONS] Description Override the calibration file(s) specified in the SIM file. CALIBRATIONS is a reference to an array of calibration file names. If no CALIBRATIONS parameter is passed it only returns the an array with the current calibration file names. scenarios [SCENARIOS] Description Override the MDL file(s) specified in the SIM file. SCENARIOS is a reference to an array of MDL file names. If no SCENARIOS parameter is passed it only returns the an array with the current MDL file names.

event addhandler EVENT NAME, HANDLER Description Add event handler HANDLER to handle event EVENT NAME. The event handler is added to the end of the list if there are already event handlers installed for this event. The installed handler is returned for later use with event removehandler. An overview of available events can be found in the EuroSim C client interface description ,section Section 31.3. event removehandler EVENT NAME, HANDLER Description Remove callback function HANDLER for event with name EVENT NAME. An overview of available events can be found in the EuroSim C client interface description ,section Section 31.3. sev to string SEV Description Return string representation of severity SEV. esim connect Description Connect to a running simulator as specified in. A new journal file is opened and a window with test controller messages is opened in interactive mode. init

c Airbus Defence and Space 349 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Start a new simulation run.

finish Description Finish a stopped simulation session. When a simulation is run in interactive mode a window appears with the test controller messages. When the simulation stops, this window is not re- moved to make it possible to read the final messages. In order to finally close that window too, call this function.

esim disconnect Description Disconnect from the simulation session. The simulator will continue to run in the background.

join channel CHANNEL Description Join a channel of a simulation session. By default each session connects to all channels. The following channels are available: mdlAndActions, data-monitor, rt-control, sched-control. To join all channels use channel ”all”.

leave channel CHANNEL Description Leave a channel of a simulation channel.

wait event EVENT NAME [, TIMEOUT] Description Synchronously wait for an event with name EVENT NAME. The default timeout is 10 seconds. Other events are processed normally. If the event arrived within the timeout period then the name of that event is returned. An overview of available events can be found in the EuroSim C client interface description ,section Section 31.3.

abort Description Abort the current simulation run. Equivalent to the Abort button of the test controller.

health Description Request a health check of the running simulator. Prints health information to the test controller window.

reset sim Description Restart the current simulation with the current settings. Equivalent to the Reset button of the test controller.

new scenario SCENARIO

350 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Create a new scenario in the simulator. This new scenario is only a container for new actions. It is not a file on disk. It is a pure in core representation. open scenario SCENARIO Description Open a new scenario file in the simulator with file name SCENARIO. The file must be on disk and readable. The function returns the handle to the newly loaded MDL file or undef if the file cannot be loaded. close scenario SCENARIO Description Close a currently opened scenario with name SCENARIO in the simulator. new action SCENARIO, ACTION Description Add a new action in the scenario file with name SCENARIO. ACTION is the complete action text. There are a few utility functions to generate those actions. See EuroSim::MDL(3). delete action SCENARIO, ACTION Description Delete an action from scenario SCENARIO with name ACTION. action execute SCENARIO, ACTION Description Trigger the execution of the action with name ACTION in scenario with name SCENARIO. This is equivalent to triggering an action manually on the scenario canvas of the Simulation Controller. action activate SCENARIO, ACTION Description Make action with name ACTION in scenario with name SCENARIO active in the running simulator. The action must already be defined in the scenario. This is equivalent to activating an action on the scenario canvas of the Simulation Controller. action deactivate SCENARIO, ACTION Description Deactivate action with name ACTION in scenario with name SCENARIO in the running sim- ulator. This is equivalent to deactivating an action on the scenario canvas of the Simulation Controller. execute command NAME, COMMAND, [ACTION MGR NR] Description Execute command COMMAND with name NAME on action mgr ACTION MGR NR in the running simulator. This is the equivalent of creating an action, executing it and deleting it again.

c Airbus Defence and Space 351 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

snapshot [FILENAME [, COMMENT] ] Description Make a snapshot of the current state of the variables in the data dictionary. The COMMENT string is optional. If you omit the filename, a filename is chosen of the form snapshot ¡simtime¿.snap. The snapshot is saved in the output directory, unless the filename is absolute. This is equivalent to the ”Take Snaphot...” menu option in the ”Simulation” menu of the test controller.

mark [COMMENT] Description Make a mark in the journal file. The COMMENT string is optional. This is equivalent to the ”Make Mark” and ”Make Comment” menu options in the ”Journal” menu of the Test Controller.

sim debug MESSAGE Description Send a debugging message to the simulator. Only used internally for debugging.

sim message MESSAGE Description Send a message to the simulator for distribution to all clients. This is useful if your client application is not the only client of the simulator. The message is broadcasted to all clients.

suspend recording Description Suspend recording in the simulator. This is equivalent to using the ”Suspend Recording” menu item of the ”Simulation” menu of the test controller. Use

resume recording Description Resume recording in the simulator. This is equivalent to using the ”Resume Recording” menu item of the ”Simulation” menu of the test controller.

recording switch Description Switch all recording files of a simulation run. All currently open recorder files are closed and new recorder files are created. Recording will continue in the new recorder files.

set initcond INITCONDS Description Set the initial condition file of the simulation to INITCONDS. You have to do a reset on the simulator before these new initial conditions are taken into account. For example:

$s->set\_initcond("a.init", "b.init", "c.init"); $s->reset\_sim;

352 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

set calibration CALIBRATIONS Description Set the initial condition file of the simulation to CALIBRATIONS. You have to do a reset on the simulator before these new initial conditions are taken into account. For example:

$s->set\_calibration("a.cal", "b.cal", "c.cal"); $s->reset\_sim; reload [SNAPFILE [, HARD]] Description Load initial condition file or snapshot file with file name SNAPFILE into the running simulator. The parameter HARD is by default 0. This means that the simulation time stored in the snapshot file is ignored. If HARD is set to 1, the simulation time is set to the value specified in the snapshot file. monitor add VARNAME Description Start monitoring variable VARNAME. The value of the variable is updated with 2 Hz. The function ”print monitored vars” prints an overview of all monitored variables. monitor remove VARNAME Description Stop monitoring a variable VARNAME. monitor set VARNAME, VALUE Description Set variable VARNAME to value VALUE in the simulator. A message is printed in the journal file for tracing purposes. The command can set a compound value, e.g. array or struct in, in one call to this function, which will set the variable values atomically in the simulator. To set a complex variable in one go, use a comma seperated list in curly brackets as value. Nesting of complex values is allowed monitor set multi VAR VALUE HASH Description Set multiple variables defined in the VAR VALUE HASH to the specified value in the simula- tor. The key of each hash element is the name of the variable and the value is the new value of the variable. A message is printed in the journal file for tracing purposes. This method can set multiple different variables in one go, the variables can be complex and all variables are set atomically via the action manager task. monitor get VARNAME Description Get value of variable VARNAME from the simulator. cpuload set peak PROCESSOR, PEAK TIME

c Airbus Defence and Space 353 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Configure the CPU load monitor peak time in msecs.

set breakpoint TASKNAME, ENTRYNR, ENABLE Description Set a breakpoint on entry nr ENTRYNR in task TASKNAME in the scheduler. If parameter ENABLE is set to 1 the breakpoint is enabled. To disable it again set the parameter to 0.

set trace TASKNAME, ENTRYNR, ENABLE Description Enable/disable tracing of entry points. Entry points are defined by specifying the number of the entry point ENTRYNR (numbering starts at 0) and the name of the task TASKNAME. To enable a trace set ENABLE to 1, to disable it set it to 0. Tracing an entry point means that messages are printed to the journal window.

where Description Request the current position when the scheduler has stopped on a break point. The reply to the message is automatically stored in the SESSION structure. Normally the position is sent to the client whenever the scheduler hits a breakpoint. So there is rarely any need to request the position manually if you store the position on the client side (as is done in this tool.)

step task Description Perform one step (=one entrypoint) in the scheduler debugger.

cont Description Continue executing upto the next breakpoint in the scheduler debugger.

list tasks Description Request a list of all tasks in the current schedule of the simulator. The list is also sent auto- matically upon joining the ”sched-control” channel. The information is stored in the SESSION structure.

task disable TASKNAME Description Disable task with name TASKNAME in the current schedule of the simulator.

task enable TASKNAME Description Enable task with name TASKNAME in the current schedule of the simulator.

clear breaks

354 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Remove all breakpoints in the current schedule of the simulator. clear traces Description Remove all traces in the current schedule of the simulator. set simtime SIMTIME SEC, SIMTIME NSEC Description Set the simulation time to SIMTIME SEC seconds and SIMTIME NSEC nanoseconds. This can only be done in stand-by state. enable realtime Description Switch to real-time mode. This can only be done when the simulator has started off in real-time mode, and has switched to non-real-time mode. disable realtime Description Switch to non-real-time mode. list events Description Request a list of all events in the schedule of the simulator in all states. The result is stored in the SESSION structure. The list is automatically sent to the client when subscribing to the ”sched-control” channel at start-up. raise event EVENT Description Raise event with name EVENT in the scheduler. An event is defined by the input connector on the scheduler canvas. The event is handled as fast as possible. raise event at EVENT, SEC, NSEC Description Raise event with name EVENT in the scheduler at a specified wallclock time. The wallclock time is specified as SEC seconds and NSEC nanoseconds. raise event at simtime EVENT, SEC, NSEC Description Raise event with name EVENT in the scheduler at a specified simulation time. The simulation time is specified as SEC seconds and NSEC nanoseconds. speed ACCELERATION

c Airbus Defence and Space 355 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Set the acceleration/deceleration of the scheduler of the simulator. Values smaller than 1 will cause a proportional deceleration of the scheduler clock. Values larger than 1 will cause a proportional acceleration of the scheduler clock. Magical value -1 means that the scheduler will run in an optimized as-fast-as-possible mode.

entrypoint set enabled ENTRYPOINTNAME, ENABLED Description Enable/disable entry point. If ENABLED is 1 the entry point ENTRYPOINTNAME is enabled, if it is 0 it is disabled. The entry point is not executed by the scheduler nor from MDL scripts.

kill [SIGNAL] Description Kill the session SESSION with signal SIGNAL. By default the current session is killed with SIGTERM.

24.2.4 Session Hash reference The Session object is a hash table with the following fields:

MDL Hash table of loaded MDL files. Each hash key is the name of a loaded MDL file. The hash value is a EuroSim::MDL object. MDL files are loaded at start-up when a .sim file is loaded or during run-time when extra MDL files are loaded. Extra files can be loaded by the built-in event handler for event maNewMission or by manually adding MDL files with new_scenario. clientname The name under which this session is known to the simulator. The value is set with the function clientname.

conn EuroSim::Conn object. Low level connection object.

cwd Current working directory of the simulator. The value is set by the built-in event handler for event maCurrentWorkingDir.

dict Data dictionary file name. The value is set by the built-in event handler for event maCurrentDict. eventlist List of events present in the schedule. The value is set by the built-in event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. The eventlist is an array of hash tables. Each table consists of three elements:

name The name of the event.

state The scheduler state for which it is defined. is standard Flag indicating that it is a standard event, i.e. predefined by EuroSim.

handler Event handler table. sim hostname Simulation host name. The value is set with the function sim_hostname. startup timeout Simulation startup timeout. The default value is 5 seconds and it can be change with the function startup_timeout.

356 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

initconds Initial condition files. The value is set by the built-in event handler for event maCurrentInitconds. calibrations Calibration files. The value is set by the event handler for event maCurrentCalibrations. logwindow EuroSim::Window object. Used to display simulation messages in interactive mode. monitored vars Table of monitored variables. outputdir Result directory used in current simulation run. The value is set by the built-in event handler for event maCurrentResultDir. prefcon Connection number. realtime Realtime mode. 1 is real-time, 0 is non-realtime. The value is set by the built-in event handler for event scGoRT. recording Flag indicating that recording is enabled or not. 1 means enabled. 0 means disabled. The value is set by the built-in event handler for event maRecording. recording bandwidth Recorder bandwidth in bytes/second. The value is set by the built-in event handler for event maRecordingBandwidth. schedule Schedule file name. The value is defined in the simulation definition file. simdef Simulation definition handle to a EuroSim::SimDef object. sim time The simulation time (as seen by the running simulator). The value is set by incoming events and thus at least updated at the frequency of the event dtHeartBeat. speed The clock acceleration factor achieved by the simulator. Values larger than 1 indicate faster than real-time. Values smaller than 1 indicate slower than real-time. The value is set by the built-in event handler for event scSpeed. state Simulator state. Can be: unconfigured, initialising, standby, executing, exiting. The value is set by the built-in event handler for the following events: rtUnconfigured, rtInitialising, rtStandby, rtExecuting and rtExiting. stimulator bandwidth Stimulator bandwidth in bytes/second. The value is set by the built-in event handler for event maStimulatorBandwidth. tasklist List of tasks present in the schedule. The value is set by the built-in event handlers for the events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. The field tasklist is a hash table. Each key in the hash table is the name of a task (e.g. $session->tasklist->taskname). Each task consists of a number of entry points and a flag called disable. The disable flag is set by the built-in event handler of scTaskDisable. The entry points are stored in an array. Each array element is a hash table consisting of three fields: name The name of the entry point.

c Airbus Defence and Space 357 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

breakpoint Flag indicating that a breakpoint has been set on this entry point. The value is set by the built-in event handler for event scSetBrk.

trace Flag indicating that this entry point is being traced. The value is set by the built-in event handler for event scSetTrc. time mode The time mode can be relative or absolute (UTC). Relative is 0 and absolute is 1. The value is set by the built-in event handler for event maCurrentTimeMode.

alias Alias file used in current simulation run. The value is set by the built-in event handler of event maCurrentAliasFile. user defined outputdir User defined output directory path. This directory path overrides the default output directory path. The value is set with the function outputdir. wallclock time The wallclock time (as seen by the running simulator). The value is set by the incoming events and thus at least updated at the frequency of the incoming event dtHeartBeat. wallclock boundary The wallclock boundary time to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. simtime boundary The simulation time boundary to be used for timed state transitions. If you add an integer num- ber of times the main cycle time to this value it will produce a valid state transition boundary time. main cycle The main cycle time of the current schedule. It can be used to calculate valid boundary times for timed state transitions. watcher Event::io object. Used to process incoming events.

where Current breakpoint. The value is set by the built-in event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. The value is an array of value pairs stored in an array. The first value in the array is the task name and the second is the entry number. For example:

print "task: $s->{where}->[0][0]\n"; print "entry_nr: $s->{where}->[0][1]\n";

write access Flag to indicate whether this client is allowed to change variable values in the simulator. The value is set by the built-in event handler for event maDenyWriteAccess.

24.3 SimDef module

This is the low-level module use to set and get values in the session definition RPC structure used to launch simulators. It is accessed through the EuroSim::Session module by end users.

358 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

24.3.1 Method reference open FILENAME [, HOSTNAME] Description Open the simulation definition file with file name FILENAME. By default the local host is used to determine the simulator and dict paths. By specifying a specific HOSTNAME you can override this. The function returns a handle to a simulation definition object. filename SIM Description Close the simulation definition object. filename SIM Description Return the filename of the simulation definition file. mdl list SIM Description Return an array with filenames of MDL files. model SIM Description Return the filename of the model file. initcond list SIM Description Return an array with filenames of initial condition files. calibration list SIM Description Return an array with filenames of calibration files. schedule SIM Description Return the filename of the schedule file. dict SIM Description Return the filename of the data dictionary file. outputdit SIM, OUTPUTDIR Description Set the output directory. workdir SIM, WORKDIR

c Airbus Defence and Space 359 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Set the work directory.

alias SIM, ALIAS Description Set the alias file.

update arch SIM, HOSTNAME Description Set the dict and simulaator paths correctly based on the hostname.

refresh outputdir SIM Description Refresh the output directory name based on the current date and time

realtime SIM [, RT FLAGS] Description Get/Set the realtime file. 0= non-realtime, 1= realtime

launch HOSTNAME Description Launch the simulator

24.4 MDL module

This is a wrapper module for the EuroSim Script functions. These functions manipulate MDL files and actions. The following (sets of) functions are available:

• read MDL file

• write MDL file

• add actions to the MDL file

• delete actions from the MDL file

• utility functions to ease the creation of new actions There are four functions to generate action text: script action create a generic action script monitor action create a monitor action script recorder action create a recorder action script stimulus action create a stimulus action script A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::MDL(3) and the following method reference.

360 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

24.4.1 Method reference open FILENAME,DICT Description Open the MDL file with file name FILENAME and data dictionary DICT. The function returns a handle to an MDL object. close MDL Description Close the MDL object filename MDL Description Return the filename of the MDL file. action list MDL Description Return a list iwth the names of all the actions. script actions NAME, SCRIPT, CONDITION Description Create and MDL script text for an action name NAME with script action SCRIPT and condition CONDITION. monitor action NAME, VAR1, VAR2, ..., VARN Description Create an MDL script text for a monitor action name NAME with variables VAR1, VAR2 to VARN. recorder action NAME, FREQ, VAR1, VAR2, ..., VARN Description Create an MDL script text for a recorder action name NAME with variables VAR1, VAR2 to VARN to be recorded at frequence FREQ. stimulus action NAME, OPTION, FILENAME, FREQ, VAR1, VAR2, ..., VARN Description Create an MDL script text for a stimulus action name NAME with variables VAR1, VAR2 to VARN to be stimulated from file FILENAME at frequency FREQ.

24.5 Dict module

This is a wrapper module for the EuroSim data dictionary functions. You can open and close EuroSim data dictionary files. You can get and set individual values of variables. This is used in conjunction with the initial condition module. This module is also used for command line completion in interactive mode to complete the path of data dictionary variables. A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::Dict(3) and the following method reference.

c Airbus Defence and Space 361 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

24.5.1 Method reference

open FILENAME Description OPen data dictionary file FILENAME. The function returns a EuroSim::Dict object.

close DICT Description Close the DICT object. Frees memory.

list DICT, PATH Description Return a list of child node names of parent node PATH.

var value get DICT, PATH Description Return the numerical value of variable with dictionary path PATH.

var string get DICT, PATH Description Return the string value of variable with dictionary path PATH.

var value set DICT, PATH Description Set the numerical value of variable with dictionary path PATH.

var string set DICT, PATH Description Set the string value of variable with dictionary path PATH.

24.6 InitCond module

This module offers reading and writing of initial condition files. You can also use it to combine multiple initial condition files into one file. In conjunction with the EuroSim::Dict module it is possible to set variables to specific values, and then save them in an initial condition file. The following steps must be taken to change values in an initial condition file:

1. Load a data dictionary file.

2. Load one or more initial condition files into that data dictionary

3. Set one or more values of variables to their initial values.

4. Save the initial condition file with the new values.

This initial condition file can be used in a new simulation run, or it can be loaded into an already running simulator. In order to load it into a running simulator, the simulator must be in standby state, or it can be used for reinitialization.

362 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Example: # load a data dictionary $dict = EuroSim::Dict::open("test.dict");

# load initial values into that dictionary $initcond = EuroSim::InitCond::read("test.init", $dict);

# get an initial condition value $value = $dict->var_value_get("/test/var1");

# set an initial condition value $dict->var_value_set("/test/var2", 3.1415);

# save the new initial condition file in ASCII format $initcond->write("test2.init", 0);

A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::InitCond(3) and the following reference section.

24.6.1 Method reference read FILENAME, DICT Description Read initial condition file with file name FILENAME. The values are loaded into an existing DICT. The function returns an object of type EuroSim::InitCond. add INITCOND, FILENAME Description Add additional initial condition values from initial condition file with file name FILENAME to initial conditions INITCOND. simtime INITCOND Description Return the simulation time specified in the initial conditions INITCOND. comment INITCOND Description Return the comment string specified in the initial conditions INITCOND. get varlist failed INITCOND Description Return the list of variables defined in the initial condition file read but not present in the data dictionary. This is used to report to the user that the initial condition file contains variables which are not part of the data dictionary. This is an error. get varlist set INITCOND Description Return the list of variables in the initial condition file which were successfully loaded into the data dictionary. write INITCOND, FILENAME, BINARY Description Write out the initial conditions in INITCOND to a file named FILENAME. If BINARY is set to 1, the format is binary, otherwise it is in ASCII format.

c Airbus Defence and Space 363 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

24.7 Link module

This module wraps the EuroSimTM/TC Link library (see Chapter 33). Create a TM/TC link and connect it to a running simulator using link_open and link_connect. Thereafter link_read and link_write can be used to read and write data on the tmtc link. Finally the tmtc link can be terminted using link_close. A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::Link(3) and the following reference section.

24.7.1 Method reference

open ID, MODE Description Open one end of a TmTc Link named ID with mode MODE. Mode is ”r”, ”w” or ”rw”. The function returns a EuroSim::Link object.

connect LINK, SESSION Description Connects one end of link LINK to the other end in a running simulator SESSION.

close LINK Description Close the link LINK.

write LINK, DATA Description Write DATA to the link LINK.

read LINK Description Read datafrom the link LINK. The data read is returned.

24.8 Connection module

This is the low-level module used to send and receive events (messages) from/to a running simulator. All of these functions are used internally by the EuroSim::Session module. To print a list of all events use print_event_list. This function prints a list of all events, their internal event number and their arguments. The EuroSim manual pages provide more details on the events, type man 3 to get more details. A complete overview of all functions provided by this module can be found in the manual page Eu- roSim::Conn(3). The following reference provides all non internal functions.

364 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

24.8.1 Method reference event num EVENT NAME Description Return the internal event number given the name EVENT NAME of the event. For an overview of the available events, see the EuroSim manual page events(3) or section Section 31.3. event num EVENT NUMBER Description Return the internal event number given the name EVENT NUMBER of the event. simulator SESSION. event list Description Return an array of hash tables containing the table of events (messages). Each event has the following hash keys and values: id - numerical event number name - symbolic event name args - string of characters indicating the types of the arguments sim disconnect CONN Description Disconnect from a running simulator. The connection is specfied by parameter CONN. session fd CONN Description Return the file handle of the socket of the connection CONN. session prefcon CONN Description Return the connection number of the connection CONN. session poll CONN Description Poll for incoming data on connection CONN. For each incoming packet the callback function is called.

24.9 The interactive batch shell

The EuroSim perl command line shell is started by running the esimsh command. The esim> prompt appears and you can start typing commands. The shell has various forms of completion. Typing TAB once will show you a complete list of available commands. Each command is in fact a perl function provided by the EuroSim modules. Read the manual pages for detailed information on arguments and return values. You can save the commands by using the built-in logging function. This function is started by calling log_open “perl-script”. All commands entered after this are written to the file called perl-script. This file can then be used as a starting point for further non-interactive runs. To stop logging commands you call log_close.

c Airbus Defence and Space 365 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

When you start a simulation in interactive mode (the default when starting esimsh) an xterm window is started to show the journal messages. Normal usage of the EuroSim perl modules requires an object oriented notation in the following manner:

$object->method($arg1, $arg2);

There is one module which forms an exception to this rule for convenience reasons when using the interactive shell: EuroSim::Session. All functions (methods) can be called directly without the object reference. This is done to reduce typing in the interactive shell. Each function uses the current session. This works fine as long as you only have one session. If you want to manage multiple sessions in parallel within one script you must use the full notation.

24.10 Example

The following example is a complete script which performs one simulation run. Some event handlers are installed as well as some monitors.

Batch script example

#!/usr/bin/perl # This is an example perl script using the EuroSim bindings # to automate a simulation run. # Import all modules. use EuroSim ’:all’; use EuroSim::InitCond ’:all’; use EuroSim::Session ’:all’; use EuroSim::Link ’:all’; use EuroSim::Conn ’:all’; use EuroSim::MDL ’:all’;

# Load the simulation definition file. $s = new EuroSim::Session("some.sim");

# Set to real-time. $s->realtime(1);

# Define a callback to be called when standby state is reached. sub cb_standby { my ($session, $event_name, $simtime_sec, $simtime_nsec, $wallclock_sec, $wallclock_nsec) = @_; print "going to standby at $wallclock_sec\n"; }

# Install the callback. $s->event_addhandler("rtStandby", \&cb_standby);

# The same thing but then a bit more compact. # Isn’t perl wonderful :-) $s->event_addhandler("rtExecuting", sub { print "going to executing at $_[4]\n"; });

# Start the simulation run. $s->init;

# Wait for standby state. $s->wait_event("rtStandby");

366 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

# Add a monitor for variable "/test/var1". # Note that the $ sign in fortran variables must be escaped. $var = "/test/var1"; $s->monitor_add($var);

# Wait one second. This should be more than enough for the 2Hz # update to take place. $s->wait_time(1);

# Print the value of the monitored variable. print "The value of $var is $s->{monitored_vars}->{$var}\n";

# Trigger an event "my_event". $s->raise_event("my_event");

# Trigger another event at some time in the future. In this # case at simulation time 5.025 s. $s->raise_event_at_simtime("another_event", 5, 25000000);

# Trigger an action in an MDL script. $s->action_execute("some_loaded.mdl", "inject a failure");

# Go to executing state. $s->go;

# Wait for the state transition to executing state. $s->wait_event("rtExecuting");

# Schedule a state transition to standby state at simulation # time 1000.0 s. $s->freeze_at_simtime(1000, 0);

# Wait for the state transition to standby state. $s->wait_event("rtStandby");

# Stop the simulation. $s->stop;

# Wait until the connection with the simulator is shut down. $s->wait_event("evShutdown");

# Quit the script. $s->finish;

24.11 Extending the perl batch utility

For advanced users, this section provides design information required for the extensionof the EuroSim perl batch utility capabilities. The batch utility is based on the Event module. This perl module provides a framework where you can integrate various systems with each other. The client-server connection with the simulator sends packets to its clients (such as the batch utility). These packets are handled by a callback (watcher in Event module terminology). The Event module is used to perform the mapping between incoming data on a socket to the central event dispatching function of the EuroSim::Session module. Also the wait functions are implemented by using the timer watcher. The interactive EuroSim shell is implemented using this module. The input is processed by the package Term::ReadLine::Gnu. This package reads commands from stdin. The readline input function is hooked

c Airbus Defence and Space 367 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

into the Event framework using an io watcher. The EuroSim connection is handled by another Event::io watcher. This enables the interactive shell to stay interactive. It reads simultaneously from the standard input and from the EuroSim socket. This mechanism can be extended to your needs. For a complete reference check out the Event(3) manual page.

24.12 Command line utilities

There are two EuroSim command line utilities that can be very useful in combination with the batch utility. They are briefly described in the following subsections.

24.12.1 efoList

The efoList command line utility shows a list of currently running simulators. See the ICD document or the manual page efoList(1) for information on the command line options that can be passed to efoList.

24.12.2 efoKill

The efoKill command line utility lets you terminate a running simulator. See the ICD document or the manual page efoKill(1) for information on the command line options that can be passed to efoKill.

368 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 25

Java batch reference

25.1 Introduction

This chapter provides details on the batch utility for the Java language. Various Java classes have been created that provide an interface to existing EuroSim libraries. This means that a batch application is no more than an ordinary Java program using EuroSim classes. These classes offer the same capabilities to a Java program as the Simulation Controller to an operator. Writing a Java program is therefore much like programming an operator, including waiting for changes and handling events, checking and setting variable values, and even inserting and controlling MDL scripts. These capabilities allow complete simulation runs to be automated, which can for instance be used for unit and system testing, both on demand and in nightly regression runs. It can also be used in combination with manual operation, for instance to automate the startup of complex simulators, allowing multiple programs and hardware to be booted and then starting the Simulation Controller in an attached state for the operator. The Java language interface is generated using SWIG and wraps the C++ client interface provided by EuroSim. The same interface is also available for Java and Tcl. Note that the EuroSim Perl interface is not generated via SWIG and though it follows the same concept it differs in interface and capabilities. The batch utility for java consists of various classes. Each class (or group of classes) is described in a separate chapter. The most important classes are the Session and EventHandler classes. Due to the fact that the classes are in fact wrapper classes around existing C++ code you have to load the native code library explicitly. In order to use the EuroSim batch classes you have to add the following code: import nl.eurosim.batch.*; public class example { static { try { System.loadLibrary("eurosim"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. " + e); System.exit(1); } }

// your code }

When compiling, use javac -classpath $EFOROOT/lib64/java/eurosim.jar.

c Airbus Defence and Space 369 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

25.2 Session class

The Session class is the central class used to automate simulations. Its methods wrap the EuroSim dae- mon interface to launch and connect to simulators, as well as the EuroSim ”EventConnection” network protocol to control a running simulator. For sending EventConnection messages to the simulator, the Session class provides a method for each possible command to easily fill the event structure and sends it to the simulator. For handling incoming events generated by the simulator, the Session class supports both a callback mechanism to handle each type of event, as well as the means to blocking wait for a specific message. Both mechanisms are based on the wait_event method of the Session class. This method processes received events from the EventConnection socket until it either encounters a specific event, exceeds a timeout or the socket buffer is exhausted. While processing events the wait_event method will call for each event the associated event handler routine which is either a default handler or a user installed handler. In Java installation of user defined event handlers can be achieved by instantiating an object of a class that is derived from the EuroSim EventHandler class. The wait_event method is thus the single interface through which the user’s script controls when events are processed and which assures that such processing does not occur in parallel to the execution of the user’s script. The event handler mechanism thereby assures that all incoming events can be handled, even when waiting for a specific event and/or amount of time. When only using event handlers, the user would call wait_event without arguments to process each received event until the socket is exhausted. When wanting to blocking wait for a specific event the user would call wait_event with the name of the specific event to wait for. The wait_event call will not return until the event occured. A second timeout argument can be provided to limit the amount of time that is waited for the occurence of the event. The result of wait_event indicites if the specified event occurred. By only providing the timeout the processing of events continues for the specified amount of wallclock time. Note that this wallclock time increases based on the wallclock timestamps in the received events, which is thus limited in resolution but is guaranteed to be at least updated with 5Hz (heartbeat messages). The potential events that can be received are documented in detail in Chapter 31. Following is an example of how to start a simulator and wait indefinitely until it achieves Standby state. Session s = new Session("some.sim"); // load simulation definition s.init(); // start simulator s.wait_event("rtStandby"); //wait for achieving standby

As shown in the example, similar information is passed to the Session methods as needed by the Simu- lation Controller. In the Simulation Controller a simulation definition file (.sim) is opened and then the simulator is launched using the Init button. The Simulation Controller then automatically connects to the simulator and processes events in a predefined manner. The example illustrates that in the same manner the constructor for a Session is passed the simulation definition file and the init method launches the simulator and connects when it is ready. The details of this connection are stored in the session class and can be printed with the print_session_parameters method. In the example it is chosen to blocking wait for the occurance of the rtStandby event which is transmitted by the simulator when it enters standby state. We could have also added a timout argument (in msec) to limit the amount of time that the script is allowed to wait for the event in order to provide an escape for situations where the simulator has a startup problem. However, in the mean time the wait_event method also encounters events from the simulator that we may want to handle, for instance resonding to an error event by printing the error messages. For this we need to install an event handler which will force the execution of a user defined callback function when the wait_event encounters the associated event. Note that these callbacks are thus not executed in parallel to the script execution. Although callbacks are associated with asynchronous behavior, they are only called from within the context of a wait_event. In Java, a user defined event handler is installed by creating an object of a class that is derived from the EuroSim EventHandler class. The constructor of the class automatically installs the event handler in the Session class. To remove an event handler, just delete the created event handler object and it unregisters itself. See Section 25.3 for detailed information on each event handler class method.

370 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

25.2.1 Monitoring variables

In order to monitor variables you must call the method monitor_add with the variable you want to monitor. The variable parameter is in the form of a valid EuroSim data dictionary path. This method will add the variable to the list of variables monitored in EuroSim. The value of each variable will be updated with the asynchronous action manager frequency, which defaults to 5 Hz if they change. If there is no change, no update is sent. The values of the variables are stored in the Session class. To get the value of a variable use the following expression: s.monitor_value(var_path). The value is always returned as a string. To stop monitoring a variable you must call the function monitor_remove with the variable you want to stop monitoring. If you only want to get the value of a variable once, it is better to call the function get_value. This function retrieves the value of the variable immediately from the simulator, but only once. The value of the variable is returned as a string.

25.2.2 Modifying variables

If you want to change the value of a variable in the simulator you can simply call set_value with the name and value (as a string) of the variable. The value will be set as soon as possible in the simulator. Calling set_value also works on an array of variables or struct in its entirety and will set these values atomically. To set multiple variables in one API call, use set_values. The argument is an instance of class Variable- Set in the eurosim namespace. Variable value pairs can be added to this VariableSet instance using its add function, which takes the variable path and value string as arguments. The benefit of this approach is a much quicker execution time as the client will send the value pairs in one message to the simulator and wait for confirmation. Using set_value the client will send one message and wait for confirmation, which then must be repeated for each variable.

25.2.3 Method reference 25.2.3.1 Constructors public Session() public Session(String sim) public Session(String sim, String hostname)

Description Creates a EuroSim simulation session by loading the given simulation definition file sim. The simulation run will be started on the host with the given hostname or on the current host if not specified. Parameters sim the simulation definition file name hostname the name of the host on which to run the simulator

25.2.3.2 Methods public String cwd() Description Returns the path name of the current working directory of the simulator. The value is set by the event handler for event maCurrentWorkingDir.

c Airbus Defence and Space 371 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value Path name of the current working directory

public String dict() Description Returns the path name of the EuroSim data dictionary of the simulator. The value is set by the event handler for event maCurrentDict. Return value Path name of the EuroSim data dictionary

public String outputdir() Description Returns the path name of the directory where the output files of the simulator are stored (journal file, recorder files, etc.) The value is set by the event handler for event maCurrentResultDir. Return value Path name of the output directory

public String state() Description Returns the simulator state. Can be: unconfigured, initialising, stand-by, executing, exiting. The value is set by the event handler for the following events: rtUnconfigured, rtInitialising, rtStandby, rtExecuting and rtExiting. Return value Simulator state

public void set remote path() Description If client and server have different paths (e.g. A Windows client launching a simulator on a linux server) set_remote_path can be used to set the root path of the simulator in the remote EuroSim server. Return value None

public String journal() Description Returns the path name of the journal file. Return value Path name of the journal file

public String schedule() Description Returns the path name of the schedule file. Return value Path name of the schedule file

372 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public String exports() Description Returns the path name of the exports file. Return value Path name of the exports file public String alias(String alias) public String alias() Description Set or get the alias file name. Parameters alias Override the alias file specified in the SIM file. If alias was not specified, then the alias file remains unchanged. Return value Path name of the alias file. If the simulation is running, then the value is set by the event handler for event maCurrentAliasFile. public String model() Description Returns the path name of the model file. Return value Path name of the model file public double recording bandwidth() Description Returns the recorder bandwidth in bytes/second. The value is set by the event handler for event maRecordingBandwidth. Return value Recorder bandwidth in bytes/second public double stimulator bandwidth() Description Returns the stimulator bandwidth in bytes/second. The value is set by the event handler for event maStimulatorBandwidth. Return value Stimulator bandwidth in bytes/second public double speed() Description Returns the clock acceleration factor achieved by the simulator. Values larger than 1 indicate faster than real-time. Values smaller than 1 indicate slower than real-time. The value is set by the event handler for event scSpeed. Return value Acceleration factor

c Airbus Defence and Space 373 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public double sim time() Description

Description Returns the simulation time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Simulation time in seconds

public double wallclock time() Description Returns the wallclock time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Wallclock time in seconds

public double wallclock boundary() Description Returns the wallclock boundary time to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Wallclock time boundary in seconds

public double simtime boundary() Description Returns the simulation time boundary to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Simulation time boundary in seconds

public double main cycle() Description Returns the main cycle time of the current schedule. It can be used to calculate valid boundary times for timed state transitions. Return value Main cycle in seconds.

public boolean recording() Description Returns the flag indicating that recording is enabled or not. True means enabled, false means disabled. The value is set by the event handler for event maRecording.

374 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value Recording is enabled public boolean write access() Description Returns the flag to indicate whether this client is allowed to change variable values in the sim- ulator. The value is set by the event handler for event maDenyWriteAccess. Return value Client is allowed to change variables public int time mode() Description Returns the time mode. It can be relative or absolute (UTC). Relative is 0 and absolute is 1. The value is set by the event handler for event maCurrentTimeMode. Return value Time mode public boolean realtime(boolean realtime) public boolean realtime() Description Set or get the realtime mode. Parameters realtime If the realtime mode is not specified, then the realtime mode is not set. If realtime is 0, then realtime mode is disabled, otherwise it is enabled. The new setting will not effect an already running simulation. Return value The realtime mode, true for realtime, false for non-realtime. If a simulation is running, then the value as was set by the event handler for event scGoRT is reported. Non-realtime is the default. public boolean auto init(boolean auto init) public boolean auto init() Description Set or get the auto initialization flag. Parameters auto init If the auto initialization flag is not specified, then the auto initialization flag is not set. If auto init is 0, then the simulator will not go automatically to initializing state on startup, otherwise it will go automatically to initializing (this is the default). The new setting will not effect an already running simulation. Return value The auto init flag, true if the state transition to initializing state is performed automatically, false if it isn’t. Automatic state transition to initializing is the default. public int prefcon(int prefcon) public int prefcon()

c Airbus Defence and Space 375 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Set or get the preferred connection. Parameters prefcon The preferred connection. This can be used in a situation where you need to reconnect to an already running simulator. To start new simulation runs, this number is not used. If prefcon was not specified, then the preferred connection is not set. Return value Return the connection number of the current simulation session.

public int startup timeout(int timeout) public int startup timeout() Description Set or get the startup timeout. The startup timeout default is 5 seconds. If starting up a simulator takes longer than this you must change that default to a higher value. If timeout was not specified, then the startup timeout is not set. Parameters timeout The startup timeout. Return value Return the startup timeout in seconds of the current simulation session.

public String clientname(String clientname) public String clientname() Description Set or get the name under which this session is known to the simulator. Parameters clientname The client name of the current simulation session. The default is “esimbatch”. If clientname was not specified, then the client name is not changed. Return value Return the client name of the current simulation session.

public vector string initconds(vector string initconds) public String initconds() Description Set or get the initial condition files. Parameters initconds Override the initial condition files specified in the SIM file. If initconds was not specified, then the initial condition files remain unchanged. Return value Initial condition files. If the simulation is running, then the value is set by the event handler for event maCurrentInitconds.

public vector string calibrations(vector string calibrations) public String calibrations()

376 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Set or get the calibration files. Parameters calibrations Override the calibration files specified in the SIM file. If calibrations was not specified, then the calibration files remain unchanged. Return value Calibration files. If the simulation is running, then the value is set by the event handler for event maCurrentCalibrations. public String workdir(String workdir) public String workdir() Description Set or get the work directory. Parameters workdir Use this directory as the work or project directory instead of the current directory. Return value The work directory. public String user defined outputdir(String outputdir) public String user defined outputdir() Description Set or get the user defined output directory. Parameters outputdir Use this output directory instead of the default date/time directory. If not set, then the user defined output directory is not changed. Return value The user defined output directory. public String hostname(String hostname) public String hostname() Description Set or get the EuroSim server hostname. Parameters hostname Use this EuroSim server. If not set, then the hostname is not changed. Return value The EuroSim server hostname. public String sim(String sim, String hostname) public String sim(String sim) public String sim() Description Set or get the simulation definition file. This simulation definition file is used to start the simulator. Information derived from the sim- ulation definition file is used to provide sensible defaults for all parameters.

c Airbus Defence and Space 377 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters sim The simulation definition file. If not set, then the simulation definition is not changed. hostname The EuroSim server hostname. If not set, then the local host is used instead. Return value The filename of the simulation definition file.

public int init() Description Start a new simulation run. Return value 1 on success, 0 on failure.

public int join channel(String channel) Description Join a channel of a simulation session. By default each session connects to all channels. The following channels are available: mdlAndActions, data-monitor, rt-control, sched-control. To join all channels use channel “all”. Parameters channel The channel to join. Return value 1 on success, 0 on failure.

public int leave channel(String channel) Description Leave a channel of a simulation channel. Parameters channel The channel that you want to leave. Return value 1 on success, 0 on failure.

public boolean wait event(String event, int timeout ms) Description Wait for an incoming event This function is used to wait synchronously for the given event. The timeout is used to limit the amount of time to wait for this event. Parameters event The name of the event to wait for. If the event name is empty this function can be used to read all pending events while waiting for the given amount of time. timeout ms The timeout in milliseconds. A value of -1 means that this this function will wait until the event arrives for an unlimited amount of time. A value of 0 means that the function will return immediately even if the event has not arrived yet. Return value true if the event had arrived, false if it has not.

public int monitor add(String var)

378 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Monitor a variable. The value of the variable is updated with the frequency of the asynchronous action manager, which defaults to 5 Hz. Parameters var The variable from the data dictionary that you want to monitor. Return value 1 on success, 0 on failure. public String monitor value(String var) Description Retrieve the value of a monitored variable Parameters var The name of the monitored variable. Return value the value of the variable public int monitor remove(String var) Description Remove the monitor of a variable. Parameters var The variable from the data dictionary that should be removed from the monitor list. Return value 1 on success, 0 on failure. public long create session list(String hostname) public long create session list() Description Create a list of all sessions and return the size of that list. Parameters hostname If set, then report the sessions running on that host. Otherwise report all sessions running on the subnet. Return value the number of sessions. public SessionInfo session list(long idx) Description Return the session info for the session with the given index. Parameters idx The index in the session list. Return value The session info. public int esim connect()

c Airbus Defence and Space 379 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Connect to a running simulation; a new journal file is opened. Return value 1 on success, 0 on failure.

public void esim disconnect() Description Disconnect from the simulation session. The simulator will continue to run in the background.

public void print monitored vars() Description Print a list of currently monitored variables and their current values. All variables in active monitors send values to the batch tool. A table with all variables is kept with their current values.

public void print session parameters() Description Print a complete overview of all available parameters.

public void print event list() Description Print a list of all events (messages) and parameters used in the communication between the test controller and the simulator.

public String script action(String name, String script, String condition) public String script action(String name, String script) Description Create an MDL script text. Parameters name The action name. script The action script. condition The optional condition. Return value The fully composed action script.

public String recorder action(String name, double freq, vector string vars) Description Create a recorder script. Parameters name The action name. freq The recorder frequency. vars A list of all variables to be recorded. Return value The fully composed recorder script.

380 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public String stimulus action(String name, String option, String filename, double freq, vector string vars) Description Create a stimulus script. Parameters name The action name. freq The stimulus frequency. option An option string (“soft”, “hard” or “cyclic”). filename The stimulus filename. vars A list of all variables to serve as stimulus. Return value The fully composed stimulus script. public long event list size() Description Return the size of the list of events present in the schedule. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Return value The size of the list of events. public EventInfo event list(long idx) Description Return the event info of the event with the given index. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Parameters idx The index in the event list (the first element has index 0). Return value Event info. public long where list size() Description Return the size of the current breakpoint list. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Return value The size of the list. public WhereInfo where list(long idx) Description Return the current breakpoint with the given index. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue.

c Airbus Defence and Space 381 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters idx The index in the current breakpoint list. Return value The breakpoint location.

public long task list size() Description Return the size of the task list. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Return value The size of the task list.

public TaskInfo task list(long idx) Description Return the task info for the task with the given index. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Parameters idx The index in the task list. Return value The task info

public long find task index(String taskname) Description Convert task name to index number. Parameters taskname The name of the task. Return value The index in the task list.

public vector string mdl list() Description Return a list of all loaded MDL files. MDL files are loaded at start-up when a .sim file is loaded or during run-time when extra MDL files are loaded. Extra files can be loaded by the event handler for event maNewMission or by manually adding MDL files with new scenario. Return value The list of MDL files.

public vector string action list(String mdl) Description Return a list with the names of all the actions.

382 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters mdl The name of the MDL file. Return value The list of action names. public vector string monitored vars() Description Return a list of all monitored variables. Return value The list of variables. public long event type list size() Description Return the size of the event messages table. Return value The number of event messages. public EventTypeInfo event type list(long idx) Description Return the event type info of event message idx. Parameters idx The index in the event messages table. Return value The event type info. public String sev to string(int sev) Description Return a string respresentation of a message severity Parameters sev Message severity Return value String representation of severity public int go(int sec, int nsec) public int go(int sec) public int go() Description Change the simulator state from stand-by to executing. Equivalent to the Go button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is specified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds)

c Airbus Defence and Space 383 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

public int stop(int sec, int nsec) public int stop(int sec) public int stop() Description Stop the simulation run. Equivalent to the Stop button of the test controller. The variant speci- fying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

public int pause(int sec, int nsec) public int pause(int sec) public int pause() Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

public int freeze(int sec, int nsec) public int freeze(int sec) public int freeze() Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

public int freeze at simtime(int sec, int nsec) public int freeze at simtime(int sec)

384 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Change the simulator state from executing to stand-by on the specified simulation time. The simulation time is secified as sec seconds and nsec nanoseconds. Parameters sec Simulation time (seconds) nsec Simulation time (nanoseconds) Return value 1 on success, 0 on failure. public int step() Description Perform one main scheduler cycle. Equivalent to the Step button of the test controller. Return value 1 on success, 0 on failure. public int abort() Description Abort the current simulation run. Equivalent to the Abort button of the test controller. Return value 1 on success, 0 on failure. public int health() Description Request a health check of the running simulator. Prints health information to the test controller. Return value 1 on success, 0 on failure. public int reset sim() Description Restart the current simulation with the current settings. Equivalent to the Reset button of the test controller. Return value 1 on success, 0 on failure. public int new scenario(String scen) Description Create a new scenario in the simulator. This new scenario is only a container for new actions. It is not a file on disk. It is a pure in core representation. Parameters scen The scenario name. Return value 1 on success, 0 on failure. public int open scenario(String scen)

c Airbus Defence and Space 385 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Open a new scenario file in the simulator with file name scen. The file must be on disk and readable. Parameters scen Scenario file name. Return value 1 on success, 0 on failure.

public int close scenario(String scen) Description Close a currently opened scenario with name scen in the simulator. Parameters scen Scenario file name. Return value 1 on success, 0 on failure.

public int new action(String scen, String action text) Description Add a new action in the scenario file with name scen. action text is the complete action text. There are a few utility functions to generate those actions. Parameters scen The scenario file name. action text The action text. Return value 1 on success, 0 on failure.

public int delete action(String scen, String action) Description Delete an action from scenario scen with name action. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

public int action execute(String scen, String action) Description Trigger the execution of the action with name action in scenario with name scen. This is equivalent to triggering an action manually on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

386 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public int action activate(String scen, String action) Description Make action with name action in scenario with name scen active in the running simulator. The action must already be defined in the scenario. This is equivalent to activating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure. public int action deactivate(String scen, String action) Description Deactivate action with name action in scenario with name scen in the running simulator. This is equivalent to deactivating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure. public int snapshot(String filename, String comment) public int snapshot(String filename) public int snapshot() Description Make a snapshot of the current state of the variables in the data dictionary. The comment string is optional. If you omit the filename, a filename is chosen of the form snapshot simtime.snap. The snapshot is saved in the output directory, unless the filename is absolute. This is equivalent to the “Take Snaphot...” menu option in the “Control” menu of the test controller. Parameters filename Path name of the snapshot file. comment Comment string Return value 1 on success, 0 on failure. public int mark(String comment) public int mark() Description Make a mark in the journal file. The comment string is optional. This is equivalent to the “Mark Journal” and “Comment Journal Mark” menu options in the “Insert” menu of the Simulation Controller. Parameters comment Comment string

c Airbus Defence and Space 387 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

public int sim message(String msg) Description Send a message to the simulator for distribution to all clients. This is useful if your client application is not the only client of the simulator. The message is broadcasted to all clients. Parameters msg Message string Return value 1 on success, 0 on failure.

public int suspend recording() Description Suspend recording in the simulator. This is equivalent to unchecking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure.

public int resume recording() Description Resume recording in the simulator. This is equivalent to checking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure.

public int recording switch() Description Switch all recording files of a simulation run. All currently open recorder files are closed and new recorder files are created. Recording will continue in the new recorder files. Return value 1 on success, 0 on failure.

public int reload(String snapfile, String hard) public int reload(String snapfile) Description Load initial condition file or snapshot file with file name snapfile into the running simulator. Parameter hard is by default “off”. This means that the simulation time stored in the snapshot file is ignored. If hard is set to “on”, the simulation time is set to the value specified in the snapshot file. Parameters snapfile Path name of snapshot file. hard “on” or “off”. Return value 1 on success, 0 on failure.

388 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public int set value(String var, String value) Description Set the value of a variable. Parameters var The data dictionary path name of variable you want to change. value The new value as string. To set an array variable write the value as a comma seperated list between curly brackets. For example: ::s set_value("/Thrusters/force","{1,2, 2, 3, 4, 5, 6, -2, 2}) The same applies for a struct with respect to fields. Nesting is possible too, a field of a struct that is an array would be a comma seperated list in curly brackets embedded in a comma seperated list in curly brackets as in: ::s set_value "/Thrusters/example" "{1,2, {1,5}, 3, 4,}" Return value 1 on success, 0 on failure. public int set values(VariableSet varset) Description Set the value for a list of variables in one command. The class VariableSet can hold a list of variable-value pairs. The advantage is a much faster handling for larger sets of variables. Parameters varset The instance that holds the list of variable-value pairs. VariableSet varset = new VariableSet(); varset.add("/Thrusters/force", "2"); varset.add("/Thrusters/torque", "3’); s set_values(varset); Return value 1 on success, 0 on failure. public String get value(String var) Description Get the value of a variable. Parameters var The data dictionary path name of the variable Return value The value, empty on failure public int cpuload set peak(int cpu, int peak time) Description Configure the CPU load monitor peak time in msecs. Parameters cpu CPU number peak time Peak time in seconds. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 389 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public int set breakpoint(String taskname, int entrynr, boolean enable) Description Set a breakpoint on entry nr entrynr in task taskname in the scheduler. If parameter enable is set to true the breakpoint is enabled. To disable it again set the parameter to false. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure.

public int set trace(String taskname, int entrynr, boolean enable) Description Enable/disable tracing of entry points. Entry points are defined by specifying the number of the entry point entrynr (numbering starts at 0) and the name of the task taskname. To enable a trace set enable to true, to disable it set it to false. Tracing an entry point means that messages are printed to the journal window. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure.

public int where() Description Request the current position when the scheduler has stopped on a break point. The reply to the message is automatically stored and can be retrieved by using where list. Normally the position is sent to the client whenever the scheduler hits a breakpoint. So there is rarely any need to request the position manually if you store the position on the client side (as is done in this tool.) Return value 1 on success, 0 on failure.

public int step task() Description Perform one step (=one entry point) in the scheduler debugger. Return value 1 on success, 0 on failure.

public int cont() Description Continue executing upto the next breakpoint in the scheduler debugger. Return value 1 on success, 0 on failure.

390 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public int task disable(String taskname) Description Disable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure. public int task enable(String taskname) Description Enable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure. public int clear breaks() Description Remove all breakpoints in the current schedule of the simulator. Return value 1 on success, 0 on failure. public int clear traces() Description Remove all traces in the current schedule of the simulator. Return value 1 on success, 0 on failure. public int set simtime(int sec, int nsec) public int set simtime(int sec) Description Set the simulation time to sec seconds and nsec nanoseconds. This can only be done in stand-by state. Parameters sec Simulation time in seconds. nsec Simulation time in nanoseconds. Return value 1 on success, 0 on failure. public int enable realtime() Description Switch to real-time mode. This can only be done when the simulator has started off in real-time mode, and has switched to non-real-time mode.

c Airbus Defence and Space 391 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

public int disable realtime() Description Switch to non-real-time mode. Return value 1 on success, 0 on failure.

public int list tasks() Description Request a list of all tasks in the current schedule of the simulator. The list is also sent automat- ically upon joining the “sched-control” channel. Return value 1 on success, 0 on failure.

public int list events() Description Request a list of all events in the schedule of the simulator in all states. The list is automatically sent to the client when subscribing to the “sched-control” channel at start-up. Return value 1 on success, 0 on failure.

public int raise event(String eventname, SWIGTYPE p void data, int size) public int raise event(String eventname) Description Raise event with name eventname in the scheduler. An event is defined by the input connector on the scheduler canvas. The event is handled as fast as possible. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

public int raise event at(String eventname, int sec, int nsec, SWIGTYPE p void data, int size) public int raise event at(String eventname, int sec, int nsec) public int raise event at(String eventname, int sec) Description Raise event with name eventname in the schedler at a specified wallclock time. The wallclock time is specified as sec seconds and nsec nanoseconds. Event data with a given size can option- ally be passed together with the event.

392 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters eventname Name of the event sec Wallclock time in seconds. nsec Wallclock time in nanoseconds. data Data size Size of data in bytes. Return value 1 on success, 0 on failure. public int raise event at simtime(String eventname, int sec, int nsec, SWIGTYPE p void data, int size) public int raise event at simtime(String eventname, int sec, int nsec) public int raise event at simtime(String eventname, int sec) Description Raise event with name eventname in the schedler at a specified simulation time. The simula- tion time is specified as sec seconds and nsec nanoseconds. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event sec Simulation time (seconds) nsec Simulation time (nanoseconds) data Data size Size of data in bytes. Return value 1 on success, 0 on failure. public int set speed(double speed) Description Set the acceleration/deceleration of the scheduler of the simulator. Values smaller than 1 will cause a proportional deceleration of the scheduler clock. Values larger than 1 will cause a proportional acceleration of the scheduler clock. Magical value -1 means that the scheduler will run in an optimized as-fast-as-possible mode. Parameters speed acceleration factor Return value 1 on success, 0 on failure. public int add MDL(String mdlname) Description Load (another) new MDL file in the session. Parameters mdlname Path name of the MDL file. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 393 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public int sync send(int token) Description Send sync token to simulator Parameters token synchronization token id Return value 1 on success, 0 on failure

public int sync recv(int token) Description Wait for sync token from simulator Parameters token synchronization token id Return value 1 on success, 0 on failure

public int kill(int signal) public int kill() Description Kill the simulator with signal signal. By default the simulator is killed with SIGTERM. Parameters signal Signal to send to the simulator Return value 1 on success, 0 on failure

25.3 EventHandler class

The EventHandler class is used to handle events coming from the simulator. The user must derive from this class and implement the methods for the events that must be handled. When a messsage from the simulator is received, first the built-in message handling is performed fol- lowed by the user defined message handlers. The message handlers are installed by instantiating the handler. The message handler is removed by calling the remove method. To define a user defined message handler all you need to do is: class ExampleEventHandler extends EventHandler {

// constructor public ExampleEventHandler(Session s) { super(s); }

// handler for maMessage events public void maMessage(int simtime_sec, int simtime_nsec, int runtime_sec, int runtime_nsec, int sev, String procname, String msg) { System.out.println(procname + " " + msg); }

394 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

}

ExampleEventHandler eh;

// instantiate event handler (implicitly installs it) void example_handler_init(Session s) { eh = new ExampleEventHandler(s); }

// remove event handler void example_handler_remove(Session s) { eh.remove(); }

25.3.1 Method reference 25.3.1.1 Constructors public EventHandler(Session s) Description Construct a new EventHandler and install the handler. Parameters s The simulator session

25.3.1.2 Methods public Session session() Description Return the session for this event handler. Return value The simulator session.

25.3.1.3 Event Handler Methods In order to create a user defined event handler, one or more methods must be implemented. public void maNewMission(String mission) Description A new mission (MDL) is created. Parameters mission The name of the mission. public void maOpenMission(String mission) Description A mission (MDL) file is opened. Parameters mission The filename of the mission file. public void maCloseMission(String mission)

c Airbus Defence and Space 395 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description A mission (MDL) file is closed. Parameters mission The filename of the mission file.

public void maSimDef(String simdef) Description Inform that client which simulation definition file is currently loaded. Parameters simdef The filename of the simulation definition file. Return value

public void maCurrentDict(String dict) Description Inform the client which data dictionary file is currently loaded. Parameters dict The filename of the data dictionary file. Return value

public void maCurrentWorkingDir(String cwd) Description Inform the client what the current working directory of the simulator is. Parameters cwd The path name of the current working directory.

public void maCurrentResultDir(String result dir) Description Inform the client what the result directory is. The result directory contains all the journal files, recorder files, snapshots and timings file. Parameters result dir The path name of the result directory.

public void maCurrentAliasFile(String filename) Description Inform the client what the alias file is. The alias file contains the data dictionary aliases. Parameters filename The path name of the alias file.

public void maNewAction(String mission, String actiontext) Description Inform the client that a new action has been created.

396 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters mission The name of the mission. actiontext The new action. public void maDeleteAction(String mission, String actionname) Description Inform the client that an action has been deleted. Parameters mission The name of the mission. actionname The name of the action. public void maActionExecute(String mission, String actionname) Description Inform the client that an action is being executed. Parameters mission The name of the mission. actionname The name of the action. public void maActionExecuteStop(String mission, String actionname) Description Inform the client that an action is no longer being executed. Parameters mission The name of the mission. actionname The name of the action. public void maActionExecuting(String mission, String actionname) Description Inform a newly connected client that the action is currently executing. Parameters mission The name of the mission. actionname The name of the action. public void maActionActivate(String mission, String actionname) Description Inform the client that an action has been activated. I.e. is allowed to execute. Parameters mission The name of the mission. actionname The name of the action. public void maActionDeActivate(String mission, String actionname) Description Inform the client that an action has been deactivated. I.e. is no longer allowed to execute. Parameters mission The name of the mission.

c Airbus Defence and Space 397 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

actionname The name of the action.

public void maExecuteCommand(String name, String command, int action mgr nr) Description Inform the client that a one shot action has been executed. Parameters name The name of the action. command The commands of the action. action mgr nr The number of the action manager that has executed the action.

public void maSnapshot(String snapshot, String comment) Description Handle maSnapshot event. This event is sent after a snapshot of the current simulator state has been made. Parameters snapshot Path name of the snapshot file. comment Comment describing the snapshot.

public void maMark(String message, int marknumber) Description Inform the client that a mark has been made in the journal file. Parameters message The descriptive message of the mark. marknumber The number of the mark.

public void maMessage(int simtime sec, int simtime nsec, int runtime sec, int runtime nsec, int sev, String process, String msg) Description Inform the client that a message has been generated in the simulator. This message is also automatically logged in the journal file by the simulator. Parameters simtime sec Simulation time stamp (seconds part) simtime nsec Simulation time stamp (nanoseconds part) runtime sec Wallclock time stamp (seconds part) runtime nsec Wallclock time stamp (nanoseconds part) sev Severity of the message. The name of the severity can be retrieved by using the sev_to_string() method of the Session class. process Name of the simulator thread from where the message was generated. msg The message text.

public void maRecording(String on off) Description Inform the client that recording has been globally enabled/disabled.

398 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters on off If the string is equal to “on”, recording is enabled. If it is “off” it is disabled. public void maRecordingBandwidth(double bandwidth) Description Report the bandwidth used to record data to disk. Parameters bandwidth Number of bytes per seconds written to disk. public void maStimulatorBandwidth(double bandwidth) Description Report the bandwidth used to read data from disk for stimulation. Parameters bandwidth Number of bytes per second read from disk. public void maRecorderFileClosed(String filename) Description Inform the client that a recorder file has been closed and can be used for further processing. Parameters filename The file name of the recorder file. public void maDenyWriteAccess(boolean denied) Description Inform the client that the write access to variables is denied. This is the case if the client has the role of observer. Parameters denied Flag to indicate denial of write access to the simulator variables. public void maCurrentInitconds(String simdef, String initconds) Description Inform the client of the current list of initial conditions as used for the initialization of the simulator. Parameters simdef The name of the simulation definition file. initconds The list of initial condition files (space separated). public void maCurrentCalibrations(String simdef, String calibrations) Description Inform the client of the current list of calibration definition files as used by the simulator. Parameters simdef The name of the simulation definition file. calibrations The list of calibration files (space separated). public void maCurrentTimeMode(int time mode)

c Airbus Defence and Space 399 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client of the current time mode. The time mode can be relative time or absolute time (UTC mode). Parameters time mode The time mode, 0 is relative time mode, 1 is absolute time mode (UTC mode).

public void maNewSeverity(int sev, String sev name) Description Inform the client about a new user-defined message severity. This message is automatically han- dled. The severity identifier can be mapped to its symbolic name using the sev_to_string() method of the Session class. Parameters sev The severity numerical identifier. sev name The symbolic name of the severity.

public void rtUnconfigured() Description Inform the client that the state of the simulator is unconfigured. This state means that the simulator is either still starting up, or is in its final clean up phase. This is a transient state. When starting up, the next state will be Initialising. When cleaning up the last event will be evShutdown.

public void rtInitialising() Description Inform the client that the state of the simulator is initialising. Depending on the schedule definition, this state will automatically be followed by the standby state. Otherwise you have to manually change the state to standby using the eventStandby() method of the Session() class.

public void rtStandby() Description Inform the client that the state of the simulator is standby.

public void rtExecuting() Description Inform the client that the state of the simulator is executing.

public void rtExiting() Description Inform the client that the state of the simulator is exiting. This is a transient state. The next state will be the unconfigured state.

public void rtTimeToNextState(int sec, int nsec) Description Report the time to the next state transition. This is useful when the major cycle is quite long (more than a couple of seconds). This can be the case if the schedule definition contains a clock with a very low frequency or when the lowest common denominator of the clocks results in a long major cycle.

400 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters sec Time to next state (seconds part) nsec Time to next state (nanoseconds part) public void rtMainCycle(int sec, int nsec) Description Report the length of the main cycle of the schedule. Parameters sec Main cycle (seconds part) nsec Main cycle (nanoseconds part) public void scSetBrk(String taskname, int entrynr, int enable) Description Inform the client about the enabling/disabling of a break point on a specific entry point in a task in the schedule. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). enable Whether the break point is enabled (1) or disabled (0). public void scStepTsk() Description Inform the client that a step to the next task has been performed in debugging mode. public void scContinue() Description Inform the client that the execution is now continued after being stopped on a break point in debugging mode. public void scGoRT(bool enable) Description Inform the client that the real-time mode has changed. Parameters enable Real-time mode is enabled (true) or disabled (false). public void scTaskDisable(String taskname, bool disable) Description Inform the client that a task has been disabled. This means that the task is no longer executed. Parameters taskname The name of the task. disable The task is disabled (true), or enabled again (false). public void scSetTrc(String taskname, int entrynr, bool enable)

c Airbus Defence and Space 401 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client that a trace has been set on an entry point in a task. Parameters taskname The name of the task. entrynr The number of the entry point in the task (counting starts at 0). enable The trace is enabled (true), or disabled (false).

public void scSpeed(double speed) Description Report the speed of the scheduler clock. This is only relevant in non-real-time mode when going slower or faster than real time. Parameters speed Speed factor. 1 means real-time, less than 1 means slower than real-time, more than 1 means faster than real-time. E.g. 2 means two times faster than real-time.

public void scTaskListStart() Description Start the description of the list of tasks.

public void scTaskStart(String taskname, bool enabled) Description Start the description of a task. This is followed by a number of scTaskEntry events, one for each entry in the order of execution in the task. Parameters taskname The name of the task enabled The task is enabled (true), or disabled (false).

public void scTaskEntry(String entryname, bool breakpoint, bool trace) Description Report information of an entry point in a task. Parameters entryname The name of the entry point. breakpoint The entry point has a break point set (true) or not set (false). trace The entry point is traced (true) or not (false).

public void scTaskEnd() Description Report the end of the task information.

public void scTaskListEnd() Description Report the end of the list of tasks.

public void scEventListStart()

402 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Report the start of the list of schedule events. public void scEventInfo(String eventname, int state, bool is standard) Description Report all information about a specific schedule event. Parameters eventname The name of the event. state The state in which it is present. is standard Whether or not it is a built-in (standard) event (true), or a user defined event (false). public void scEventListEnd() Description Report the end of the list of events. public void scWhereListStart() Description Report the start of the list of places where the scheduler has stopped execution when reaching a break point. As there are possibly more than 1 executers executing tasks, there can be multiple places where the execution has stopped. public void scWhereEntry(String taskname, int entrynr) Description Report a location where the execution has stopped. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). public void scWhereListEnd() Description End of the list of locations where the execution has stopped. public void scEntrypointSetEnabled(String entrypointname, bool enabled) Description Report the enabling or disabling of the execution of an entry point. The execution of the entry point is disabled for all tasks and also when executing the entry point from MDL scripts. Parameters entrypointname The name of the entry point. enabled Whether the entry point is enabled for execution (true), or disabled (false). public void dtLogValueUpdate(String var, String value) Description Report an updated value for a logged variable.

c Airbus Defence and Space 403 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters var The name of the variable. value The value of the variable.

public void dtHeartBeat() Description This event is sent at the speed of the non realtime action manager component, which is 5 Hz by default and indicates that the simulator is still alive. It is also the last event sent after a series of dtLogValueUpdate events.

public void dtCpuLoad(int cpu, double average, double peak) Description Report the load of a CPU. Parameters cpu CPU number average Average load over a main cycle. peak Peak load over a minor cycle.

public void evLinkData(String link id) Description Event that is used internally to transmit (TM/TC) packets. The actual data of the packet is not passed to this callback function. It is stored internally and can be retrieved using the read() method of the TmTcLink class. Parameters link id The symbolic name of the link.

void evExtNewView(String view id, String export id) Description Event that is used to confirm the creation of an external view by the simulator. Parameters view id The symbolic name of the view. export id The symbolic name of the exported view as defined in the exports file.

public void evExtSetData(String view id) Description Event that is used internally to update External Simulator Access views. The actual data of the event is not passed to this callback function. It is decoded and stored in the view variables and can be retrieved with the get() method of the ExtSimVar* classes. Parameters view id The symbolic name of the view.

public void evShutdown(int error code, String error string) Description Event that is received when the connection with the simulator is lost.

404 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters error code The value of errno at the time the connection was terminated. This value is zero when the connection was terminated in a normal way. error string The description of the error code. public void evEventDisconnect() Description Event that is received when the connection with the simulator is closed. This is normally done using the method esim_disconnect().

25.4 eurosim class

This class contains a couple of utility methods that are not linked to a session.

25.4.1 Method reference public static vector string host list() Description Return the list of EuroSim hosts. Return value The list of hosts. public static int session kill by name(String simname, int signal, String hostname) public static int session kill by name(String simname, int signal) public static int session kill by name(String simname) Description Kill a simulation session by name. Parameters simname The name of the session. This is normally the basename of the executable. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, other- wise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified name could not be found. public static int session kill by pid(int pid, int signal, String hostname) public static int session kill by pid(int pid, int signal) public static int session kill by pid(int pid) Description Kill a simulation session by pid. Parameters pid The process id of the session.

c Airbus Defence and Space 405 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, oth- erwise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified pid could not be found.

public int open log() Description Allows the client to log to a file. After opening the log file everything that is sent to stdout and to stderr is also logged to the spedified file. Return value 0 if succeeded.

public int close log() Description Closes the log file created by open_log. Return value 0 if succeeded.

25.5 EventInfo class

The EventInfo data is return by the event_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler event.

25.5.1 Method reference

public String name() Description Get the name of the event. Return value The name of the event

public int state() Description Get the number of the state where this event is defined. Return value The number of the state.

public String state name() Description Get the name of the state where this event is defined. Return value The name of the state.

public boolean is standard() Description Whether the event is a standard event or a user defined event. Return value true if it is a standard event, false if it is a user defined event.

406 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

25.6 WhereInfo class

The WhereInfo data is return by the where_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler break point location.

25.6.1 Method reference public String name() Description Get the name of the task where the scheduler is currently stopped. Return value The task name. public int entrynr() Description Get the entry point number of the current break point within the task. Return value The entry point number. Counting starts at 0.

25.7 EntryInfo class

The EntryInfo data is return by the entry_list method of the TaskInfo class. The methods allow you to retrieve the individual attributes of an entry point in a task.

25.7.1 Method reference public String name() Description Get the name of the entry point. Return value The name of the entry point. public boolean breakpoint() Description Get the break point status of the entry point. Return value True if a break point is set, false if not. public boolean trace() Description Get the trace status of the entry point. Return value True if a trace is set, false if not.

25.8 TaskInfo class

The TaskInfo data is return by the task_list method of the Session class. The methods allow you to retrieve the individual attributes of a task.

c Airbus Defence and Space 407 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

25.8.1 Method reference

public String name() Description Get the name of the task. Return value The name of the task.

public boolean disabled() Description Get the disabled state of the task. Return value True if the task is disabled, false if it is enabled.

public long entry list size() Description Get the number of entry points of the task. Return value The number of entry points.

public EntryInfo entry list(long idx) Description Get the entry point information of the entry point with the given index. Parameters idx The entry point index (counting starts at 0). Return value The entry point information.

25.9 EventTypeInfo class

The EventTypeInfo data is return by the event_type_list method of the Session class. The methods allow you to retrieve the individual attributes of a client/server message (called event internally).

25.9.1 Method reference

public String name() Description Get the name of the message. Return value The name of the message.

public String args() Description Get the argument types of the message. This is a character coded string with one character for each argument type.

408 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The argument types. public String argdescr() Description Get a description of the arguments of the message. Return value The description of the arguments. public int id() Description Get the numerical identifier of the message. Return value The numerical identifier.

25.10 SessionInfo class

The SessionInfo data is return by the session_list method of the Session class. The methods allow you to retrieve the individual attributes of a simulation session.

25.10.1 Method reference public String sim hostname() Description Get the host name running the simulation session. Return value The host name. public String sim() Description Get the simulation definition file. Return value The file name of the simulation definition file. public String workdir() Description Get the working directory. Return value The path name of the working directory. public String simulator() Description Get the simulator executable. Return value The path name of the executable.

c Airbus Defence and Space 409 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public String schedule() Description Get the simulator schedule. Return value The path name of the schedule file.

public vector string scenarios() Description Get the list of scenario (MDL) files. Return value The list with path names of the MDL files.

public String dict() Description Get the data dictionary file. Return value The path name of the data dictionary file.

public String model() Description Get the model file. Return value The path name of the model file.

public String recorderdir() Description Get the recorder directory. Return value The path name of the recorder directory.

public vector string initconds() Description Get the list of initial condition files. Return value The list of path names of the initial condition files.

public vector string calibrations() Description Get the list of calibration files. Return value The list of path names of the calibration files.

public String exports()

410 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Get the exports file. Return value The path name of the exports file. public String alias() Description Get the alias file. Return value The path name of the alias file. public String timestamp() Description Get the time stamp. Return value The time stamp. public int prefcon() Description Get the connection number. Each session has a connection number that can be used to connect a client to that session. Return value The connection number. public int uid() Description Get the UNIX user id of the user who started the simulator. Return value The user id. public int gid() Description Get the UNIX group id of the user who started the simulator. Return value The group id. public int pid() Description Get the UNIX process id of the simulation session. Return value The process id. public boolean realtime() Description Get the real-time state of the simulation session. Return value True if the simulator was started in real-time mode, false if it was started in non-real-time mode.

c Airbus Defence and Space 411 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

25.11 TmTcLink class

The TmTcLink class is used to create a packet link with a model in the simulator. The packet link can be used to send arbitrary packets (binary or not) to a simulator model and receive packets from a simulator model. Multiple packet links can be created. See Chapter 33 for detailed information on how to use the link.

25.11.1 Constructors

public TmTcLink(String id, String mode) Description Open one end of a TmTc link. Parameters id The symbolic name of the TmTc link. mode Mode is “r”, “w” or “rw”, similar to the modes of the fopen() function in the standard C library.

25.11.2 Method reference

public int connect(Session s) Description Connect the link to the other end in a running simulator. Parameters s The session of the running simulator. Return value -1 on failure, 0 on success.

public int write(String data) Description Write a packet to the link. Parameters data The data (binary string). Return value The number of bytes sent or -1 on failure.

public ByteArray read() Description Read data from the link. Return value The data read as a byte array.

25.12 InitCond class

This class is used for the manipulation of initial condition files. This allows the user to create a new initial condition file or modify an existing file. Individual values can be set or modified. It is also possible to merge two initial condition files.

412 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

25.12.1 Constructors public InitCond(String filename, String dictfile) Description Create a new set of initial conditions from an existing file. Parameters filename The initial condition file. dictfile The path of the data dictionary file.

25.12.2 Method reference public boolean add(String filename) Description Merge an existing initial condition file with the current initial condition data. Parameters filename The path of the to-be-merged initial condition file. Return value true on success, false on failure. public boolean write(String filename, boolean binary) Description Write the initial condition data to a file. Parameters filename The path of the new initial condition file. binary If true, write a binary file, otherwise write the data in human readable (ASCII) format. Return value true on success, false on failure. public double simtime() Description Return the simulation time of the initial condition file. Return value The simulation time. public String comment() Description Get the comment of in the initial condition file. Return value The comment string. public vector string get varlist failed() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary.

c Airbus Defence and Space 413 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value The list of variables.

public vector string get varlist set() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables.

public double var value get(String path) Description Get the numerical value of a variable. Parameters path The data dictionary path. Return value The numerical value of the variable.

public String var string get(String path) Description Get the string value of a variable. Parameters path The data dictionary path. Return value The string value of the variable.

public boolean var value set(String path, double value) Description Set the numerical value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure.

public boolean var string set(String path, String value) Description Set the string value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure.

414 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

public vector string list(String path) public vector string list() Description Get a list of child node names beneath a parent node. Parameters path The path of the parent node (default the root “/”). Return value The list of child node names.

25.13 ExtSimView class

This class wraps the External Simulator Access interface. Detailed information on the use of this inter- face can be found in Chapter 32.

25.13.1 Constructors public ExtSimView(Session session, String id) Description Create a new External Simulator Access view. Parameters session The simulation session. id The symbolic identifier of the view.

25.13.2 Method reference public int add(ExtSimVar var) Description Add a variable to this view. Parameters var The variable to add to the view. Return value 0 on success, -1 on failure.

\bigskip \hrule \cxx{string}{get\_export\_id}{} \begin{method} \property[Description] Get the ˆexport_idˆ of this view \property[Return value] the ˆexport_idˆ \end{method}

\bigskip \hrule \cxx{string}{get\_view\_id}{} \begin{method} \property[Description] Get the ˆview_idˆ of this view \property[Return value] the ˆview_idˆ \end{method}

c Airbus Defence and Space 415 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

public int connect(int rw flags, double frequency, int compression) Description Create a new view with the variables previously added to the view. Note that an excessive ammount of variables on the view might cause memory issues when calling connect. In such cases, increase the stack size of the host thread accordingly or spread the variables over multiple views. Parameters rw flags Read/write flags, 1 is read, 2 is write. frequency Update frequency in Hz. compression Compression type to be used for the data transmission. 0 is no compression, 1 means that unchanched values in the view are not transmitted. Please note that in case the whole view is not changed, no update is sent in any case. Return value 0 is success, -1 is failure. This only is a local return value. The simulator emits a message evExtNewView with view id and export id as arguments on succesful creation of the requested view.

public int change freq(double frequency) Description

Parameters Change the update frequency of the view.

frequency The update frequency in Hz. Return value 0 is success, -1 is failure.

public int send() Description Send the view with the updated values to the simulator. Return value 0 is success, -1 is failure.

25.14 ExtSimVar class

This is the base class of the ExtSimVar* classes. It is not to be used directly.

25.14.1 Method reference

public ExtSimVar.extvar t type() Description Get the variable type. Return value The variable type.

public boolean is array()

416 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Find out if the variable is an array variable. Return value true if it is an array. public boolean is fortran() Description Find out if the variable is a Fortran variable. Only relevant for arrays, as the Fortran column/row order is different from C/Ada. Return value true if it is a Fortran variable. public int nof dims() Description Get the number of dimensions of the array variable. Return value The number of array dimensions. public SWIGTYPE p int dims() Description Get the dimensions of the array variable. Return value The array dimensions. public String path() Description Get the data dictionary path of the variable. Return value The data dictionary path. public long size() Description Get the size in bytes of the variable. Return value The size in bytes.

25.15 ExtSimVar* classes

Below are the derived classes of ExtSimVar described. All similar methods are grouped to reduce the amount of documentation that only repeats the same information again and again. Therefore only two different cases are documented. One for the single element case and one for the array case. For both cases the following variants are possible: Char, Double, Float, Int, Long, Short, UnsChar, UnsInt, UnsLong and UnsShort. The java types corresponding to the above types are: char, double, float, int, int, short, short, long, long and int. For arrays there are two variants: ExtSimVar*Array and ExtSimVar*FortranArray. To summarize for one type you can have the following classes: ExtSimVarChar, ExtSimVarCharArray and ExtSimVarCharFortranArray.

c Airbus Defence and Space 417 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

25.15.1 Constructors

public ExtSimVar*(String path) public ExtSimVar*Array(String path, int dim0) public ExtSimVar*Array(String path, int dim0, int dim1) public ExtSimVar*Array(String path, int dim0, int dim1, int dim2) public ExtSimVar*FortranArray(String path, int dim0) public ExtSimVar*FortranArray(String path, int dim0, int dim1) public ExtSimVar*FortranArray(String path, int dim0, int dim1, int dim2) Description Create a new variable to be used in an ExtSimView. Parameters path The data dictionary path dim0 The size of the first dimension. dim1 The size of the second dimension. dim2 The size of the third dimension.

25.15.2 Method reference

public * get() public * get(int idx0) public * get(int idx0, int idx1) public * get(int idx0, int idx1, int idx2) Description Get the value of a single variable or single array element. The variant without the idx* param- eters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension. Return value The value of the variable. The type of the return value depends on the type of the function. The type mapping is listed above in the introduction.

public void set(* val) public void set(* val, int idx0) public void set(* val, int idx0, int idx1) public void set(* val, int idx0, int idx1, int idx2) Description Set the value of a single variable or single array element. The variant without the idx* parame- ters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters val The new value. The type of the value depends on the type of the function. The type mapping is listed above in the introduction. idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension.

418 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 26

Python batch reference

26.1 Introduction

This chapter provides details on the batch utility for the python scripting language. Various python classes have been created that provide an interface to existing EuroSim libraries. This means that a batch application is no more than an ordinary python script using EuroSim classes. These classes offer the same capabilities to a script language as the Simulation Controller to an operator. Writing a script is therefore much like programming an operator, including waiting for changes and handling events, checking and setting variable values, and even inserting and controlling MDL scripts. These capabilities allow complete simulation runs to be automated, which can for instance be used for unit and system testing, both on demand and in nightly regression runs. It can also be used in combination with manual operation, for instance to automate the startup of complex simulators, allowing multiple programs and hardware to be booted and then starting the Simulation Controller in an attached state for the operator. The Python script interface is generated using SWIG and wraps the C++ client interface provided by EuroSim. The same interface is also available for Java and Tcl. Note that the EuroSim Perl interface is not generated via SWIG and though it follows the same concept it differs in interface and capabilities. The batch utility for python consists of various classes. Each class (or group of classes) is described in a separate chapter. The most important classes are the Session and EventHandler classes.

26.2 Session class

The Session class is the central class used to automate simulations. Its methods wrap the EuroSim dae- mon interface to launch and connect to simulators, as well as the EuroSim ”EventConnection” network protocol to control a running simulator. For sending EventConnection messages to the simulator, the Session class provides a method for each possible command to easily fill the event structure and sends it to the simulator. For handling incoming events generated by the simulator, the Session class supports both a callback mechanism to handle each type of event, as well as the means to blocking wait for a spe- cific message. Both mechanisms are based on the wait_event method of the Session class. This method processes received events from the EventConnection socket until it either encounters a specific event, exceeds a timeout or the socket buffer is exhausted. While processing events the wait_event method will call for each event the associated event handler routine which is either a default handler or a user installed handler. In Python installation of user defined event handlers can be achieved by instantiating an object of a class that is derived from the EuroSim EventHandler class. The wait_event method is thus the single interface through which the user’s script controls when events are processed and which assures that such processing does not occur in parallel to the execution of the user’s script. The event handler mechanism thereby assures that all incoming events can be handled, even when waiting for a specific event and/or amount of time. When only using event handlers, the user would call wait_event without arguments to process each received event until the socket is exhausted. When wanting to blocking wait for a specific event the user would call wait_event with the name of the

c Airbus Defence and Space 419 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

specific event to wait for. The wait_event call will not return until the event occured. A second timeout argument can be provided to limit the amount of time that is waited for the occurence of the event. The result of wait_event indicites if the specified event occurred. By only providing the timeout the processing of events continues for the specified amount of wallclock time. Note that this wallclock time increases based on the wallclock timestamps in the received events, which is thus limited in resolution but is guaranteed to be at least updated with 5Hz (heartbeat messages). The potential events that can be received are documented in detail in Chapter 31. Following is an example of how to start a simulator and wait indefinitely until it achieves Standby state. s = eurosim.Session("some.sim") # load simulation definition s.init() # start simulator s.wait_event("rtStandby"); # wait for the simulator to # achieve standby state

As shown in the example, similar information is passed to the Session methods as needed by the Simu- lation Controller. In the Simulation Controller a simulation definition file (.sim) is opened and then the simulator is launched using the Init button. The Simulation Controller then automatically connects to the simulator and processes events in a predefined manner. The example illustrates that in the same manner the constructor for a Session is passed the simulation definition file and the init method launches the simulator and connects when it is ready. The details of this connection are stored in the session class and can be printed with the print_session_parameters method. In the example it is chosen to blocking wait for the occurance of the rtStandby event which is transmitted by the simulator when it enters standby state. We could have also added a timout argument (in msec) to limit the amount of time that the script is allowed to wait for the event in order to provide an escape for situations where the simulator has a startup problem. However, in the mean time the wait_event method also encounters events from the simulator that we may want to handle, for instance resonding to an error event by printing the error messages. For this we need to install an event handler which will force the execution of a user defined callback function when the wait_event encounters the associated event. Note that these callbacks are thus not executed in parallel to the script execution. Although callbacks are associated with asynchronous behavior, they are only called from within the context of a wait_event. In python, a user defined event handler is installed by creating an object of a class that is derived from the EuroSim EventHandler class. The constructor of the class automatically installs the event handler in the Session class. To remove an event handler, just delete the created event handler object and it unregisters itself. See Section 26.3 for detailed information on each event handler class method.

26.2.1 Monitoring variables

In order to monitor variables you must call the method monitor_add with the variable you want to monitor. The variable parameter is in the form of a valid EuroSim data dictionary path. This method will add the variable to the list of variables monitored in EuroSim. The value of each variable will be updated with the asynchronous action manager frequency, which defaults to 5 Hz if they change. If there is no change, no update is sent. The values of the variables are stored in the Session class. To get the value of a variable use the following expression: s.monitor_value(var_path). The value is always returned as a string. To stop monitoring a variable you must call the function monitor_remove with the variable you want to stop monitoring. If you only want to get the value of a variable once, it is better to call the function get_value. This function retrieves the value of the variable immediately from the simulator, but only once. The value of the variable is returned as a string.

420 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

26.2.2 Modifying variables

If you want to change the value of a variable in the simulator you can simply call set_value with the name and value (as a string) of the variable. The value will be set as soon as possible in the simulator. Calling set_value also works on an array of variables or struct in its entirety and will set these values atomically. To set different variables atomically one API call, use set_values. The argument is an instance of class VariableSet in the eurosim namespace. Variable value pairs can be added to this VariableSet instance using its add function, which takes the variable path and value string as arguments. The benefit of this approach is a much quicker execution time as the client will send the value pairs in one message to the simulator and wait for confirmation. Using set_value the client will send one message and wait for confirmation, which then must be repeated for each variable.

26.2.3 Method reference 26.2.3.1 Constructors

Session([sim[, hostname]]) Description Creates a EuroSim simulation session by loading the given simulation definition file sim. The simulation run will be started on the host with the given hostname or on the current host if not specified. Parameters sim the simulation definition file name hostname the name of the host on which to run the simulator

26.2.3.2 Methods cwd() Description Returns the path name of the current working directory of the simulator. The value is set by the event handler for event maCurrentWorkingDir. Return value Path name of the current working directory dict() Description Returns the path name of the EuroSim data dictionary of the simulator. The value is set by the event handler for event maCurrentDict. Return value Path name of the EuroSim data dictionary outputdir() Description Returns the path name of the directory where the output files of the simulator are stored (journal file, recorder files, etc.) The value is set by the event handler for event maCurrentResultDir. Return value Path name of the output directory

c Airbus Defence and Space 421 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

state() Description Returns the simulator state. Can be: unconfigured, initialising, stand-by, executing, exiting. The value is set by the event handler for the following events: rtUnconfigured, rtInitialising, rtStandby, rtExecuting and rtExiting. Return value Simulator state

set remote path() Description If client and server have different paths (e.g. A Windows client launching a simulator on a linux server) set_remote_path can be used to set the root path of the simulator in the remote EuroSim server. Return value New paths for the simulator.

journal() Description Returns the path name of the journal file. Return value Path name of the journal file

schedule() Description Returns the path name of the schedule file. Return value Path name of the schedule file

exports() Description Returns the path name of the exports file. Return value Path name of the exports file

alias([alias]) Description Set or get the alias file name. Parameters alias Override the alias file specified in the SIM file. If alias was not specified, then the alias file remains unchanged. Return value Path name of the alias file. If the simulation is running, then the value is set by the event handler for event maCurrentAliasFile.

422 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

model() Description Returns the path name of the model file. Return value Path name of the model file recording bandwidth() Description Returns the recorder bandwidth in bytes/second. The value is set by the event handler for event maRecordingBandwidth. Return value Recorder bandwidth in bytes/second stimulator bandwidth() Description Returns the stimulator bandwidth in bytes/second. The value is set by the event handler for event maStimulatorBandwidth. Return value Stimulator bandwidth in bytes/second speed() Description Returns the clock acceleration factor achieved by the simulator. Values larger than 1 indicate faster than real-time. Values smaller than 1 indicate slower than real-time. The value is set by the event handler for event scSpeed. Return value Acceleration factor sim time() Description

Description Returns the simulation time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Simulation time in seconds wallclock time() Description Returns the wallclock time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Wallclock time in seconds

c Airbus Defence and Space 423 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

wallclock boundary() Description Returns the wallclock boundary time to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Wallclock time boundary in seconds

simtime boundary() Description Returns the simulation time boundary to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Simulation time boundary in seconds

main cycle() Description Returns the main cycle time of the current schedule. It can be used to calculate valid boundary times for timed state transitions. Return value Main cycle in seconds.

recording() Description Returns the flag indicating that recording is enabled or not. True means enabled, false means disabled. The value is set by the event handler for event maRecording. Return value Recording is enabled

write access() Description Returns the flag to indicate whether this client is allowed to change variable values in the sim- ulator. The value is set by the event handler for event maDenyWriteAccess. Return value Client is allowed to change variables

time mode() Description Returns the time mode. It can be relative or absolute (UTC). Relative is 0 and absolute is 1. The value is set by the event handler for event maCurrentTimeMode. Return value Time mode

424 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

realtime([realtime]) Description Set or get the realtime mode. Parameters realtime If the realtime mode is not specified, then the realtime mode is not set. If realtime is 0, then realtime mode is disabled, otherwise it is enabled. The new setting will not effect an already running simulation. Return value The realtime mode, true for realtime, false for non-realtime. If a simulation is running, then the value as was set by the event handler for event scGoRT is reported. Non-realtime is the default. auto init([auto init]) Description Set or get the auto initialization flag. Parameters auto init If the auto initialization flag is not specified, then the auto initialization flag is not set. If auto init is 0, then the simulator will not go automatically to initializing state on startup, otherwise it will go automatically to initializing (this is the default). The new setting will not effect an already running simulation. Return value The auto init flag, true if the state transition to initializing state is performed automatically, false if it isn’t. Automatic state transition to initializing is the default. prefcon([prefcon]) Description Set or get the preferred connection. Parameters prefcon The preferred connection. This can be used in a situation where you need to reconnect to an already running simulator. To start new simulation runs, this number is not used. If prefcon was not specified, then the preferred connection is not set. Return value Return the connection number of the current simulation session. startup timeout([timeout]) Description Set or get the startup timeout. The startup timeout default is 5 seconds. If starting up a simulator takes longer than this you must change that default to a higher value. If timeout was not specified, then the startup timeout is not set. Parameters timeout The startup timeout. Return value Return the startup timeout in seconds of the current simulation session.

c Airbus Defence and Space 425 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

clientname([clientname]) Description Set or get the name under which this session is known to the simulator. Parameters clientname The client name of the current simulation session. The default is “esimbatch”. If clientname was not specified, then the client name is not changed. Return value Return the client name of the current simulation session.

initconds([initconds]) Description Set or get the initial condition files. Parameters initconds Override the initial condition files specified in the SIM file. If initconds was not specified, then the initial condition files remain unchanged. Return value Initial condition files. If the simulation is running, then the value is set by the event handler for event maCurrentInitconds.

calibrations([calibrations]) Description Set or get the calibration files. Parameters calibrations Override the calibration files specified in the SIM file. If calibrations was not specified, then the calibration files remain unchanged. Return value Calibration files. If the simulation is running, then the value is set by the event handler for event maCurrentCalibrations.

workdir([workdir]) Description Set or get the work directory. Parameters workdir Use this directory as the work or project directory instead of the current directory. Return value The work directory.

user defined outputdir([outputdir]) Description Set or get the user defined output directory. Parameters outputdir Use this output directory instead of the default date/time directory. If not set, then the user defined output directory is not changed.

426 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The user defined output directory. hostname([hostname]) Description Set or get the EuroSim server hostname. Parameters hostname Use this EuroSim server. If not set, then the hostname is not changed. Return value The EuroSim server hostname. sim([sim[, hostname]]) Description Set or get the simulation definition file. This simulation definition file is used to start the simulator. Information derived from the sim- ulation definition file is used to provide sensible defaults for all parameters. Parameters sim The simulation definition file. If not set, then the simulation definition is not changed. hostname The EuroSim server hostname. If not set, then the local host is used instead. Return value The filename of the simulation definition file. init() Description Start a new simulation run. Return value 1 on success, 0 on failure. join channel(channel) Description Join a channel of a simulation session. By default each session connects to all channels. The following channels are available: mdlAndActions, data-monitor, rt-control, sched-control. To join all channels use channel “all”. Parameters channel The channel to join. Return value 1 on success, 0 on failure. leave channel(channel) Description Leave a channel of a simulation channel. Parameters channel The channel that you want to leave. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 427 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

wait event(event, timeout ms) Description Wait for an incoming event This function is used to wait synchronously for the given event. The timeout is used to limit the amount of time to wait for this event. Parameters event The name of the event to wait for. If the event name is empty this function can be used to read all pending events while waiting for the given amount of time. timeout ms The timeout in milliseconds. A value of -1 means that this this function will wait until the event arrives for an unlimited amount of time. A value of 0 means that the function will return immediately even if the event has not arrived yet. Return value true if the event had arrived, false if it has not.

monitor add(var) Description Monitor a variable. The value of the variable is updated with the frequency of the asynchronous action manager which defaults to 5 Hz. Parameters var The variable from the data dictionary that you want to monitor. Return value 1 on success, 0 on failure.

monitor value(var) Description Retrieve the value of a monitored variable Parameters var The name of the monitored variable. Return value the value of the variable

monitor remove(var) Description Remove the monitor of a variable. Parameters var The variable from the data dictionary that should be removed from the monitor list. Return value 1 on success, 0 on failure.

create session list([hostname]) Description Create a list of all sessions and return the size of that list.

428 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters hostname If set, then report the sessions running on that host. Otherwise report all sessions running on the subnet. Return value the number of sessions. session list(idx) Description Return the session info for the session with the given index. Parameters idx The index in the session list. Return value A SessionInfo object. esim connect() Description Connect to a running simulation; a new journal file is opened. Return value 1 on success, 0 on failure. esim disconnect() Description Disconnect from the simulation session. The simulator will continue to run in the background. print monitored vars() Description Print a list of currently monitored variables and their current values. All variables in active monitors send values to the batch tool. A table with all variables is kept with their current values. print session paramters() Description Print a complete overview of all available parameters. print event list() Description Print a list of all events (messages) and parameters used in the communication between the test controller and the simulator. script action(name, script[, condition]) Description Create an MDL script text. Parameters name The action name. script The action script.

c Airbus Defence and Space 429 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

condition The optional condition. Return value The fully composed action script.

recorder action(name, freq, vars) Description Create a recorder script. Parameters name The action name. freq The recorder frequency. vars A list of all variables to be recorded. Return value The fully composed recorder script.

stimulus action(name, option, filename, freq, vars) Description Create a stimulus script. Parameters name The action name. freq The stimulus frequency. option An option string (“soft”, “hard” or “cyclic”). filename The stimulus filename. vars A list of all variables to serve as stimulus. Return value The fully composed stimulus script.

event list size() Description Return the size of the list of events present in the schedule. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Return value The size of the list of events.

event list(idx) Description Return the event info of the event with the given index. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Parameters idx The index in the event list (the first element has index 0). Return value An EventInfo object.

where list size()

430 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Return the size of the current breakpoint list. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Return value The size of the list. where list(idx) Description Return the current breakpoint with the given index. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Parameters idx The index in the current breakpoint list. Return value A WhereInfo object describing the break point location. task list size() Description Return the size of the task list. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Return value The size of the task list. task list(idx) Description Return the task info for the task with the given index. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Parameters idx The index in the task list. Return value A TaskInfo object. find task index(taskname) Description Convert task name to index number. Parameters taskname The name of the task. Return value The index in the task list.

c Airbus Defence and Space 431 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

mdl list() Description Return a list of all loaded MDL files. MDL files are loaded at start-up when a .sim file is loaded or during run-time when extra MDL files are loaded. Extra files can be loaded by the event handler for event maNewMission or by manually adding MDL files with new scenario. Return value The list of MDL files.

action list(mdl) Description Return a list with the names of all the actions. Parameters mdl The name of the MDL file. Return value The list of action names.

monitored vars() Description Return a list of all monitored variables. Return value The list of variables.

event type list size() Description Return the size of the event messages table. Return value The number of event messages.

event type list(idx) Description Return the event type info of event message idx. Parameters idx The index in the event messages table. Return value An EventTypeInfo object.

sev to string(sev) Description Return a string respresentation of a message severity Parameters sev Message severity Return value String representation of severity

432 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

go([sec[, nsec]]) Description Change the simulator state from stand-by to executing. Equivalent to the Go button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is specified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. stop([sec[, nsec]]) Description Stop the simulation run. Equivalent to the Stop button of the test controller. The variant speci- fying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. pause([sec[, nsec]]) Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. freeze([sec[, nsec]]) Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. freeze at simtime(sec[, nsec])

c Airbus Defence and Space 433 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Change the simulator state from executing to stand-by on the specified simulation time. The simulation time is secified as sec seconds and nsec nanoseconds. Parameters sec Simulation time (seconds) nsec Simulation time (nanoseconds) Return value 1 on success, 0 on failure.

step() Description Perform one main scheduler cycle. Equivalent to the Step button of the test controller. Return value 1 on success, 0 on failure.

abort() Description Abort the current simulation run. Equivalent to the Abort button of the test controller. Return value 1 on success, 0 on failure.

health() Description Request a health check of the running simulator. Prints health information to the test controller. Return value 1 on success, 0 on failure.

reset sim() Description Restart the current simulation with the current settings. Equivalent to the Reset button of the test controller. Return value 1 on success, 0 on failure.

new scenario() Description Create a new scenario in the simulator. This new scenario is only a container for new actions. It is not a file on disk. It is a pure in core representation. Parameters scen The scenario name. Return value 1 on success, 0 on failure.

open scenario(scen)

434 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Open a new scenario file in the simulator with file name scen. The file must be on disk and readable. Parameters scen Scenario file name. Return value 1 on success, 0 on failure. close scenario(scen) Description Close a currently opened scenario with name scen in the simulator. Parameters scen Scenario file name. Return value 1 on success, 0 on failure. new action(scen, action text) Description Add a new action in the scenario file with name scen. action text is the complete action text. There are a few utility functions to generate those actions. Parameters scen The scenario file name. action text The action text. Return value 1 on success, 0 on failure. delete action(scen, action) Description Delete an action from scenario scen with name action. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure. action execute(scen, action) Description Trigger the execution of the action with name action in scenario with name scen. This is equivalent to triggering an action manually on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 435 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

action activate(scen, action) Description Make action with name action in scenario with name scen active in the running simulator. The action must already be defined in the scenario. This is equivalent to activating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

action deactivate(scen, action) Description Deactivate action with name action in scenario with name scen in the running simulator. This is equivalent to deactivating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

snapshot([filename[, comment]]) Description Make a snapshot of the current state of the variables in the data dictionary. The comment string is optional. If you omit the filename, a filename is chosen of the form snapshot simtime.snap. The snapshot is saved in the output directory, unless the filename is absolute. This is equivalent to the “Take Snaphot...” menu option in the “Control” menu of the test controller. Parameters filename Path name of the snapshot file. comment Comment string Return value 1 on success, 0 on failure.

mark([comment]) Description Make a mark in the journal file. The comment string is optional. This is equivalent to the “Mark Journal” and “Comment Journal Mark” menu options in the “Insert” menu of the Simulation Controller. Parameters comment Comment string Return value 1 on success, 0 on failure.

sim message(msg)

436 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Send a message to the simulator for distribution to all clients. This is useful if your client application is not the only client of the simulator. The message is broadcasted to all clients. Parameters msg Message string Return value 1 on success, 0 on failure. suspend recording() Description Suspend recording in the simulator. This is equivalent to unchecking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure. resume recording() Description Resume recording in the simulator. This is equivalent to checking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure. recording switch() Description Switch all recording files of a simulation run. All currently open recorder files are closed and new recorder files are created. Recording will continue in the new recorder files. Return value 1 on success, 0 on failure. reload(snapfile[, hard]) Description Load initial condition file or snapshot file with file name snapfile into the running simulator. Parameter hard is by default “off”. This means that the simulation time stored in the snapshot file is ignored. If hard is set to “on”, the simulation time is set to the value specified in the snapshot file. Parameters snapfile Path name of snapshot file. hard “on” or “off”. Return value 1 on success, 0 on failure. set value(var, value) Description Set the value of a variable. Parameters var The data dictionary path name of variable you want to change.

c Airbus Defence and Space 437 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

value The new value as string. To set an array variable write the value as a comma seperated list between curly brackets. For example: ::s set_value "/Thrusters/force" "{1,2, 2, 3, 4, 5, 6, -2, 2}" The same applies for a struct with respect to fields. Nesting is possible too, a field of a struct that is an array would be a comma seperated list in curly brackets embedded in a comma seperated list in curly brackets as in: ::s set_value "/Thrusters/example" "{1,2, {1,5}, 3, 4,}" Return value 1 on success, 0 on failure.

int(set values)eurosim::VariableSet varset Description Set the value for a list of variables in one command. The class VariableSet can hold a list of variable-value pairs. The advantage is a much faster handling for larger sets of variables. Parameters varset The instance that holds the list of variable-value pairs. varset = eurosim.VariableSet; varset.add("/Thrusters/force", "2"); varset.add("/Thrusters/torque", "3’); self.s.set_values(varset); Return value 1 on success, 0 on failure.

get value(var) Description Get the value of a variable. Parameters var The data dictionary path name of the variable Return value The value, empty on failure

cpu load set peak(cpu, peak time) Description Configure the CPU load monitor peak time in msecs. Parameters cpu CPU number peak time Peak time in seconds. Return value 1 on success, 0 on failure.

set breakpoint(taskname, entrynr, enable) Description Set a breakpoint on entry nr entrynr in task taskname in the scheduler. If parameter enable is set to true the breakpoint is enabled. To disable it again set the parameter to false.

438 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure. set trace(taskname, entrynr, enable) Description Enable/disable tracing of entry points. Entry points are defined by specifying the number of the entry point entrynr (numbering starts at 0) and the name of the task taskname. To enable a trace set enable to true, to disable it set it to false. Tracing an entry point means that messages are printed to the journal window. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure. where() Description Request the current position when the scheduler has stopped on a break point. The reply to the message is automatically stored and can be retrieved by using where list. Normally the position is sent to the client whenever the scheduler hits a breakpoint. So there is rarely any need to request the position manually if you store the position on the client side (as is done in this tool.) Return value 1 on success, 0 on failure. step task() Description Perform one step (=one entry point) in the scheduler debugger. Return value 1 on success, 0 on failure. cont() Description Continue executing upto the next breakpoint in the scheduler debugger. Return value 1 on success, 0 on failure. task disable(taskname) Description Disable task with name taskname in the current schedule of the simulator.

c Airbus Defence and Space 439 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters taskname Name of the task. Return value 1 on success, 0 on failure.

task enable(taskname) Description Enable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure.

clear breaks() Description Remove all breakpoints in the current schedule of the simulator. Return value 1 on success, 0 on failure.

clear traces() Description Remove all traces in the current schedule of the simulator. Return value 1 on success, 0 on failure.

set simtime(sec[, nsec]) Description Set the simulation time to sec seconds and nsec nanoseconds. This can only be done in stand-by state. Parameters sec Simulation time in seconds. nsec Simulation time in nanoseconds. Return value 1 on success, 0 on failure.

enable realtime() Description Switch to real-time mode. This can only be done when the simulator has started off in real-time mode, and has switched to non-real-time mode. Return value 1 on success, 0 on failure.

disable realtime() Description Switch to non-real-time mode.

440 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure. list tasks() Description Request a list of all tasks in the current schedule of the simulator. The list is also sent automat- ically upon joining the “sched-control” channel. Return value 1 on success, 0 on failure. list events() Description Request a list of all events in the schedule of the simulator in all states. The list is automatically sent to the client when subscribing to the “sched-control” channel at start-up. Return value 1 on success, 0 on failure. raise event(eventname[, data, size]) Description Raise event with name eventname in the scheduler. An event is defined by the input connector on the scheduler canvas. The event is handled as fast as possible. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event data Data size Size of data in bytes. Return value 1 on success, 0 on failure. raise event at(eventname, sec[, nsec[, data, size]]) Description Raise event with name eventname in the schedler at a specified wallclock time. The wallclock time is specified as sec seconds and nsec nanoseconds. Event data with a given size can option- ally be passed together with the event. Parameters eventname Name of the event sec Wallclock time in seconds. nsec Wallclock time in nanoseconds. data Data size Size of data in bytes. Return value 1 on success, 0 on failure. raise event at simtime(eventname, sec[, nsec[, data, size])

c Airbus Defence and Space 441 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Raise event with name eventname in the schedler at a specified simulation time. The simula- tion time is specified as sec seconds and nsec nanoseconds. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event sec Simulation time (seconds) nsec Simulation time (nanoseconds) data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

set speed(speed) Description Set the acceleration/deceleration of the scheduler of the simulator. Values smaller than 1 will cause a proportional deceleration of the scheduler clock. Values larger than 1 will cause a proportional acceleration of the scheduler clock. Magical value -1 means that the scheduler will run in an optimized as-fast-as-possible mode. Parameters speed acceleration factor Return value 1 on success, 0 on failure.

add MDL(mdlname) Description Load (another) new MDL file in the session. Parameters mdlname Path name of the MDL file. Return value 1 on success, 0 on failure.

sync send(token) Description Send sync token to simulator Parameters token synchronization token id Return value 1 on success, 0 on failure

sync recv(token) Description Wait for sync token from simulator Parameters token synchronization token id

442 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure kill([signal]) Description Kill the simulator with signal signal. By default the simulator is killed with SIGTERM. Parameters signal Signal to send to the simulator Return value 1 on success, 0 on failure

26.3 EventHandler class

The EventHandler class is used to handle events coming from the simulator. The user must derive from this class and implement the methods for the events that must be handled. When a messsage from the simulator is received, first the built-in message handling is performed fol- lowed by the user defined message handlers. The message handlers are installed by instantiating the handler. The message handler is removed by deleting the created event handler instance. To define a user defined message handler all you need to do is: class ExampleEventHandler(eurosim.EventHandler):

# constructor def __init__(self, session): eurosim.EventHandler.__init__(self, session)

# handler for maMessage events def maMessage(self, simtime_sec, simtime_nsec, runtime_sec, runtime_nsec, sev, procname, msg): print procname, msg

# instantiate event handler (implicitly installs it) eh = ExampleEventHandler(s)

26.3.1 Method reference 26.3.1.1 Constructors

EventHandler(s) Description Construct a new EventHandler and install the handler. Parameters s The simulator session

26.3.1.2 Methods session() Description Return the session for this event handler. Return value The Session object of the simulator session.

c Airbus Defence and Space 443 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

26.3.1.3 Event Handler Methods In order to create a user defined event handler, one or more methods must be implemented. maNewMission(mission) Description A new mission (MDL) is created. Parameters mission The name of the mission.

maOpenMission(mission) Description A mission (MDL) file is opened. Parameters mission The filename of the mission file.

maCloseMission(mission) Description A mission (MDL) file is closed. Parameters mission The filename of the mission file.

maSimDef(simdef) Description Inform that client which simulation definition file is currently loaded. Parameters simdef The filename of the simulation definition file. Return value

maCurrentDict(dict) Description Inform the client which data dictionary file is currently loaded. Parameters dict The filename of the data dictionary file. Return value

maCurrentWorkingDir(cwd) Description Inform the client what the current working directory of the simulator is. Parameters cwd The path name of the current working directory.

maCurrentResultDir(result dir)

444 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Inform the client what the result directory is. The result directory contains all the journal files, recorder files, snapshots and timings file. Parameters result dir The path name of the result directory. maCurrentAliasFile(filename) Description Inform the client what the alias file is. The alias file contains the data dictionary aliases. Parameters filename The path name of the alias file. maNewAction(mission, actiontext) Description Inform the client that a new action has been created. Parameters mission The name of the mission. actiontext The new action. maDeleteAction(mission, actionname) Description Inform the client that an action has been deleted. Parameters mission The name of the mission. actionname The name of the action. maActionExecute(mission, actionname) Description Inform the client that an action is being executed. Parameters mission The name of the mission. actionname The name of the action. maActionExecuteStop(mission, actionname) Description Inform the client that an action is no longer being executed. Parameters mission The name of the mission. actionname The name of the action. maActionExecuting(mission, actionname) Description Inform a newly connected client that the action is currently executing.

c Airbus Defence and Space 445 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters mission The name of the mission. actionname The name of the action.

maActionActivate(mission, actionname) Description Inform the client that an action has been activated. I.e. is allowed to execute. Parameters mission The name of the mission. actionname The name of the action.

maActionDeActivate(mission, actionname) Description Inform the client that an action has been deactivated. I.e. is no longer allowed to execute. Parameters mission The name of the mission. actionname The name of the action.

maExecuteCommand(name, command, action mgr nr) Description Inform the client that a one shot action has been executed. Parameters name The name of the action. command The commands of the action. action mgr nr The number of the action manager that has executed the action.

maSnapshot(snapshot, comment) Description Handle maSnapshot event. This event is sent after a snapshot of the current simulator state has been made. Parameters snapshot Path name of the snapshot file. comment Comment describing the snapshot.

maMark(message, marknumber) Description Inform the client that a mark has been made in the journal file. Parameters message The descriptive message of the mark. marknumber The number of the mark.

maMessage(simtime sec, simtime nsec, runtime sec, runtime nsec, sev, process, msg)

446 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Inform the client that a message has been generated in the simulator. This message is also automatically logged in the journal file by the simulator. Parameters simtime sec Simulation time stamp (seconds part) simtime nsec Simulation time stamp (nanoseconds part) runtime sec Wallclock time stamp (seconds part) runtime nsec Wallclock time stamp (nanoseconds part) sev Severity of the message. The name of the severity can be retrieved by using the sev_to_string() method of the Session class. process Name of the simulator thread from where the message was generated. msg The message text. maRecording(on off) Description Inform the client that recording has been globally enabled/disabled. Parameters on off If the string is equal to “on”, recording is enabled. If it is “off” it is disabled. maRecordingBandwidth(bandwidth) Description Report the bandwidth used to record data to disk. Parameters bandwidth Number of bytes per seconds written to disk. maStimulatorBandwidth(bandwidth) Description Report the bandwidth used to read data from disk for stimulation. Parameters bandwidth Number of bytes per second read from disk. maRecorderFileClosed(filename) Description Inform the client that a recorder file has been closed and can be used for further processing. Parameters filename The file name of the recorder file. maDenyWriteAccess(denied) Description Inform the client that the write access to variables is denied. This is the case if the client has the role of observer. Parameters denied Flag to indicate denial of write access to the simulator variables.

c Airbus Defence and Space 447 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

maCurrentInitconds(simdef, initconds) Description Inform the client of the current list of initial conditions as used for the initialization of the simulator. Parameters simdef The name of the simulation definition file. initconds The list of initial condition files (space separated).

maCurrentCalibrations(simdef, calibrations) Description Inform the client of the current list of calibration definition files as used by the simulator. Parameters simdef The name of the simulation definition file. calibrations The list of calibration files (space separated).

maCurrentTimeMode(time mode) Description Inform the client of the current time mode. The time mode can be relative time or absolute time (UTC mode). Parameters time mode The time mode, 0 is relative time mode, 1 is absolute time mode (UTC mode).

maNewSeverity(sev, sev name) Description Inform the client about a new user-defined message severity. This message is automatically han- dled. The severity identifier can be mapped to its symbolic name using the sev_to_string() method of the Session class. Parameters sev The severity numerical identifier. sev name The symbolic name of the severity.

rtUnconfigured() Description Inform the client that the state of the simulator is unconfigured. This state means that the simulator is either still starting up, or is in its final clean up phase. This is a transient state. When starting up, the next state will be Initialising. When cleaning up the last event will be evShutdown.

rtInitialising() Description Inform the client that the state of the simulator is initialising. Depending on the schedule definition, this state will automatically be followed by the standby state. Otherwise you have to manually change the state to standby using the eventStandby() method of the Session() class.

448 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

rtStandby() Description Inform the client that the state of the simulator is standby. rtExecuting() Description Inform the client that the state of the simulator is executing. rtExiting() Description Inform the client that the state of the simulator is exiting. This is a transient state. The next state will be the unconfigured state. rtTimeToNextState(sec, nsec) Description Report the time to the next state transition. This is useful when the major cycle is quite long (more than a couple of seconds). This can be the case if the schedule definition contains a clock with a very low frequency or when the lowest common denominator of the clocks results in a long major cycle. Parameters sec Time to next state (seconds part) nsec Time to next state (nanoseconds part) rtMainCycle(sec, nsec) Description Report the length of the main cycle of the schedule. Parameters sec Main cycle (seconds part) nsec Main cycle (nanoseconds part) scSetBrk(taskname, entrynr, enable) Description Inform the client about the enabling/disabling of a break point on a specific entry point in a task in the schedule. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). enable Whether the break point is enabled (1) or disabled (0). scStepTsk() Description Inform the client that a step to the next task has been performed in debugging mode. scContinue()

c Airbus Defence and Space 449 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client that the execution is now continued after being stopped on a break point in debugging mode.

scGoRT(enable) Description Inform the client that the real-time mode has changed. Parameters enable Real-time mode is enabled (true) or disabled (false).

scTaskDisable(taskname, disable) Description Inform the client that a task has been disabled. This means that the task is no longer executed. Parameters taskname The name of the task. disable The task is disabled (true), or enabled again (false).

scSetTrc(taskname, entrynr, enable) Description Inform the client that a trace has been set on an entry point in a task. Parameters taskname The name of the task. entrynr The number of the entry point in the task (counting starts at 0). enable The trace is enabled (true), or disabled (false).

scSpeed(speed) Description Report the speed of the scheduler clock. This is only relevant in non-real-time mode when going slower or faster than real time. Parameters speed Speed factor. 1 means real-time, less than 1 means slower than real-time, more than 1 means faster than real-time. E.g. 2 means two times faster than real-time.

scTaskListStart() Description Start the description of the list of tasks.

scTaskStart(taskname, enabled) Description Start the description of a task. This is followed by a number of scTaskEntry events, one for each entry in the order of execution in the task. Parameters taskname The name of the task enabled The task is enabled (true), or disabled (false).

450 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

scTaskEntry(entryname, breakpoint, trace) Description Report information of an entry point in a task. Parameters entryname The name of the entry point. breakpoint The entry point has a break point set (true) or not set (false). trace The entry point is traced (true) or not (false). scTaskEnd() Description Report the end of the task information. scTaskListEnd() Description Report the end of the list of tasks. scEventListStart() Description Report the start of the list of schedule events. scEventInfo(eventname, state, is standard) Description Report all information about a specific schedule event. Parameters eventname The name of the event. state The state in which it is present. is standard Whether or not it is a built-in (standard) event (true), or a user defined event (false). scEventListEnd() Description Report the end of the list of events. scWhereListStart() Description Report the start of the list of places where the scheduler has stopped execution when reaching a break point. As there are possibly more than 1 executers executing tasks, there can be multiple places where the execution has stopped. scWhereEntry(taskname, entrynr) Description Report a location where the execution has stopped. Parameters taskname The name of the task.

c Airbus Defence and Space 451 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

entrynr The number of the entry point (counting starts at 0).

scWhereListEnd() Description End of the list of locations where the execution has stopped.

scEntrypointSetEnabled(entrypointname, enabled) Description Report the enabling or disabling of the execution of an entry point. The execution of the entry point is disabled for all tasks and also when executing the entry point from MDL scripts. Parameters entrypointname The name of the entry point. enabled Whether the entry point is enabled for execution (true), or disabled (false).

dtLogValueUpdate(var, value) Description Report an updated value for a logged variable. Parameters var The name of the variable. value The value of the variable.

dtHeartBeat() Description This event is sent at the speed of the non realtime action manager component, which is 5 Hz by default and indicates that the simulator is still alive. It is also the last event sent after a series of dtLogValueUpdate events.

dtCpuLoad(cpu, average, peak) Description Report the load of a CPU. Parameters cpu CPU number average Average load over a main cycle. peak Peak load over a minor cycle.

evLinkData(link id) Description Event that is used internally to transmit (TM/TC) packets. The actual data of the packet is not passed to this callback function. It is stored internally and can be retrieved using the read() method of the TmTcLink class. Parameters link id The symbolic name of the link.

void(evExtNewView)view id, export id

452 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Event that is used to confirm the creation of an external view by the simulator. Parameters view id The symbolic name of the view. export id The symbolic name of the exported view as defined in the exports file. evExtSetData(view id) Description Event that is used internally to update External Simulator Access views. The actual data of the event is not passed to this callback function. It is decoded and stored in the view variables and can be retrieved with the get() method of the ExtSimVar* classes. Parameters view id The symbolic name of the view. evShutdown(error code, error string) Description Event that is received when the connection with the simulator is lost. Parameters error code The value of errno at the time the connection was terminated. This value is zero when the connection was terminated in a normal way. error string The description of the error code. evEventDisconnect() Description Event that is received when the connection with the simulator is closed. This is normally done using the method esim_disconnect().

26.4 eurosim class

This class contains a couple of utility methods that are not linked to a session.

26.4.1 Method reference host list() Description Return the list of EuroSim hosts. Return value The list of hosts. session kill by name(simname[, signal[, hostname]]) Description Kill a simulation session by name. Parameters simname The name of the session. This is normally the basename of the executable. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost)

c Airbus Defence and Space 453 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, other- wise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified name could not be found.

session kill by pid(pid[, signal[, hostname]]) Description Kill a simulation session by pid. Parameters pid The process id of the session. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, oth- erwise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified pid could not be found.

open log() Description Allows the client to log to a file. After opening the log file everything that is sent to stdout and to stderr is also logged to the spedified file. Return value 0 if succeeded.

close log() Description Closes the log file created by open_log. Return value 0 if succeeded.

26.5 EventInfo class

The EventInfo data is return by the event_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler event.

26.5.1 Method reference

name() Description Get the name of the event. Return value The name of the event

state()

454 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Get the number of the state where this event is defined. Return value The number of the state. state name() Description Get the name of the state where this event is defined. Return value The name of the state. is standard() Description Whether the event is a standard event or a user defined event. Return value true if it is a standard event, false if it is a user defined event.

26.6 WhereInfo class

The WhereInfo data is return by the where_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler break point location.

26.6.1 Method reference name() Description Get the name of the task where the scheduler is currently stopped. Return value The task name. entrynr() Description Get the entry point number of the current break point within the task. Return value The entry point number. Counting starts at 0.

26.7 EntryInfo class

The EntryInfo data is return by the entry_list method of the TaskInfo class. The methods allow you to retrieve the individual attributes of an entry point in a task.

c Airbus Defence and Space 455 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

26.7.1 Method reference

name() Description Get the name of the entry point. Return value The name of the entry point.

breakpoint() Description Get the break point status of the entry point. Return value True if a break point is set, false if not.

trace() Description Get the trace status of the entry point. Return value True if a trace is set, false if not.

26.8 TaskInfo class

The TaskInfo data is return by the task_list method of the Session class. The methods allow you to retrieve the individual attributes of a task.

26.8.1 Method reference

name() Description Get the name of the task. Return value The name of the task.

disabled() Description Get the disabled state of the task. Return value True if the task is disabled, false if it is enabled.

entry list size() Description Get the number of entry points of the task. Return value The number of entry points.

456 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

entry list(idx) Description Get the entry point information of the entry point with the given index. Parameters idx The entry point index (counting starts at 0). Return value An EntryInfo object describing the entry point information.

26.9 EventTypeInfo class

The EventTypeInfo data is return by the event_type_list method of the Session class. The methods allow you to retrieve the individual attributes of a client/server message (called event internally).

26.9.1 Method reference name() Description Get the name of the message. Return value The name of the message. args() Description Get the argument types of the message. This is a character coded string with one character for each argument type. Return value The argument types. argdescr() Description Get a description of the arguments of the message. Return value The description of the arguments. id() Description Get the numerical identifier of the message. Return value The numerical identifier.

26.10 SessionInfo class

The SessionInfo data is return by the session_list method of the Session class. The methods allow you to retrieve the individual attributes of a simulation session.

c Airbus Defence and Space 457 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

26.10.1 Method reference

sim hostname() Description Get the host name running the simulation session. Return value The host name.

sim() Description Get the simulation definition file. Return value The file name of the simulation definition file.

workdir() Description Get the working directory. Return value The path name of the working directory.

simulator() Description Get the simulator executable. Return value The path name of the executable.

schedule() Description Get the simulator schedule. Return value The path name of the schedule file.

scenarios() Description Get the list of scenario (MDL) files. Return value The list with path names of the MDL files.

dict() Description Get the data dictionary file. Return value The path name of the data dictionary file.

458 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

model() Description Get the model file. Return value The path name of the model file. recorderdir() Description Get the recorder directory. Return value The path name of the recorder directory. initconds() Description Get the list of initial condition files. Return value The list of path names of the initial condition files. calibrations() Description Get the list of calibration files. Return value The list of path names of the calibration files. exports() Description Get the exports file. Return value The path name of the exports file. alias() Description Get the alias file. Return value The path name of the alias file. timestamp() Description Get the time stamp. Return value The time stamp. prefcon()

c Airbus Defence and Space 459 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Get the connection number. Each session has a connection number that can be used to connect a client to that session. Return value The connection number.

uid() Description Get the UNIX user id of the user who started the simulator. Return value The user id.

gid() Description Get the UNIX group id of the user who started the simulator. Return value The group id.

pid() Description Get the UNIX process id of the simulation session. Return value The process id.

realtime() Description Get the real-time state of the simulation session. Return value True if the simulator was started in real-time mode, false if it was started in non-real-time mode.

26.11 TmTcLink class

The TmTcLink class is used to create a packet link with a model in the simulator. The packet link can be used to send arbitrary packets (binary or not) to a simulator model and receive packets from a simulator model. Multiple packet links can be created. See Chapter 33 for detailed information on how to use the link.

26.11.1 Constructors

TmTcLink(id, mode) Description Open one end of a TmTc link. Parameters id The symbolic name of the TmTc link. mode Mode is “r”, “w” or “rw”, similar to the modes of the fopen() function in the standard C library.

460 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

26.11.2 Method reference connect(s) Description Connect the link to the other end in a running simulator. Parameters s The Session object of the running simulator. Return value -1 on failure, 0 on success. write(data) Description Write a packet to the link. Parameters data The data (binary string). Return value The number of bytes sent or -1 on failure. bytes(read) Description Read data from the link. Return value The data read as a bytes object.

26.12 InitCond class

This class is used for the manipulation of initial condition files. This allows the user to create a new initial condition file or modify an existing file. Individual values can be set or modified. It is also possible to merge two initial condition files.

26.12.1 Constructors

InitCond(filename, dictfile) Description Create a new set of initial conditions from an existing file. Parameters filename The initial condition file. dictfile The path of the data dictionary file.

26.12.2 Method reference add(filename) Description Merge an existing initial condition file with the current initial condition data. Parameters filename The path of the to-be-merged initial condition file.

c Airbus Defence and Space 461 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value true on success, false on failure.

write(filename, binary) Description Write the initial condition data to a file. Parameters filename The path of the new initial condition file. binary If true, write a binary file, otherwise write the data in human readable (ASCII) format. Return value true on success, false on failure.

simtime() Description Return the simulation time of the initial condition file. Return value The simulation time.

comment() Description Get the comment of in the initial condition file. Return value The comment string.

get varlist failed() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables.

get varlist set() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables.

var value get(path) Description Get the numerical value of a variable. Parameters path The data dictionary path. Return value The numerical value of the variable.

462 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

var string get(path) Description Get the string value of a variable. Parameters path The data dictionary path. Return value The string value of the variable. var value set(path, value) Description Set the numerical value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure. var string set(path, value) Description Set the string value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure. list([path]) Description Get a list of child node names beneath a parent node. Parameters path The path of the parent node (default the root “/”). Return value The list of child node names.

26.13 ExtSimView class

This class wraps the External Simulator Access interface. Detailed information on the use of this inter- face can be found in Chapter 32.

26.13.1 Constructors

ExtSimView(session, id) Description Create a new External Simulator Access view. Parameters session The Session object of the simulation session. id The symbolic identifier of the view.

c Airbus Defence and Space 463 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

26.13.2 Method reference

add(var) Description Add a variable to this view. Parameters var An ExtSimVar object of the variable to add to the view. Return value 0 on success, -1 on failure.

\bigskip \hrule \cxx{string}{get\_export\_id}{} \begin{method} \property[Description] Get the ˆexport_idˆ of this view \property[Return value] the ˆexport_idˆ \end{method}

\bigskip \hrule \cxx{string}{get\_view\_id}{} \begin{method} \property[Description] Get the ˆview_idˆ of this view \property[Return value] the ˆview_idˆ \end{method}

connect(rw flags, frequency, compression) Description Create a new view with the variables previously added to the view. Note that an excessive ammount of variables on the view might cause memory issues when calling connect. In such cases, increase the stack size of the host thread accordingly or spread the variables over multiple views. Parameters rw flags Read/write flags, 1 is read, 2 is write. frequency Update frequency in Hz. compression Compression type to be used for the data transmission. 0 is no compression, 1 means that unchanched values in the view are not transmitted. Please note that in case the whole view is not changed, no update is sent in any case. Return value 0 is success, -1 is failure. This only is a local return value. The simulator emits a message evExtNewView with view id and export id as arguments on succesful creation of the requested view.

change freq(frequency) Description

Parameters Change the update frequency of the view.

464 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

frequency The update frequency in Hz. Return value 0 is success, -1 is failure. send() Description Send the view with the updated values to the simulator. Return value 0 is success, -1 is failure.

26.14 ExtSimVar class

This is the base class of the ExtSimVar* classes. It is not to be used directly.

26.14.1 Method reference type() Description Get the variable type. Return value The variable type. is array() Description Find out if the variable is an array variable. Return value true if it is an array. is fortran() Description Find out if the variable is a Fortran variable. Only relevant for arrays, as the Fortran column/row order is different from C/Ada. Return value true if it is a Fortran variable. nof dims() Description Get the number of dimensions of the array variable. Return value The number of array dimensions. dims() Description Get the dimensions of the array variable.

c Airbus Defence and Space 465 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value The array dimensions.

path() Description Get the data dictionary path of the variable. Return value The data dictionary path.

size() Description Get the size in bytes of the variable. Return value The size in bytes.

26.15 ExtSimVar* classes

Below are the derived classes of ExtSimVar described. All similar methods are grouped to reduce the amount of documentation that only repeats the same information again and again. Therefore only two different cases are documented. One for the single element case and one for the array case. For both cases the following variants are possible: Char, Double, Float, Int, Long, Short, UnsChar, UnsInt, UnsLong and UnsShort. For arrays there are two variants: ExtSimVar*Array and ExtSimVar*FortranArray. To summarize for one type you can have the following classes: ExtSimVarChar, ExtSimVarCharArray and ExtSimVarCharFortranArray.

26.15.1 Constructors

ExtSimVar*(path) ExtSimVar*Array(path, dim0[, dim1[, dim2]]) ExtSimVar*FortranArray(path, dim0[, dim1[, dim2]]) Description Create a new variable to be used in an ExtSimView. Parameters path The data dictionary path dim0 The size of the first dimension. dim1 The size of the second dimension. dim2 The size of the third dimension.

26.15.2 Method reference

get([idx0[, idx1[, idx2]]]) Description Get the value of a single variable or single array element. The variant without the idx* param- eters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters idx0 Index in first dimension.

466 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

idx1 Index in second dimension. idx2 Index in third dimension. Return value The value of the variable. The type of the return value depends on the type of the function. The type mapping is listed above in the introduction. set(val[, idx0[, idx1[, idx2]]]) Description Set the value of a single variable or single array element. The variant without the idx* parame- ters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters val The new value. The type of the value depends on the type of the function. The type mapping is listed above in the introduction. idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension.

c Airbus Defence and Space 467 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

468 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 27

Tcl batch reference

27.1 Introduction

This chapter provides details on the batch utility for the TCL scripting language. Various TCL objects have been created that provide an interface to existing EuroSim libraries. This means that a batch ap- plication is no more than an ordinary TCL script using EuroSim objects. These objects provide the functionality to script the launch and operation of a EuroSim simulator, with similar capabilities to those available to an operator via the Simulation Controller. The TCL glue code is generated using SWIG and wraps the C++ client interface provided by EuroSim. The same interface is also available for Java and Python, though small changes may apply in behavior. In particular TCL has an event loop which adds some automatic update behavior which is detailed in this chapter. The batch utility for TCL consists of various objects. Each object (or group of objects) is described in a separate chapter. The most important object is the Session class.

27.2 Session class

This is the central class used to run simulations. It functions as a replacement for the simulation con- troller, allowing the user to automate any action that can can be performed with the simulation controller. The class supports the complete EuroSim ”EventConnection” network protocol required to control and monitor the running simulator executable. Where the Simulation Controller provides buttons to control the simulator, the Session class provides a method to easily create and send an event to the simulator. And where the Simulation Controller handles incoming events in a predefined manner, the Session class provides both the ability to install callbacks to handle an event as well as the ability to wait for a specific or for any event including a timeout option. For a complete overview of all events, see Chapter 31. Following example shows how to start a simulator using the Session class: # load simulation definition eurosim::Session s "some.sim" # start simulator s init

As shown in the example, similar information is passed to these calls as needed by the simulation con- troller. In the simulation controller a simulation definition file (.sim) is opened and then the simulator is launched using the Init button. The Simulation Controller then automatically connects to the sim- ulator and processes events in a predefined manner. In the same manner the constructor for a session object is passed the simulation definition file, and the init method launches the simulator and connects when it is ready. The details of this connection are stored in the session class and can be printed with the print_session_parameters method. The init method also sets up a number of standard event handlers for incoming events (messages).

c Airbus Defence and Space 469 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.2.1 Event Handling details The client uses the EuroSim Event Connection protocol to synchronize with the simulator. Via this protocol it receives a large variety of events, including heartbeat events, state update events, and variable value update events. The latter can occur due to the usage of external simulator access or because the client sent a get_value event to the simulator. There are two approaches to handle events, asynchronous or synchronous. The asynchronous approach is based on event handlers, these are callbacks that are called when the nicomnig messages are processed. To install a new event handler you have to add an event handler callback procedure. See Section 27.3. The timing of the processing of the received events is determined by the user. The wait_event method reads the events in the receiver socket and calls the associated event handler(s). Although the event handlers are an asynchronous mechanism the user thus still controls when the event procesing is performed. It is thus not in parallel to the execution of the user’s scripts (use multithreading if such parallellism is needed). It is also possible to synchronously wait for an event you expect. In this case you call the wait_event method with the name of the event (same name as the method in the event handler class) and a time- out (in milliseconds). The wait_event method processes the received events until the specific event is received or the timout occurs. The return value of the wait_event indicates which condition occured. Note that this approach may thus trigger event handlers callbacks as well when it processes the received events it encounters, which of course includes events received until the timeout occurs. A timeout of zero processes the events until no more events are encountered and then returns. To synchronously wait for some time to pass, the wait_event can be called with an empty string as the event name. In line with the TCL event loop approach though, the pending events are also processed as part of the TCL event loop. When in TCL the user calls the vwait to allow the TCL event loop to process events, potentially using this to wait for a change in a variable, the pending EuroSim events are thus also regularly processed and can trigger the calling of EuroSim event handler callbacks. Another concept to take into account in the TCL client interface is that you can have multiple TCL command interpreters in parallel that all want to communicate with the simulator. This is possible, the threads have there own event loop safe and hence each can create its own connection with the simulator. This will thus create multiple clients that are connected with the same simulaor. Please however be aware of the safe thread concept of TCL. It is quite often needed to echange data between the command interpreters at the script level. The global variables in TCL scripting are not shared, unless they are specifically stored as shared variables in the env object.

27.2.2 Monitoring variables

In order to monitor variables you must call the method monitor_add with the variable you want to monitor. The variable parameter is in the form of a valid EuroSim data dictionary path. This method will add the variable to the list of variables monitored in EuroSim. The value of each variable will be updated with the asynchronous action manager frequency, which defaults to 5 Hz if they change. If there is no change, no update is sent. The values of the variables are stored in the Session class. To get the value of a variable use the following expression: s.monitor_value(var_path). The value is always returned as a string. To stop monitoring a variable you must call the function monitor_remove with the variable you want to stop monitoring. If you only want to get the value of a variable once, it is better to call the function get_value. This function retrieves the value of the variable immediately from the simulator, but only once. The value of the variable is returned as a string.

470 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

27.2.3 Modifying variables

If you want to change the value of a variable in the simulator you can simply call set_value with the name and value (as a string) of the variable. The value will be set as soon as possible in the simulator. Calling set_value also works on an array variable or struct in its entirety and will set these values atomically. To set different variables atomically in one API call, use set_values. The argument is an instance of class VariableSet in the eurosim namespace. Variable value pairs can be added to this VariableSet instance using its add function, which takes the variable path and value string as arguments. The benefit of this approach is a much quicker execution time as the client will send the value pairs in one message to the simulator and wait for confirmation. Using set_value the client will send one message and wait for confirmation, which then must be repeated for each variable.

27.2.4 Method reference 27.2.4.1 Constructors eurosim::Session session ?sim hostname? Description Creates a EuroSim simulation session by loading the given simulation definition file sim. The simulation run will be started on the host with the given hostname or on the current host if not specified. Parameters session The name of the new Session object sim the simulation definition file name hostname the name of the host on which to run the simulator

27.2.4.2 Methods cwd Description Returns the path name of the current working directory of the simulator. The value is set by the event handler for event maCurrentWorkingDir. Return value Path name of the current working directory dict Description Returns the path name of the EuroSim data dictionary of the simulator. The value is set by the event handler for event maCurrentDict. Return value Path name of the EuroSim data dictionary outputdir Description Returns the path name of the directory where the output files of the simulator are stored (journal file, recorder files, etc.) The value is set by the event handler for event maCurrentResultDir. Return value Path name of the output directory

c Airbus Defence and Space 471 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

state Description Returns the simulator state. Can be: unconfigured, initialising, stand-by, executing, exiting. The value is set by the event handler for the following events: rtUnconfigured, rtInitialising, rtStandby, rtExecuting and rtExiting. Return value Simulator state

set remote path Description If client and server have different paths (e.g. A Windows client launching a simulator on a linux server) set_remote_path can be used to set the root path of the simulator in the remote EuroSim server. Note: When setting the remote path the recordings files and the EuroSim journal are stored in the /tmp directory on the server machine. Return value New paths for the simulator.

journal Description Returns the path name of the journal file. Return value Path name of the journal file

schedule Description Returns the path name of the schedule file. Return value Path name of the schedule file

exports Description Returns the path name of the exports file. Return value Path name of the exports file

alias ?alias? Description Set or get the alias file name. Parameters alias Override the alias file specified in the SIM file. If alias was not specified, then the alias file remains unchanged. Return value Path name of the alias file. If the simulation is running, then the value is set by the event handler for event maCurrentAliasFile.

472 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

model Description Returns the path name of the model file. Return value Path name of the model file recording bandwidth Description Returns the recorder bandwidth in bytes/second. The value is set by the event handler for event maRecordingBandwidth. Return value Recorder bandwidth in bytes/second stimulator bandwidth Description Returns the stimulator bandwidth in bytes/second. The value is set by the event handler for event maStimulatorBandwidth. Return value Stimulator bandwidth in bytes/second speed Description Returns the clock acceleration factor achieved by the simulator. Values larger than 1 indicate faster than real-time. Values smaller than 1 indicate slower than real-time. The value is set by the event handler for event scSpeed. Return value Acceleration factor sim time Description

Description Returns the simulation time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Simulation time in seconds wallclock time Description Returns the wallclock time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Wallclock time in seconds

c Airbus Defence and Space 473 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

wallclock boundary Description Returns the wallclock boundary time to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Wallclock time boundary in seconds

simtime boundary Description Returns the simulation time boundary to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Simulation time boundary in seconds

main cycle Description Returns the main cycle time of the current schedule. It can be used to calculate valid boundary times for timed state transitions. Return value Main cycle in seconds.

recording Description Returns the flag indicating that recording is enabled or not. True means enabled, false means disabled. The value is set by the event handler for event maRecording. Return value Recording is enabled

write access Description Returns the flag to indicate whether this client is allowed to change variable values in the sim- ulator. The value is set by the event handler for event maDenyWriteAccess. Return value Client is allowed to change variables

time mode Description Returns the time mode. It can be relative or absolute (UTC). Relative is 0 and absolute is 1. The value is set by the event handler for event maCurrentTimeMode. Return value Time mode

474 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

realtime Description Set or get the realtime mode. Parameters realtime If the realtime mode is not specified, then the realtime mode is not set. If realtime is 0, then realtime mode is disabled, otherwise it is enabled. The new setting will not effect an already running simulation. Return value The realtime mode, true for realtime, false for non-realtime. If a simulation is running, then the value as was set by the event handler for event scGoRT is reported. Non-realtime is the default. auto init ?auto init? Description Set or get the auto initialization flag. Parameters auto init If the auto initialization flag is not specified, then the auto initialization flag is not set. If auto init is 0, then the simulator will not go automatically to initializing state on startup, otherwise it will go automatically to initializing (this is the default). The new setting will not effect an already running simulation. Return value The auto init flag, true if the state transition to initializing state is performed automatically, false if it isn’t. Automatic state transition to initializing is the default. prefcon ?prefcon? Description Set or get the preferred connection. Parameters prefcon The preferred connection. This can be used in a situation where you need to reconnect to an already running simulator. To start new simulation runs, this number is not used. If prefcon was not specified, then the preferred connection is not set. Return value Return the connection number of the current simulation session. startup timeout ?timeout? Description Set or get the startup timeout. The startup timeout default is 5 seconds. If starting up a simulator takes longer than this you must change that default to a higher value. If timeout was not specified, then the startup timeout is not set. Parameters timeout The startup timeout. Return value Return the startup timeout in seconds of the current simulation session.

c Airbus Defence and Space 475 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

clientname ?clientname? Description Set or get the name under which this session is known to the simulator. Parameters clientname The client name of the current simulation session. The default is “esimbatch”. If clientname was not specified, then the client name is not changed. Return value Return the client name of the current simulation session.

initconds ?initconds? Description Set or get the initial condition files. Parameters initconds Override the initial condition files specified in the SIM file. If initconds was not specified, then the initial condition files remain unchanged. Return value Initial condition files. If the simulation is running, then the value is set by the event handler for event maCurrentInitconds.

calibrations ?calibrations? Description Set or get the calibration files. Parameters calibrations Override the calibration files specified in the SIM file. If calibrations was not specified, then the calibration files remain unchanged. Return value Calibration files. If the simulation is running, then the value is set by the event handler for event maCurrentCalibrations.

workdir ?workdir? Description Set or get the work directory. Parameters workdir Use this directory as the work or project directory instead of the current directory. Return value The work directory.

user defined outputdir ?outputdir? Description Set or get the user defined output directory. Parameters outputdir Use this output directory instead of the default date/time directory. If not set, then the user defined output directory is not changed.

476 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The user defined output directory. hostname ?hostname? Description Set or get the EuroSim server hostname. Parameters hostname Use this EuroSim server. If not set, then the hostname is not changed. Return value The EuroSim server hostname. sim ?sim hostname? Description Set or get the simulation definition file. This simulation definition file is used to start the simulator. Information derived from the sim- ulation definition file is used to provide sensible defaults for all parameters. Parameters sim The simulation definition file. If not set, then the simulation definition is not changed. hostname The EuroSim server hostname. If not set, then the local host is used instead. Return value The filename of the simulation definition file. init Description Start a new simulation run. Return value 1 on success, 0 on failure. join channel channel Description Join a channel of a simulation session. By default each session connects to all channels. The following channels are available: mdlAndActions, data-monitor, rt-control, sched-control. To join all channels use channel “all”. Parameters channel The channel to join. Return value 1 on success, 0 on failure. leave channel channel Description Leave a channel of a simulation channel. Parameters channel The channel that you want to leave. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 477 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

event addhandler name cb Description Add TCL event handler. The event handler is added to the end of the list if there are already event handlers installed for this event. Parameters name The name of the event. cb The name of the callback function. Return value 1 on success, 0 on failure.

event removehandler name cb Description Remove callback function. Parameters name The name of the event. cb The name of the callback function. Return value 1 on success, 0 on failure.

wait event event timeout ms Description Wait for an incoming event This function is used to wait synchronously for the given event. The timeout is used to limit the amount of time to wait for this event. Parameters event The name of the event to wait for. If the event name is empty this function can be used to read all pending events while waiting for the given amount of time. timeout ms The timeout in milliseconds. A value of -1 means that this this function will wait until the event arrives for an unlimited amount of time. A value of 0 means that the function will return immediately even if the event has not arrived yet. Return value true if the event had arrived, false if it has not.

monitor add path var Description Monitor a variable. The value of the variable is updated with the frequency of the asynchronous action manager, which defaults to 5 Hz. Parameters path The pathname of the variable from the data dictionary that you want to monitor. var The name of the variable to use to store the monitored value in. Return value 1 on success, 0 on failure.

monitor value var

478 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Retrieve the value of a monitored variable Parameters var The name of the monitored variable. Return value the value of the variable monitor remove var Description Remove the monitor of a variable. Parameters var The variable from the data dictionary that should be removed from the monitor list. Return value 1 on success, 0 on failure. create session list ?hostname? Description Create a list of all sessions and return the size of that list. Parameters hostname If set, then report the sessions running on that host. Otherwise report all sessions running on the subnet. Return value the number of sessions. session list idx Description Return the session info for the session with the given index. Parameters idx The index in the session list. Return value A SessionInfo object. esim connect Description Connect to a running simulation; a new journal file is opened. Return value 1 on success, 0 on failure. esim disconnect Description Disconnect from the simulation session. The simulator will continue to run in the background. print monitored vars

c Airbus Defence and Space 479 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Print a list of currently monitored variables and their current values. All variables in active monitors send values to the batch tool. A table with all variables is kept with their current values.

print session paramters Description Print a complete overview of all available parameters.

print event list Description Print a list of all events (messages) and parameters used in the communication between the test controller and the simulator.

script action name script ?condition? Description Create an MDL script text. Parameters name The action name. script The action script. condition The optional condition. Return value The fully composed action script.

recorder action name freq vars Description Create a recorder script. Parameters name The action name. freq The recorder frequency. vars A list of all variables to be recorded. Return value The fully composed recorder script.

stimulus action name option filename freq vars Description Create a stimulus script. Parameters name The action name. freq The stimulus frequency. option An option string (“soft”, “hard” or “cyclic”). filename The stimulus filename. vars A list of all variables to serve as stimulus.

480 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The fully composed stimulus script. event list size Description Return the size of the list of events present in the schedule. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Return value The size of the list of events. event list idx Description Return the event info of the event with the given index. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Parameters idx The index in the event list (the first element has index 0). Return value An EventInfo object. where list size Description Return the size of the current breakpoint list. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Return value The size of the list. where list idx Description Return the current breakpoint with the given index. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Parameters idx The index in the current breakpoint list. Return value A WhereInfo object describing the break point location. task list size Description Return the size of the task list. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable.

c Airbus Defence and Space 481 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value The size of the task list.

task list idx Description Return the task info for the task with the given index. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Parameters idx The index in the task list. Return value A TaskInfo object.

find task index taskname Description Convert task name to index number. Parameters taskname The name of the task. Return value The index in the task list.

mdl list Description Return a list of all loaded MDL files. MDL files are loaded at start-up when a .sim file is loaded or during run-time when extra MDL files are loaded. Extra files can be loaded by the event handler for event maNewMission or by manually adding MDL files with new scenario. Return value The list of MDL files.

action list mdl Description Return a list with the names of all the actions. Parameters mdl The name of the MDL file. Return value The list of action names.

monitored vars Description Return a list of all monitored variables. Return value The list of variables.

event type list size

482 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Return the size of the event messages table. Return value The number of event messages. event type list idx Description Return the event type info of event message idx. Parameters idx The index in the event messages table. Return value An EventTypeInfo object. sev to string sev Description Return a string respresentation of a message severity Parameters sev Message severity Return value String representation of severity go ?sec nsec? Description Change the simulator state from stand-by to executing. Equivalent to the Go button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is specified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. stop ?sec nsec? Description Stop the simulation run. Equivalent to the Stop button of the test controller. The variant speci- fying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. pause ?sec nsec?

c Airbus Defence and Space 483 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

freeze ?sec nsec? Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

freeze at simtime sec ?nsec? Description Change the simulator state from executing to stand-by on the specified simulation time. The simulation time is secified as sec seconds and nsec nanoseconds. Parameters sec Simulation time (seconds) nsec Simulation time (nanoseconds) Return value 1 on success, 0 on failure.

step Description Perform one main scheduler cycle. Equivalent to the Step button of the test controller. Return value 1 on success, 0 on failure.

abort Description Abort the current simulation run. Equivalent to the Abort button of the test controller. Return value 1 on success, 0 on failure.

health Description Request a health check of the running simulator. Prints health information to the test controller.

484 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure. reset sim Description Restart the current simulation with the current settings. Equivalent to the Reset button of the test controller. Return value 1 on success, 0 on failure. new scenario scen Description Create a new scenario in the simulator. This new scenario is only a container for new actions. It is not a file on disk. It is a pure in core representation. Parameters scen The scenario name. Return value 1 on success, 0 on failure. open scenario scen Description Open a new scenario file in the simulator with file name scen. The file must be on disk and readable. Parameters scen Scenario file name. Return value 1 on success, 0 on failure. close scenario scen Description Close a currently opened scenario with name scen in the simulator. Parameters scen Scenario file name. Return value 1 on success, 0 on failure. new action scen action text Description Add a new action in the scenario file with name scen. action text is the complete action text. There are a few utility functions to generate those actions. Parameters scen The scenario file name. action text The action text. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 485 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

delete action scen action Description Delete an action from scenario scen with name action. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

action execute scen action Description Trigger the execution of the action with name action in scenario with name scen. This is equivalent to triggering an action manually on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

action activate scen action Description Make action with name action in scenario with name scen active in the running simulator. The action must already be defined in the scenario. This is equivalent to activating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

action deactivate scen action Description Deactivate action with name action in scenario with name scen in the running simulator. This is equivalent to deactivating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

snapshot ?filename comment? Description Make a snapshot of the current state of the variables in the data dictionary. The comment string is optional. If you omit the filename, a filename is chosen of the form snapshot simtime.snap. The snapshot is saved in the output directory, unless the filename is absolute. This is equivalent to the “Take Snaphot...” menu option in the “Control” menu of the test controller.

486 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters filename Path name of the snapshot file. comment Comment string Return value 1 on success, 0 on failure. mark ?comment? Description Make a mark in the journal file. The comment string is optional. This is equivalent to the “Mark Journal” and “Comment Journal Mark” menu options in the “Insert” menu of the Simulation Controller. Parameters comment Comment string Return value 1 on success, 0 on failure. sim message msg Description Send a message to the simulator for distribution to all clients. This is useful if your client application is not the only client of the simulator. The message is broadcasted to all clients. Parameters msg Message string Return value 1 on success, 0 on failure. suspend recording Description Suspend recording in the simulator. This is equivalent to unchecking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure. resume recording Description Resume recording in the simulator. This is equivalent to checking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure. recording switch Description Switch all recording files of a simulation run. All currently open recorder files are closed and new recorder files are created. Recording will continue in the new recorder files. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 487 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

reload snapfile ?hard? Description Load initial condition file or snapshot file with file name snapfile into the running simulator. Parameter hard is by default “off”. This means that the simulation time stored in the snapshot file is ignored. If hard is set to “on”, the simulation time is set to the value specified in the snapshot file. Parameters snapfile Path name of snapshot file. hard “on” or “off”. Return value 1 on success, 0 on failure.

set value var value Description Set the value of a variable. Parameters var The data dictionary path name of variable you want to change. value The new value as string. To set an array variable write the value as a comma seperated list between curly brackets. For example: ::s set_value "/Thrusters/force" "{1,2, 2, 3, 4, 5, 6, -2, 2}" The same applies for a struct with respect to fields. Nesting is possible too, a field of a struct that is an array would be a comma seperated list in curly brackets embedded in a comma seperated list in curly brackets as in: ::s set_value "/Thrusters/example" "{1,2, {1,5}, 3, 4,}" Return value 1 on success, 0 on failure.

set values varset Description Set the value for a list of variables in one command. The argument varset is VariableSet instance and can hold a list of variable-value pairs. The advantage is a much faster handling for larger sets of variables. Parameters varset The instance that holds the list of variable-value pairs. eurosim::VariableSet varset varset add {/Thrusters/force} 2 varset add {/Thrusters/torque} 3 s set_values(varset) Return value 1 on success, 0 on failure.

get value var Description Get the value of a variable. Parameters var The data dictionary path name of the variable

488 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The value, empty on failure cpu load set peak cpu peak time Description Configure the CPU load monitor peak time in msecs. Parameters cpu CPU number peak time Peak time in seconds. Return value 1 on success, 0 on failure. set breakpoint taskname entrynr enable Description Set a breakpoint on entry nr entrynr in task taskname in the scheduler. If parameter enable is set to true the breakpoint is enabled. To disable it again set the parameter to false. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure. set trace taskname entrynr enable Description Enable/disable tracing of entry points. Entry points are defined by specifying the number of the entry point entrynr (numbering starts at 0) and the name of the task taskname. To enable a trace set enable to true, to disable it set it to false. Tracing an entry point means that messages are printed to the journal window. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure. where Description Request the current position when the scheduler has stopped on a break point. The reply to the message is automatically stored and can be retrieved by using where list. Normally the position is sent to the client whenever the scheduler hits a breakpoint. So there is rarely any need to request the position manually if you store the position on the client side (as is done in this tool.) Return value 1 on success, 0 on failure.

c Airbus Defence and Space 489 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

step task Description Perform one step (=one entry point) in the scheduler debugger. Return value 1 on success, 0 on failure.

cont Description Continue executing upto the next breakpoint in the scheduler debugger. Return value 1 on success, 0 on failure.

task disable taskname Description Disable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure.

task enable taskname Description Enable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure.

clear breaks Description Remove all breakpoints in the current schedule of the simulator. Return value 1 on success, 0 on failure.

clear traces Description Remove all traces in the current schedule of the simulator. Return value 1 on success, 0 on failure.

set simtime sec ?nsec? Description Set the simulation time to sec seconds and nsec nanoseconds. This can only be done in stand-by state.

490 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters sec Simulation time in seconds. nsec Simulation time in nanoseconds. Return value 1 on success, 0 on failure. enable realtime Description Switch to real-time mode. This can only be done when the simulator has started off in real-time mode, and has switched to non-real-time mode. Return value 1 on success, 0 on failure. disable realtime Description Switch to non-real-time mode. Return value 1 on success, 0 on failure. list tasks Description Request a list of all tasks in the current schedule of the simulator. The list is also sent automat- ically upon joining the “sched-control” channel. Return value 1 on success, 0 on failure. list events Description Request a list of all events in the schedule of the simulator in all states. The list is automatically sent to the client when subscribing to the “sched-control” channel at start-up. Return value 1 on success, 0 on failure. raise event eventname ?data size? Description Raise event with name eventname in the scheduler. An event is defined by the input connector on the scheduler canvas. The event is handled as fast as possible. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 491 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

raise event at eventname sec ?nsec data size? Description Raise event with name eventname in the schedler at a specified wallclock time. The wallclock time is specified as sec seconds and nsec nanoseconds. Event data with a given size can option- ally be passed together with the event. Parameters eventname Name of the event sec Wallclock time in seconds. nsec Wallclock time in nanoseconds. data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

raise event at simtime eventname sec ?nsec data size? Description Raise event with name eventname in the schedler at a specified simulation time. The simula- tion time is specified as sec seconds and nsec nanoseconds. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event sec Simulation time (seconds) nsec Simulation time (nanoseconds) data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

set speed speed Description Set the acceleration/deceleration of the scheduler of the simulator. Values smaller than 1 will cause a proportional deceleration of the scheduler clock. Values larger than 1 will cause a proportional acceleration of the scheduler clock. Magical value -1 means that the scheduler will run in an optimized as-fast-as-possible mode. Parameters speed acceleration factor Return value 1 on success, 0 on failure.

add MDL mdlname Description Load (another) new MDL file in the session. Parameters mdlname Path name of the MDL file.

492 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure. sync send token Description Send sync token to simulator Parameters token synchronization token id Return value 1 on success, 0 on failure sync recv token Description Wait for sync token from simulator Parameters token synchronization token id Return value 1 on success, 0 on failure kill ?signal? Description Kill the simulator with signal signal. By default the simulator is killed with SIGTERM. Parameters signal Signal to send to the simulator Return value 1 on success, 0 on failure

27.3 Event handler callbacks

Event handler callbacks can be installed to handle events coming from the simulator. When a messsage from the simulator is received, first the built-in message handling is performed fol- lowed by the user defined message handlers. The message handlers are installed by calling the event_addhandler method of the Session object. The message handler is removed by calling the event_removehandler method. To define a user defined message handler all you need to do is: # handler for maMessage events proc cb_message {s t1 t2 t3 t4 varargs} { puts "[lindex $varargs 1] [lindex $varargs 2]" }

# install event handler s event_addhandler maMessage cb_message

Each message type has a specific set of arguments apart from an initial set of standard arguments. The specific arguments are described in the next section. The initial set of standard arguments are: session The Session object.

c Airbus Defence and Space 493 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

simtime sec The simulation time (seconds part)

simtime nsec The simulation time (nanoseconds part)

runtime sec The wallclock time (seconds part)

runtime nsec The wallclock time (nanoseconds part)

varargs The remaining message specific arguments.

27.3.1 Message reference

maNewMission mission Description A new mission (MDL) is created. Parameters mission The name of the mission.

maOpenMission mission Description A mission (MDL) file is opened. Parameters mission The filename of the mission file.

maCloseMission mission Description A mission (MDL) file is closed. Parameters mission The filename of the mission file.

maSimDef simdef Description Inform that client which simulation definition file is currently loaded. Parameters simdef The filename of the simulation definition file. Return value

maCurrentDict dict Description Inform the client which data dictionary file is currently loaded. Parameters dict The filename of the data dictionary file. Return value

maCurrentWorkingDir cwd

494 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Inform the client what the current working directory of the simulator is. Parameters cwd The path name of the current working directory. maCurrentResultDir result dir Description Inform the client what the result directory is. The result directory contains all the journal files, recorder files, snapshots and timings file. Parameters result dir The path name of the result directory. maCurrentAliasFile filename Description Inform the client what the alias file is. The alias file contains the data dictionary aliases. Parameters filename The path name of the alias file. maNewAction mission actiontext Description Inform the client that a new action has been created. Parameters mission The name of the mission. actiontext The new action. maDeleteAction mission actionname Description Inform the client that an action has been deleted. Parameters mission The name of the mission. actionname The name of the action. maActionExecute mission actionname Description Inform the client that an action is being executed. Parameters mission The name of the mission. actionname The name of the action. maActionExecuteStop mission actionname Description Inform the client that an action is no longer being executed. Parameters mission The name of the mission. actionname The name of the action.

c Airbus Defence and Space 495 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

maActionExecuting mission actionname Description Inform a newly connected client that the action is currently executing. Parameters mission The name of the mission. actionname The name of the action.

maActionActivate mission actionname Description Inform the client that an action has been activated. I.e. is allowed to execute. Parameters mission The name of the mission. actionname The name of the action.

maActionDeActivate mission actionname Description Inform the client that an action has been deactivated. I.e. is no longer allowed to execute. Parameters mission The name of the mission. actionname The name of the action.

maExecuteCommand name command action mgr nr Description Inform the client that a one shot action has been executed. Parameters name The name of the action. command The commands of the action. action mgr nr The number of the action manager that has executed the action.

maSnapshot snapshot comment Description Handle maSnapshot event. This event is sent after a snapshot of the current simulator state has been made. Parameters snapshot Path name of the snapshot file. comment Comment describing the snapshot.

maMark message marknumber Description Inform the client that a mark has been made in the journal file. Parameters message The descriptive message of the mark. marknumber The number of the mark.

496 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

maMessage sev msg Description Inform the client that a message has been generated in the simulator. This message is also automatically logged in the journal file by the simulator. Parameters sev Severity of the message. The name of the severity can be retrieved by using the sev_to_string() method of the Session class. process Name of the simulator thread from where the message was generated. msg The message text. maRecording on off Description Inform the client that recording has been globally enabled/disabled. Parameters on off If the string is equal to “on”, recording is enabled. If it is “off” it is disabled. maRecordingBandwidth bandwidth Description Report the bandwidth used to record data to disk. Parameters bandwidth Number of bytes per seconds written to disk. maStimulatorBandwidth bandwidth Description Report the bandwidth used to read data from disk for stimulation. Parameters bandwidth Number of bytes per second read from disk. maRecorderFileClosed filename Description Inform the client that a recorder file has been closed and can be used for further processing. Parameters filename The file name of the recorder file. maDenyWriteAccess denied Description Inform the client that the write access to variables is denied. This is the case if the client has the role of observer. Parameters denied Flag to indicate denial of write access to the simulator variables. maCurrentInitconds simdef initconds

c Airbus Defence and Space 497 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client of the current list of initial conditions as used for the initialization of the simulator. Parameters simdef The name of the simulation definition file. initconds The list of initial condition files (space separated).

maCurrentCalibrations simdef calibrations Description Inform the client of the current list of calibration definition files as used by the simulator. Parameters simdef The name of the simulation definition file. calibrations The list of calibration files (space separated).

maCurrentTimeMode time mode Description Inform the client of the current time mode. The time mode can be relative time or absolute time (UTC mode). Parameters time mode The time mode, 0 is relative time mode, 1 is absolute time mode (UTC mode).

maNewSeverity sev sev name Description Inform the client about a new user-defined message severity. This message is automatically han- dled. The severity identifier can be mapped to its symbolic name using the sev_to_string() method of the Session class. Parameters sev The severity numerical identifier. sev name The symbolic name of the severity.

rtUnconfigured Description Inform the client that the state of the simulator is unconfigured. This state means that the simulator is either still starting up, or is in its final clean up phase. This is a transient state. When starting up, the next state will be Initialising. When cleaning up the last event will be evShutdown.

rtInitialising Description Inform the client that the state of the simulator is initialising. Depending on the schedule definition, this state will automatically be followed by the standby state. Otherwise you have to manually change the state to standby using the eventStandby() method of the Session() class.

rtStandby

498 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Inform the client that the state of the simulator is standby. rtExecuting Description Inform the client that the state of the simulator is executing. rtExiting Description Inform the client that the state of the simulator is exiting. This is a transient state. The next state will be the unconfigured state. rtTimeToNextState sec nsec Description Report the time to the next state transition. This is useful when the major cycle is quite long (more than a couple of seconds). This can be the case if the schedule definition contains a clock with a very low frequency or when the lowest common denominator of the clocks results in a long major cycle. Parameters sec Time to next state (seconds part) nsec Time to next state (nanoseconds part) rtMainCycle sec nsec Description Report the length of the main cycle of the schedule. Parameters sec Main cycle (seconds part) nsec Main cycle (nanoseconds part) scSetBrk taskname entrynr enable Description Inform the client about the enabling/disabling of a break point on a specific entry point in a task in the schedule. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). enable Whether the break point is enabled (1) or disabled (0). scStepTsk Description Inform the client that a step to the next task has been performed in debugging mode. scContinue

c Airbus Defence and Space 499 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client that the execution is now continued after being stopped on a break point in debugging mode.

scGoRT enable Description Inform the client that the real-time mode has changed. Parameters enable Real-time mode is enabled (true) or disabled (false).

scTaskDisable taskname disable Description Inform the client that a task has been disabled. This means that the task is no longer executed. Parameters taskname The name of the task. disable The task is disabled (true), or enabled again (false).

scSetTrc taskname entrynr enable Description Inform the client that a trace has been set on an entry point in a task. Parameters taskname The name of the task. entrynr The number of the entry point in the task (counting starts at 0). enable The trace is enabled (true), or disabled (false).

scSpeed speed Description Report the speed of the scheduler clock. This is only relevant in non-real-time mode when going slower or faster than real time. Parameters speed Speed factor. 1 means real-time, less than 1 means slower than real-time, more than 1 means faster than real-time. E.g. 2 means two times faster than real-time.

scTaskListStart Description Start the description of the list of tasks.

scTaskStart taskname enabled Description Start the description of a task. This is followed by a number of scTaskEntry events, one for each entry in the order of execution in the task. Parameters taskname The name of the task enabled The task is enabled (true), or disabled (false).

500 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

scTaskEntry entryname breakpoint trace Description Report information of an entry point in a task. Parameters entryname The name of the entry point. breakpoint The entry point has a break point set (true) or not set (false). trace The entry point is traced (true) or not (false). scTaskEnd Description Report the end of the task information. scTaskListEnd Description Report the end of the list of tasks. scEventListStart Description Report the start of the list of schedule events. scEventInfo eventname state is standard Description Report all information about a specific schedule event. Parameters eventname The name of the event. state The state in which it is present. is standard Whether or not it is a built-in (standard) event (true), or a user defined event (false). scEventListEnd Description Report the end of the list of events. scWhereListStart Description Report the start of the list of places where the scheduler has stopped execution when reaching a break point. As there are possibly more than 1 executers executing tasks, there can be multiple places where the execution has stopped. scWhereEntry taskname entrynr Description Report a location where the execution has stopped. Parameters taskname The name of the task.

c Airbus Defence and Space 501 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

entrynr The number of the entry point (counting starts at 0).

scWhereListEnd Description End of the list of locations where the execution has stopped.

scEntrypointSetEnabled entrypointname enabled Description Report the enabling or disabling of the execution of an entry point. The execution of the entry point is disabled for all tasks and also when executing the entry point from MDL scripts. Parameters entrypointname The name of the entry point. enabled Whether the entry point is enabled for execution (true), or disabled (false).

dtLogValueUpdate var value Description Report an updated value for a logged variable. Parameters var The name of the variable. value The value of the variable.

dtHeartBeat Description This event is sent at the speed of the non realtime action manager component, which is 5 Hz by default and indicates that the simulator is still alive. It is also the last event sent after a series of dtLogValueUpdate events.

dtCpuLoad cpu average peak Description Report the load of a CPU. Parameters cpu CPU number average Average load over a main cycle. peak Peak load over a minor cycle.

evLinkData link id Description Event that is used internally to transmit (TM/TC) packets. The actual data of the packet is not passed to this callback function. It is stored internally and can be retrieved using the read() method of the TmTcLink class. Parameters link id The symbolic name of the link.

void evExtNewViewview id export id

502 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Event that is used to confirm the creation of an external view by the simulator. Parameters view id The symbolic name of the view. export id The symbolic name of the exported view as defined in the exports file. evExtSetData view id Description Event that is used internally to update External Simulator Access views. The actual data of the event is not passed to this callback function. It is decoded and stored in the view variables and can be retrieved with the get() method of the ExtSimVar* classes. Parameters view id The symbolic name of the view. evShutdown error code error string Description Event that is received when the connection with the simulator is lost. Parameters error code The value of errno at the time the connection was terminated. This value is zero when the connection was terminated in a normal way. error string The description of the error code. evEventDisconnect Description Event that is received when the connection with the simulator is closed. This is normally done using the method esim_disconnect().

27.4 eurosim class

This class contains a couple of utility methods that are not linked to a session.

27.4.1 Method reference host list Description Return the list of EuroSim hosts. Return value The list of hosts. session kill by name simname ?signal hostname? Description Kill a simulation session by name. Parameters simname The name of the session. This is normally the basename of the executable. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost)

c Airbus Defence and Space 503 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, other- wise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified name could not be found.

session kill by pid pid ?signal hostname? Description Kill a simulation session by pid. Parameters pid The process id of the session. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, oth- erwise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified pid could not be found.

open log Description Allows the client to log to a file. After opening the log file everything that is sent to stdout and to stderr is also logged to the spedified file. Return value 0 if succeeded.

close log Description Closes the log file created by open_log. Return value 0 if succeeded.

27.5 EventInfo class

The EventInfo data is return by the event_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler event.

27.5.1 Method reference

name Description Get the name of the event. Return value The name of the event

state

504 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Get the number of the state where this event is defined. Return value The number of the state. state name Description Get the name of the state where this event is defined. Return value The name of the state. is standard Description Whether the event is a standard event or a user defined event. Return value true if it is a standard event, false if it is a user defined event.

27.6 WhereInfo class

The WhereInfo data is return by the where_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler break point location.

27.6.1 Method reference name Description Get the name of the task where the scheduler is currently stopped. Return value The task name. entrynr Description Get the entry point number of the current break point within the task. Return value The entry point number. Counting starts at 0.

27.7 EntryInfo class

The EntryInfo data is return by the entry_list method of the TaskInfo class. The methods allow you to retrieve the individual attributes of an entry point in a task.

c Airbus Defence and Space 505 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.7.1 Method reference

name Description Get the name of the entry point. Return value The name of the entry point.

breakpoint Description Get the break point status of the entry point. Return value True if a break point is set, false if not.

trace Description Get the trace status of the entry point. Return value True if a trace is set, false if not.

27.8 TaskInfo class

The TaskInfo data is return by the task_list method of the Session class. The methods allow you to retrieve the individual attributes of a task.

27.8.1 Method reference

name Description Get the name of the task. Return value The name of the task.

disabled Description Get the disabled state of the task. Return value True if the task is disabled, false if it is enabled.

entry list size Description Get the number of entry points of the task. Return value The number of entry points.

entry list idx

506 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Get the entry point information of the entry point with the given index. Parameters idx The entry point index (counting starts at 0). Return value An EntryInfo object describing the entry point information.

27.9 EventTypeInfo class

The EventTypeInfo data is return by the event_type_list method of the Session class. The methods allow you to retrieve the individual attributes of a client/server message (called event internally).

27.9.1 Method reference name Description Get the name of the message. Return value The name of the message. args Description Get the argument types of the message. This is a character coded string with one character for each argument type. Return value The argument types. argdescr Description Get a description of the arguments of the message. Return value The description of the arguments. id Description Get the numerical identifier of the message. Return value The numerical identifier.

27.10 SessionInfo class

The SessionInfo data is return by the session_list method of the Session class. The methods allow you to retrieve the individual attributes of a simulation session.

c Airbus Defence and Space 507 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.10.1 Method reference

sim hostname Description Get the host name running the simulation session. Return value The host name.

sim Description Get the simulation definition file. Return value The file name of the simulation definition file.

workdir Description Get the working directory. Return value The path name of the working directory.

simulator Description Get the simulator executable. Return value The path name of the executable.

schedule Description Get the simulator schedule. Return value The path name of the schedule file.

scenarios Description Get the list of scenario (MDL) files. Return value The list with path names of the MDL files.

dict Description Get the data dictionary file. Return value The path name of the data dictionary file.

model

508 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Get the model file. Return value The path name of the model file. recorderdir Description Get the recorder directory. Return value The path name of the recorder directory. initconds Description Get the list of initial condition files. Return value The list of path names of the initial condition files. calibrations Description Get the list of calibration files. Return value The list of path names of the calibration files. exports Description Get the exports file. Return value The path name of the exports file. alias Description Get the alias file. Return value The path name of the alias file. timestamp Description Get the time stamp. Return value The time stamp. prefcon Description Get the connection number. Each session has a connection number that can be used to connect a client to that session.

c Airbus Defence and Space 509 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value The connection number.

uid Description Get the UNIX user id of the user who started the simulator. Return value The user id.

gid Description Get the UNIX group id of the user who started the simulator. Return value The group id.

pid Description Get the UNIX process id of the simulation session. Return value The process id.

realtime Description Get the real-time state of the simulation session. Return value True if the simulator was started in real-time mode, false if it was started in non-real-time mode.

27.11 TmTcLink class

The TmTcLink class is used to create a packet link with a model in the simulator. The packet link can be used to send arbitrary packets (binary or not) to a simulator model and receive packets from a simulator model. Multiple packet links can be created. See Chapter 33 for detailed information on how to use the link.

27.11.1 Constructors

eurosim::TmTcLink link id mode Description Open one end of a TmTc link. Parameters link The name of the new TmTcLink object. id The symbolic name of the TmTc link. mode Mode is “r”, “w” or “rw”, similar to the modes of the fopen() function in the standard C library.

510 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

27.11.2 Method reference connect s Description Connect the link to the other end in a running simulator. Parameters s The Session object of the running simulator. Return value -1 on failure, 0 on success. write data Description Write a packet to the link. Parameters data The data (binary string). Return value The number of bytes sent or -1 on failure. read Description Read data from the link. Return value The data read as a binary string.

27.12 InitCond class

This class is used for the manipulation of initial condition files. This allows the user to create a new initial condition file or modify an existing file. Individual values can be set or modified. It is also possible to merge two initial condition files.

27.12.1 Constructors eurosim::InitCond ic filename dictfile Description Create a new set of initial conditions from an existing file. Parameters ic The name of the new InitCond object. filename The initial condition file. dictfile The path of the data dictionary file.

c Airbus Defence and Space 511 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.12.2 Method reference

add filename Description Merge an existing initial condition file with the current initial condition data. Parameters filename The path of the to-be-merged initial condition file. Return value true on success, false on failure.

write filename binary Description Write the initial condition data to a file. Parameters filename The path of the new initial condition file. binary If true, write a binary file, otherwise write the data in human readable (ASCII) format. Return value true on success, false on failure.

simtime Description Return the simulation time of the initial condition file. Return value The simulation time.

comment Description Get the comment of in the initial condition file. Return value The comment string.

get varlist failed Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables.

get varlist set Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables.

512 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

var value get path

Description Get the numerical value of a variable. Parameters path The data dictionary path. Return value The numerical value of the variable. var string get path Description Get the string value of a variable. Parameters path The data dictionary path. Return value The string value of the variable. var value set path value Description Set the numerical value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure. var string set path value Description Set the string value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure. list ?path? Description Get a list of child node names beneath a parent node. Parameters path The path of the parent node (default the root “/”). Return value The list of child node names.

c Airbus Defence and Space 513 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

27.13 ExtSimView class

This class wraps the External Simulator Access interface. Detailed information on the use of this inter- face can be found in Chapter 32.

27.13.1 Constructors

eurosim::ExtSimView view session id Description Create a new External Simulator Access view. Parameters view The name of the new ExtSimView object. session The Session object of the simulation session. id The symbolic identifier of the view.

27.13.2 Method reference

add var Description Add a variable to this view. Parameters var An ExtSimVar object of the variable to add to the view. Return value 0 on success, -1 on failure.

\bigskip \hrule \cxx{string}{get\_export\_id}{} \begin{method} \property[Description] Get the ˆexport_idˆ of this view \property[Return value] the ˆexport_idˆ \end{method}

\bigskip \hrule \cxx{string}{get\_view\_id}{} \begin{method} \property[Description] Get the ˆview_idˆ of this view \property[Return value] the ˆview_idˆ \end{method}

connect rw flags frequency compression Description Create a new view with the variables previously added to the view. Note that an excessive ammount of variables on the view might cause memory issues when calling connect. In such cases, spread the variables over multiple views. Parameters rw flags Read/write flags, 1 is read, 2 is write. frequency Update frequency in Hz.

514 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

compression Compression type to be used for the data transmission. 0 is no compression, 1 means that unchanched values in the view are not transmitted. Please note that in case the whole view is not changed, no update is sent in any case. Return value 0 is success, -1 is failure. This only is a local return value. The simulator emits a message evExtNewView with view id and export id as arguments on succesful creation of the requested view. change freq frequency Description

Parameters Change the update frequency of the view.

frequency The update frequency in Hz. Return value 0 is success, -1 is failure. send Description Send the view with the updated values to the simulator. Return value 0 is success, -1 is failure.

27.14 ExtSimVar class

This is the base class of the ExtSimVar* classes. It is not to be used directly.

27.14.1 Method reference type Description Get the variable type. Return value The variable type. is array Description Find out if the variable is an array variable. Return value true if it is an array. is fortran Description Find out if the variable is a Fortran variable. Only relevant for arrays, as the Fortran column/row order is different from C/Ada.

c Airbus Defence and Space 515 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value true if it is a Fortran variable.

nof dims Description Get the number of dimensions of the array variable. Return value The number of array dimensions.

dims Description Get the dimensions of the array variable. Return value The array dimensions.

path Description Get the data dictionary path of the variable. Return value The data dictionary path.

size Description Get the size in bytes of the variable. Return value The size in bytes.

27.15 ExtSimVar* classes

Below are the derived classes of ExtSimVar described. All similar methods are grouped to reduce the amount of documentation that only repeats the same information again and again. Therefore only two different cases are documented. One for the single element case and one for the array case. For both cases the following variants are possible: Char, Double, Float, Int, Long, Short, UnsChar, UnsInt, UnsLong and UnsShort. For arrays there are two variants: ExtSimVar*Array and ExtSimVar*FortranArray. To summarize for one type you can have the following classes: ExtSimVarChar, ExtSimVarCharArray and ExtSimVarCharFortranArray.

27.15.1 Constructors

eurosim::ExtSimVar* var path eurosim::ExtSimVar*Array var path dim0 ?dim1 dim2? eurosim::ExtSimVar*FortranArray var path dim0 ?dim1 dim2? Description Create a new variable to be used in an ExtSimView. Parameters var The name of the new ExtSimVar* object. path The data dictionary path dim0 The size of the first dimension. dim1 The size of the second dimension. dim2 The size of the third dimension.

516 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

27.15.2 Method reference get ?idx0 idx1 idx2? Description Get the value of a single variable or single array element. The variant without the idx* param- eters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension. Return value The value of the variable. The type of the return value depends on the type of the function. The type mapping is listed above in the introduction. set val ?idx0 idx1 idx2? Description Set the value of a single variable or single array element. The variant without the idx* parame- ters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters val The new value. The type of the value depends on the type of the function. The type mapping is listed above in the introduction. idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension.

c Airbus Defence and Space 517 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

518 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part V

Interface Reference Guide

c Airbus Defence and Space 519

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 28

Hardware Interface reference

28.1 Introduction

EuroSim is often used in applications that require hardware interfaces. A typical example is a simulation setup where a control computer is executing in a simulated environment, or where a control computer with real sensors and actuators operate in a simulated environment to support verification or training. Models running in EuroSim then simulate or stimulate the equipment in such a manner that the control computer operates in an environment that equals its operational environment. To simulate or stimulate the equipment in such case, generally requires interfacing with realtime busses and synchronization with external clocks. Essential in such case is the response time of the simulation as jitter and latencies must be limted and guarded. It must be assured that the product under test is verified in an environment that matches the end situation, otherwise the measurements and thus the verification is not representative for the later operational use. Essential in such case is the timely exchange of data because the product under test in its intended environment operates in the real world. Often it is stated that modern computers are fast enough to assure that such response is in time, but only a hard real-time system as EuroSim can provide the assurance that that is actually the case, and will provide feedback if it isn’t. EuroSim Mk7.1 provides three different hardware interfaces 1:

• External Clock Interface

• External Event Handler

• External Interface libraries

External Clock support allows EuroSim to be driven by an external clock source and use synchronized time sources. Details are described in Section 28.2. External Event Handling is essential for real-time (avionics) and allows a variety of events from external sources, such as interrupts, to trigger events in the schedule, including passing of messages. A detailed description of this interface can be found in Section 28.3. Finally, External Interface libraries , also called Userland libraries, provide additional code to make access to hardware easier. Further information can be found in Section 28.4. Note that in the past, EuroSim integrated solutions for specific hardware into the EuroSim product. In the era of main frames and specialised computers such as the SGI systems the commonality of the hardware that was used was large and hence only a minimal set needed to be maintained. However, such approach no longer meets customer demand. In practice we find that customers prefer to be able to select and integrate their specific hardware. Since EuroSim Mk 5.3 the new strategy is therefore to open up the EuroSim hardware interface in a plugin approach and support the community by providing available plugins in source code format as example. Several plugins are made available by the consortium such as for the Aim Mil1553 APX-1 board, others are contributed by customers who prefer to see their plugin as part of the EuroSim distribution.

1Not supported on the Windows platform.

c Airbus Defence and Space 521 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

28.2 External Clock Interface

28.2.1 Introduction External clock support provides the user with the capability to install an external clock as the EuroSim master clock. This involves two aspects

• Providing the heartbeat to the EuroSim scheduler via interrupts from the external device,

• Reading the time from the external clock instead of the internal computer clock.

Note that it is also possible to have an external driven heartbeat while reading the internal clock, for instance if time is synchronized over NTP. Following sections describe the selection of an external clock (Section 28.2.2), the implementation of an external clock interface (Section 28.2.3), and alternative approach using NTP synchonization (Sec- tion 28.2.4) and the deprecated IRIG-B built-in support option (Section 28.2.5).

28.2.2 External Clock Selection At startup of the Scheduler, EuroSim will install and initialise the clock that is configured in the Sched- uleEditor. The available clocks in the ScheduleEditor depend on the operating system. The largest selection is provided on the Concurrent Redhawk platform as shown in figure 28.1.

Figure 28.1: Available clocks on a Concurrent Redhawk operating system

: The options offered are:

• Internal clock: This is the clock maintained on the motherboard.

• Plugin clock: This allows the user to select a plugin library for a clock

• IRIG-B clock: This utilizes an Irig-B card via the builtin support of the ModelEditor (see Sec- tion 28.2.5).

• RCIM clock: Selecting this clock will read the time from the RCIM card, allowing GPS and RCIM chain synchronized clocks.

• POSIX Signal: Signals in the range RTMIN to RTMAX can be routed to the EuroSim master clock to drive the scheduler.

• RCIM interrupt: Ticking the EuroSim clock on the basis of the external interrupt input on the RCIM card

522 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• EuroSim Compatible Device (type 1): Ticking the EuroSim clock on the basis of a EuroSim Compatible driver. These devices provide specific ioctl functions which EuroSim uses to wait for interrupts.See Section 28.3.4.1 on how to make a driver EuroSim compatible.The plugin is preferred, this option is however still available.

In case of Windows, there is currently only the Internal clock. In case of Red Hat Linux there are several options, including the internal clock and a full external clock plugin solution, as well as a signal based and EuroSim compatible device externally triggered solution. Note that the default basic frequency of the scheduler is 100 Hz, which means that one interrupt stands for 10 ms in real-time. The scheduler assumes that with every heartbeat the configured time interval has passed. For the internal clock and the two synchronizable external clocks, the user defined frequency configures the clock. For the interrupt clocks,however, the frequency defines only the assumed interval and the simulation time is incremented accordingly. If for the latter the interval between interrupts does not match the actual interval, the EuroSim simulation time will be faster of slower then realtime but your wallclock is not affected.

28.2.3 External Clock Plugin The Plugin solution for clocks requires the user to build a shared library that implements the functions declared in the file esimClock.h which is provided in the include directory of the EuroSim installation. The user specifies the path to the shared library in the ScheduleEditor Connfiguration dialog that is part of the Tools menu:

Figure 28.2: Specifying the location of the Clock Plugin in the ScheduleEditor

: The functions to be implemented by the user in the plugin and declared in the esimClock.g header file are: int esimClockOpen(void) void esimClockClose(void) int esimClockGetres(struct timespec *res) int esimClockGettime(struct timespec *tp) int esimClockTimerSettime(int id, const struct itimerspec *value) int esimClockTimerWait(int id) int esimClockTimerDelete(int id)

These functions are thus to be implemented by the developer of the plugin. The esimClock interface resembles the functions of the Posix clock and timer interface. The Open and Close calls allow opening a device and closing it, the unix conventions are followed thus on success zero is returned. The clock resolution is normally not required but can be implemented by setting the resulolution in the struct timespec that is passed as argument. The gettime function returns the current wallclock time to EuroSim

c Airbus Defence and Space 523 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

by setting the time read from a device in the passed timespec argument. The subsequent three time functions are passed an id, which has one of the following values as defined in esimClock.h:

#define ESIM_CLOCK_TIMER_ONESHOT 1 //!< timer id for oneshot timer #define ESIM_CLOCK_TIMER_PERIODIC 2 //!< timer id for periodic timer #define ESIM_CLOCK_TIMER_1PPS 3 //!< timer id for 1PPS timer

These values identify if the clock is periodic or single shot, and whether the device should wait to sync to 1PPS. It follows from the generic interface in EuroSim that all of these must be defined, but the user will initially see the 1PPS and subsequently the periodic id. When delaying the return when the 1PPS is passed in order to sync on 1PPS, EuroSim may give a timer error on startup, this however only occurs once on startup. You may ignore the calls with ID 1PPS if you do not require EuroSim to be started on a 1 second signal. The esimClockTimerSettime then is used to set a timer on which TimerWait then waits for its expiration. Make sure the TimerSettime is setup for periodic alarms for a normal simulation. EuroSim will call esimClockTimerDelete to clean up a timer at the end of the simulation run. As an example of a plugin implementation the examples provided with EuroSim contain an implemen- tation of a Posix based plugin implementation. This example thus implements what is internally imple- mented in EuroSim for the Internal clock using a Plugin solution and hence does not need any special hardware.

28.2.4 NTP Synchronized clock The External clock interfaces in the previous section illustrate how EuroSim can directly utilize special- ized timing devices for either time or heartbeat or the combination thereof. There is however another approach that is utilized; slaving the internal clock to an external clock: NTP synchronization. This method is applied in test equipment by Airbus Defence and Space using a Meinberg Irig-B interface board that comes wiht the capability of using NTP to synchonize the onboard computer with the clock on the Meinberg card. The approach has proven to provide excellent result and only requires the config- uration of the NTP solution in Linux systems. Note that in this case EuroSim’s wallclock is the hosts wallclock. This may be a problem when the time is switch to the future as the Eurosim license will check the host date and will state an expiration. If this is the case the plugin is the best solution or contact the EuroSim helpdesk to find an optimal approach for you specific case.

28.2.5 Irig-B (deprecated) Any IRIG-B card can be used with EuroSim as long as the user provides a shared library that implements the interface specified in the include file $EFOROOT/include/esim irigb.h. To use your own IRIG-B card, take these steps:

1. Write the glue layer between the userland library of your IRIG-B card and EuroSim by implement- ing the functions in $EFOROOT/include/esim irigb.h. Compile this into a shared library with position independent code (-fPIC).

2. Edit $EFOROOT/etc/EuroSim.capabilities. Update the libs entry of the IRIG-B capability so that it mentions the name of your ’glue library’. The default setting is tfp, which will load libtfp.so for the Datum IRIG-B card.

3. Enable the capability ’IRIG-B support’ in the build options of the ModelEditor.

4. If necessary, add the directory where you keep your ’glue library’ to build options / loader options in the ModelEditor.

5. Select IRIG-B as time source in the ScheduleEditor.

524 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

28.3 External Event Handler

28.3.1 Introduction The External Event Handler solution is essential when integrating a realtime device such as an avionics bus like Mil1553. The key to realtime systems is a seperation of control and data. In a non realtime streaming solution, the data is handled when convenient after arrival. On a realtime bus however, the data may only be available for a short time, and when they contain commands for a device, the response must be written to bus at a certain moment in time. In practice, interface devices that support such realtime busses are capable of sending an interrupt to signal to the simulation that it needs to take action, including paramters that define the current situation. Looking from the perspective of the EuroSim scheduler these interrupts are external events, which can need to be caught using an InputConnector on the schedule canvas which will trigger an association task. The standard InputConnectors however are associated with the scheduler heartbeat and thus pass on events in synchronization with the heartbeat of the scheduler, meaning at the start of a minor scheduler cycle. This delay may be far to slow for the realtime bus interface and therefore the user is able to create Event Handlers. An EventHandler owns a very high priority thread on a realtime processor in parallel to the executer threads that execute tasks. The EventHandler thread is blocked on an interrupt source and when awoken will take control of the processor core and raise an InputConnector that is associated with the EventHandler. The InputConnector will immediately activate all dependent tasks. The tasks follow the normal scheduling parameters that can be defined in the ScheduleEditor. Normally you want a high priority and other tasks shold not be non-preemptive to benefit from the very fast asynchonous event handling that Event Handler offer. There should not be more than one Eventhandler per core in the system. Figure 28.3 illustrates the above explained event handler mechanism, showing the route from an interrupt from a device to a running task in the scheduler.

Figure 28.3: Architecture of the Event Handler mechanism

In some cases the OEM provides a device driver which creates a thread to handle interrupts from the

c Airbus Defence and Space 525 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

device. This approach will not be realtime as EuroSim isolates the processors and will push the thread to the remaining cores where it must compete with the rest of the system and is susceptible to for instance network hickups. The event handler solution is actually creating the thread in a manner that is guaran- teeing fast response. In such case the EuroSim plugin solution may be used by copying the code that normally runs in the thread of the manufacturer into the event handler thread. In many cases the host computer will be fast enough, but it may fail without informing the user and hence test results are by definition unreliable. Following sections explain how event handlers are defined and used in the Schedule Editor (Section 28.3.2, how they are programmed for the various options (Section 28.3.3 and (Section 28.3.4) and an elaborate example of implementation for a Mil1553 bus (Section 28.3.4.4).

28.3.2 ScheduleEditor Event Handler usage The event handlers are defined in the scheduler editor with a specialized Event Handler Configuration dialog which can be found in the Tools menu.Here the user can choose what the source of the external event is. External events can be generated by:

• EuroSim Compatible Device (type 1): EuroSim compatible devices have device drivers adapted for EuroSim. These devices provide specific ioctl functions which EuroSim uses to wait for interrupts. The Type 1 device is the classic EuroSim compatible device which can not pass data to EuroSim in association to an interrupt

• EuroSim Compatible Device (type 2): This second generation of compatible devices has a different set of ioctls and do allow passing data with interrupt from the device ioctl to the EuroSim event handler.

• EuroSim Compatible Plugins: these are shared libraries (plugins) that are loaded by EuroSim from the path specified in the Event Handler Configuration dialog and must implement the functions defined in the include file esimEH.h. The plugin approach is the latest development and provides the same capabilities as the type 2 device, however allowing the user to implement how it accesses the available interface provided by the manufacturer instead of needing to modify the manfacturer’s source code to add the EuroSim required interface.

• Signals: available are the signal numbers between SIGRTMIN and SIGRTMAX that are not used by EuroSim internally (use numbers above 39)

• POSIX named semaphores: see the manual page of sem open. The semaphores can posted by any application on the same machine.

In the past the usage was mostly via the Compatible Device Type 1. This is expected to be replaced mostly by the plugin solution which gives much more flexibility to users. The Type 2 device is also suitable for those users that do not mind modifying drivers. The actual implementation required is not difficult, but programming at the kernel level easily leads to hangups of the system and is not for the faint at heart. The signals interface is sometimes usefull for debugging as it allows easy triggering of the event handler via the kill command on unix command line. The posix named spemaphores can be used for synchonization with other applications at the unix level, but are rarely used. When configuring the Event Handlers the user can select either an Automatic or User Defined Event Handler. When configured automatic, there can only be one input connector which must have the same name as the Event Handler. These are intended for situations where the interrupt source is not further decoded in the Event Handler, but directly linked to an input connect. When configured as User Defined, the user can install a call-back which will be activated by the Event Handler when it wakes up. From this call-back the user can make a selection of which input connectors to raise defined on the ScheduleEditor canvas as long as they are associated with the Event Handler. Such selection can be made on the basis of data that is passed by the device with the interrupt or by accessing globally available memory in the driver to identify the cause of the interrupt. Quite often however users select Automatic as it is easier to

526 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

use and still data that is provided with the interrupt is passed on to the InputConnector, thus the user can fetch the data and decode it in a EuroSim entrypoint. Following is a listing of a EuroSim user defined event handler callback routing that decodes the data that is passed with the interrupt, as well as how this callback is installed:

28.3.3 Programming User Defined Event Handlers User defined event handlers require the installation of a callback in the event handler through which the user can arrange which event in the schedule is to be raised and which data is to be passed to the InputConnector. The following interface is available for installing the event handler callback: typedef int (*esimEventHandlerDispatchFunc)(esimEH *context, const void* msg, int size,void* user_data); int esimEventHandlerInstall(const char *name, esimEventHandlerDispatchFunc dispatcher, void *user_data); int esimEventHandlerDispatch(esimEH *context, const char* name, const void *msg, int size); int esimEventHandlerUninstall(const char *name);

The esimEventHandlerInstall function is used to install the callback function programmed by the user in the Event Handler with the provided name. That name must thus match an event handler defined via the Schedule Editor. The user data argument is a pointer that is passed to the callback, on every activation. The callback is activated directly after the wait in the event handler unblocks. The arguments msg and size contain size number of bytes of information passed with the interrupt. The user should inspect this data in his code if the size is larger than zero and subsequently call the esimEventHandlerDispatch function to activate an InputConnector on the schedule canvas. The context parameter is a handle that refers to the EventHandler in which this user defined handler callback is activated. This must be passed to the call esimEventHandlerDispatch in addition to the name of the event, the size of the message to pass and a size argument to indicate how many bytes are passed to the input event. The task that is activated as a result of the InputConnector activation can use the esimEventGetData call to retrieve the message that was passed on from the event handler. Example of external event handler user code: #include #include #include "esim.h" #include "esimEH.h"

#define START_ID "Start" #define STOP_ID "STOP" #define SHUTDOWN_ID 2 #define ERROR_ID 3

#define START 0x04 #define STOP 0x05 #define PANIC 0x10

#define STREQ(a,b) (!strcmp(a,b)) enum hw_status { DO_RESET, INTERRUPT };

c Airbus Defence and Space 527 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

extern enum hw_status hw_status_get(void); extern void hw_reset(void); extern int hw_data_get(void); extern void hw_shutdown(void);

static int dispatcher(esimEH *context, const void* msg, int size, void *user_data) { int status = *(int*)msg; int data;

(void) user_data; /* not used */ (void) size; /* not used */

data = hw_data_get(); switch (status) { case START: esimEventHandlerDispatch(context, "START" , &data, sizeof(data)); break; case STOP: esimEventHandlerDispatch(context, "STOP", &data, sizeof(data)); break; case PANIC: hw_shutdown(); esimEventHandlerDispatch(context, "SHUTDOWN", &data, sizeof(data)); esimEventHandlerDispatch(context, "HW_ERROR", &data, sizeof(data)); break; default: break; } return 0; }

/* function for event handler installation */ int event_handler_install(void) { return esimEventHandlerInstall("HW_INT", dispatcher, NULL); }

/* function for event handler uninstallation */ int event_handler_uninstall(void) { return esimEventHandlerUninstall("HW_INT"); }

/* entry point raised by "START" */ void started(void) { int hw_data; struct timespec occurrence,raise;

int size = sizeof(hw_data); esimEventData(&hw_data, &size); esimEventTime(&occurrence,&raise); esimMessage("HW started: data = %d occurrence={%jd:%ld} raise={%jd:%ld}", hw_data, (intmax_t)occurrence.tv_sec, occurrence.tv_nsec, (intmax_t)raise.tv_sec, raise.tv_nsec);

528 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

}

An extensive example of the user defined event handler usage can be found in the AimMil1553 example passed with the EuroSim distribution. This example acutally receives the loglist from the driver that contains details on what caused the interrupt. For instance an end of scenario message is not necessarily passed to the EuroSim scheduler. However, if it is a reception of data at a subaddress and the user had defined in the MIL1553.cfg file that an interrupt is to be raised, then the labelname of the message is used to find the input connector to activate.

28.3.4 Programming Event Handler Plugins and Devices External events such as interrupts are caught and transformed to EuroSim events by EuroSim Event- Handlers. The configuration of these event handlers can be performed via the Schedule Editor’s Event Handler dialog. The Compatible devices and Event Handler Plugins are to be programmed by the user. For devices this usually requires the implementation of a small extension in the driver provided by the manufacturer, which is described in sections Section 28.3.4.1 and Section 28.3.4.2. For plugins it in- volves the implementation of a set of predefined functions and linking that code into a shared library, which is elaborated in Section 28.3.4.3. For the plugin approach this is not required, but often usefull as the plugin may directly call the ioctls in the driver.

28.3.4.1 EuroSim compatible devices Type 1 The EuroSim compatibel device Type 1 is the classic EuroSim compatible device solution, availabel since EuroSim mk3. This solution requires the extension of a driver with three IOCTLs that are directly accessed from EuroSim to be able to handle the interrupt. For the EuroSim compatible devices approach it is required to have the source code from the manufacturer when extending a driver provided with an interface board. The user should verify that the driver source is provided as part of the board support package, preferably including tooling to build and install the driver. To make the driver into a EuroSim compatibel device the driver must be enhanced with three ioctl() commands: OS_IOCTL_WAITINT (95), OS_IOCTL_BREAKWAITINT (96) and OS_IOCTL_GETIRQ (97). These commands are defined in osIntr.h. The OS_IOCTL_GETIRQ command is optional.

• The call to ioctl(OS_IOCTL_WAITINT) must wait for an interrupt or an event to arrive. It must block forever if needed. It can only return on two occasions: an incoming interrupt (or event) or after an ioctl call with parameter OS_IOCTL_BREAKWAITINT. Whenever the call returns EuroSim expects that an interrupt (or event) has arrived.

• The call to ioctl with command OS_IOCTL_BREAKWAITINT is issued when the application ex- its or when the user calls esimEHUninstall(). This ensures that the thread blocking on the ioctl(OS_IOCTL_WAITINT) can terminate properly.

• The call to ioctl with command OS_IOCTL_GETIRQ is issued when the event handler is installed. If implemented, then this ioctl is to return the IRQ number used for interrupts sent by this driver. This IRQ number is used by EuroSim to ensure that the interrupts go only to the CPU where the event handler is running.

Note that if the device supports interrupts then the manufacturer usually already provides some IOCTLs related to interrupt handling. What the user needs to do is to relate the prescribed IOCTL numbers in the driver to this implementation as it is quite rare that the manufacturer chosen numbers and interface would exactly match that of EuroSim. The existing type 1 enhanced drivers available with earlier versions of EuroSim are outdated. Of course the EuroSim consortium can develop drivers, but it very well possible to enhance a driver yourself into your own EuroSim compatible device type 1 driver. If desired the driver can be passed to the consortium for inclusion as example code in the distribution. The consortium can not maintain the driver, but the driver will be in a standard location and part of the distribution.

c Airbus Defence and Space 529 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

An example if a device type 1 driver can be found in the examples when the user has access to the Aim 1553 APX board support package. The patch file in the package will add the three IOCTLs to the driver. Below is an extract which shows the added IOCTLs in this driver. As can be seen the code added is minor and hooks into existing wait queues in the driver

28.3.4.2 EuroSim compatible devices Type 2 The EuroSim compatible device type 2 is more capable then the device type 1 as it can pass data with the interrupt. For instance the Aim Mil1553 driver from the manufacturer supports passing a loglist on return of an ioctl that contains all the reasons for interrupts. This is event data that is to be passed to EuroSim such that the event handler can decide which event to raise (e.g. transfer completion, data arrival, mode code braodcast received etc). The alternative would be that on receiving an interrupt the user code that is activated retreives the loglist and inspects registers. This however due to even a minor delay is not the situation encountered when the driver was processing the interrupt. Similar to the Type 1 solution, the type 2 requires the driver to be enhanced with three ioctl() com- mands: OS_IOCTL_WAITINTDATA (98), OS_IOCTL_BREAKWAITINTDATA (99) and OS_IOCTL_GETIRQ (97). The command OS_IOCTL_GETIRQ is shared with the Type 1 solution and optional, but if not implemented EuroSim is not able to optimize the interrupt routing to the appropriate processor (core) thus all pro- cessors (cores) will receive the interrupt. As for type 1 compatible drivers, for the EuroSim compatible devices approach it is required to have the source code from the manufacturer when extending a driver provided with an interface board. The user should verify that the driver source is provided as part of the board support package, preferably including tooling to build and install the driver. Being more capable, the Type 2 device also requires additional parameters with the ioctl calls. In par- ticular the WAITINTDATA command is provided a block of memory that the ioctl can fill and on return will be forwarded as message to the event handler. This datablock is structured as:

struct { int size; //input: bytes available, output: bytes filled int returnreason; //1=data available 2=timeout (no user dispatch) char returndata[512]; //free space for return data } esimdata_t;

• The call to ioctl OS_IOCTL_BREAKWAITINTDATA is issued when the application exits or when the user calls esimEHUninstall(). This ensures that the thread blocking on the ioctl (OS_IOCTL_WAITINTDATA) can terminate properly. In case the BREAKWAITINTDATA has a timeout mechanism this IOCTL does not have to force a release of the BREAKWAITINTDATA ioctl, but it can provide a usefull service by passing a timeout value back to the Event Handler which states how long it is expected to take before the WAITINT will terminate. As for WAITINTDATA the memory space for the timeout value is provided as an unsigned pointer passed as argument to the ioctl call. Setting this value in the driver prevents EuroSim from terminating to quickly and generating errors on termination because the Event Handler thread has not terminated. This is an optimization however, it is not required and the user should typically first ignore this argument and see if an error arises.

• The call to ioctl OS_IOCTL_WAITINTDATA must wait for an interrupt or an event to arrive. It may have a timeout however, as long as it provides that information back as argument to the Event Handler as return reason. The Event Handler thread will then immediately call the WAITINTDATA again. The timeout is an alternative method used in drivers to assure that the ioctl is released to prevent a hang up of the system. The normal reason is of course is that an event has arrived, or the BREAKWAITINTDATA ioctl has been called, in which case the return reason should be data available.

• The call to ioctl with command OS_IOCTL_GETIRQ is issued when the event handler is installed. If implemented, then this ioctl is to return the IRQ number used for interrupts sent by this driver. This IRQ number is used by EuroSim to ensure that the interrupts go only to the CPU where the event handler is running.

530 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

28.3.4.3 EuroSim Compatible Plugin The alternative for using a modified device driver is to implement an event handler plugin. The plugin code should include the esimEH.h header file, implement the prototyped plugin functions and link this into a dynamic library. EuroSim will on startup load the dynamic library from the path that is defined in the Event Handler Configuration dialog in the Schedule Editor and resolve the implemented functions such that they are called from the Event Handler thread. Following are the prototypes of the to be implemented functions as defined in the esimEH header file: int esimEventHandlerSetup(const char *handlername, int procesor,int *irq ,void **userarg, int (*esimreport)(int Severity, const char *fmt, ...)); int esimEventHandlerWait(const char *handlername, void *msg, int *size ,void *userarg, int (*esimreport)(int Severity, const char *fmt, ...)); int esimEventHandlerWakeup(const char *handlername, unsigned *timeout ,void *userarg, int (*esimreport)(int Severity, const char *fmt, ...)); int esimEventHandlerClose(const char *handlername ,void *userarg, int (*esimreport)(int Severity, const char *fmt, ...)); Following elaboration of the functions explains the purpose and arguments of the functions. In all the functions the pointer userarg is a pointer to communicate private data amongst the EventHandler func- tions. Furthermore report is a function pointer to the eurosim esimReport function. With this function pointer the user thus calls the esimReport and logs information to either the daemon log or the log in the Simulation Controller depending on the state of the initialisation. • esimEventHandlerSetup The Setup routine is called once during the initialisation of the scheduler to allow the user to setup the device that the event handler relates to. There can be multiple handlers active that use the same plugin potentially, therefore the routing is passed the name of the eventhandler for which it is called (defined in the Schedule Editor). Subsequently the user is provided the processor on which the event handler executes. Note that if such processor is 0, than the simulation is not running realtime. The irq number must be provided to EuroSim by the user to allow EuroSim to optimize the interrupt routing. Such information generally must be retrieved from the device or via the /proc file system. • esimEventHandlerWait When the eventhandler calls the Wait function it expects to be blocked untill an interrupt occurs. Typically this means waiting on an ioctl as performed by the device type event handlers, but in this case the user can program how to do that and use the ioctl that is already available in the driver or use the library provided by the manufacturer. If there is data to be fed back to the eventhandler, then such data can eb copied to the buffer pointed to by msg. The length ofthe buffer is provided by *size. The user has to set *size to the amount of bytes copied into the buffer. • esimEventHandlerWakeup When the event handler calls the Wakeup, the user should force the Wait function to return. This for instance is required when the user presses Abort in the simulation controller. The user can set the timeout to inform EuroSim on return of the function how long it will take to achieve the release. • esimEventHandlerClose The eventhandler calls the close function on termination of the simulator. The user should use this opportunity to close the device access and clean up and memory.

28.3.4.4 AIM Mil1553 Plugin With the release of the 12.1 version of the AIM BSP and the development of the Mil1553 Front-End model a plugin has come available for AIM Mil1553 PCI and PCIe boards which utilize the AIM li- brary API for non realtime functions, but use memory mapped IO directly on the AIM boards to assure

c Airbus Defence and Space 531 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

maximum realtime performance. The plugin combines the API for realtime data and control access with the functions for event handlers in one sinle shared library. This library can both and simultaneously be used as a plugin for the Mil1553 Front-End model via its MIL1553 configuration file as well as being used in an eventhandler. The plugin is capable of handling multiple boards. For catching interrupts via EuroSim’s event handlers it can be used in multiple eventhandlers. The handler name should be of the name aim_milx where x is the minor device number. For example, to catch interrupts from device /dev/aim_mil0 an eventhandler should be created that is of type automatic and named aim_mil0. The interrupt loglist entry as described in the AIM reference manual for APX and APE cards is passed as event data with the interrupt. Using esimEventData() from an entrypoint in a task directly attached to an event aim_mil0 the user gets the data of the event and can interpret the data according to the data structure definition denoted in the AIM reference manual for their interupt handler function. The AIM Mil1553 plugin library is called libEsimAimMil1553Plugin.so and is located in the lib or lib64 directory of $EFOROOT on your filesystem. Because these directories are already in your dynamic library search path due to the installation of EuroSim no complete path is needed. The plugin does required the installation of the AIM 12.1 BSP, patched by the EuroSim consortium. Please contact the helpdesk to receive the required patches. EuroSim is actively cooperating with AIM to move these patches into the baseline. The EuroSim helpdesk can assist you in applying the patch. The EuroSim AIM MIl1553 plugin library works together with the netlink socket support in the AIM driver. When using the plugin in EuroSim Mk7.1 the simulation may end with a message that the event handler for the aim_milx device is not terminating within its timeout. This is not a problem as the resourced are freed when the simulator terminates. The EuroSim consortium expects to solve this issue in future versions.

28.4 External Interface libraries

28.4.1 Introduction External Interface libraries are userland libraries that provide a higher level API to interface boards or devices in the computer. Often these libraries are provided by the hardware vendor of interface cards such as for mor exotic busses such as Mil1553 that are not standard part of the computer. Additionally for more used busses generic open source drivers may be found such as for CAN. For commondevices as COM, USB and ethernet the code is part of the operating system. There can still however be good reason to provide a library with EuroSim. Performance can be a reason for instance because the library from the manufacturer is not suitable for realtime use, creating for instance threads to handle interrupts or using slow ioctls instead of memory maps. Alternatively, the manufacturer or open source liubrary aims at supporting a larger set of uses cases, where an extra layer may make the library easier to use in a specific context. Finally, a reason for EuroSim to include such libraries in the past was to separate the model code from manufacturer specific implementations. In line with the approach to solve hardware interfaces together with the community rather than delivering integrated hardware support, EuroSim now provides interface libraries as part of the examples in source code. Users can verify and adapt the software to their specific needs. Adaptations that are submitted to the EuroSim helpdesk can be integrated into then next release or even a patch release, such that users are sure that they will receive the code as part of future distributions. If desired we will honor contributors the code, and include a SoftwareRelease note to state the status and last verification of the software. The source code for the existing EuroSim Serial interface for RS232 and RS422 has been moved to the SerialInterface example. The esimMil1553 interface is replaced by the AimMil1553 interface, which is currently fairly basic but will be expanded in future releases, hopefully with support from the User community. As a general hint on developing external interface libraries, there are a number of points to consider:

• How do you initialize and configure the interface

532 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• Are read and write operation non-blocking, otherwise either such operations need to be performed in a non real-time task, or in a seperate thread

• Are read and write operations realtime? Even when non-blocking, read and write operations that read data via kernel operations damage the realtime performance of EuroSim

• What dependency is created on the specific interface card versions

The source code in the src directory of the EuroSim installation can be used by all EuroSim users in their EuroSim based projects without copyright restrictions, we also ask that this is honored when you provide improvements back to the EuroSim helpdesk.

28.4.2 Serial interface The example SerialInterface that is included in the src directory of the EuroSim installation provides non-blocking read and write operations for standard serial devices. The Serial interface uses the standard serial device drivers that already supports non-blocking access. However, data must be buffered on read failures (when not enough data is available). The Serial interface provides the initialization of the drivers and the buffering of data. Before usage you may have to copy the directory to your local directory, adjust the directory and file rights and build using the makefile. Alternatively you can do this within the src/SerialInterface fdirectory if you have root rights (administrator task). For detailed information, see the esimSerial manual pages contained in the example.

28.4.3 Mil1553 interface For usage in the avionics testbench at the European Space Agency, Airbus Defence and Space integrated the Aim 1553 APX board with EuroSim. This interface board has a rich API and provides the capability to simulate the bus controller and remote terminals as wel as monitoring busses. The event handling interface to the Linux driver has already been elaborated in the Event Handler section of this chapter. Airbus Defence and Space in addition extended the driver with code to support memory mapped access to read and write date from the board as fast as possible into this Linux driver. Aim has acknowledged the request to integrate this memory mapped access into future releases. Currently the AimMil1553 directory that is in the src directory of your EuroSim example contains a patch file for the 11.20 revision of the APX Linux bsp which the user can download from the Aim website. The example however also includes a higher level API that allows the user to quickly setup remote terminals, buscontroller and event handling. The library reads the definition from the user and subsequently programs the card in accordance to this definition. The library will check if memory mapped access is available and utilise that for fast access when found. There are still areas to expand on, such as error injection and configuration of communciation aspects as gap, online and offline terminals etc. but in general the library makes a good starting point and will provide the user with a system that is running very quickly. The interface is not implemented as a library, but as source code that can be included in EuroSim projects. The concept of the Mil1553 interface is based on transferring messages. The fact that the MIl1553 bus is a realtime bus affects the moment of transfer of messages and the size of messages. A configuration file defines the Remote Terminals and Bus Controller simulation, the messages (or transfers in Mil1553 language) that can flow from either a Remote Terminal sub address to a Bus Controller subaddress or vice versa, and the minor and major frame. All of the elements have a label which is a string to be able to find a specific transfer. Read and Write routines then allow the user to read the data of a transfer from the interface board, or write the date for a transfer to the board memory. The momentum that such transfer must be performed is connected to the scheduler via the event handler interface, where in the configuration file it can be stated if an event should be raised on transfer completion (this part is explaing in the event handlers section). The essence is that the runtime API is thus simple: Initialise the device and read the configuration file, subsequently read and write transfers, terminate the unit when done. The control is decoupled as it should be for realtime busses, the timing is connected to the scheduler.

c Airbus Defence and Space 533 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Following listing shows an example of an example MIL1553 configuration file:

# Common Settings

# Bus Controller Definition: minor cycletime(msec), #major cycles (0=endless), bus (PRIM, SEC) BC: 50, 0, PRIM

# Remote Terminal Definition: Name, Address, bus (PRIM, SEC, BOTH) RT: GYR1_RT, 7, BOTH RT: GYR2_RT, 8, BOTH RT: RWL1_RT, 12, BOTH RT: RWL2_RT, 13, BOTH RT: RWL3_RT, 14, BOTH RT: THRM_RT, 23, BOTH RT: POWR_RT, 24, BOTH RT: PAYL_RT, 25, BOTH RT: BRDCST_RT, 31, BOTH

# Transfer Definition: #XferName, From_name (RTname or BC), From_SA, To_name (BC or RTname), To_SA, # number of words, INTON || INTOFF voor interruptgeneration by RT reception # #Note: To send a modecode, use 0 for SAs, the wordcount should then # be the modecode number

XFER: SYNC, BC, 0, BRDCST_RT, 0, 17, INTON # Sensors and Actuator measurements

XFER: GYR1SA2BCRT, GYR1_RT, 2, BC, 2, 12, INTOFF XFER: GYR2SA2BCRT, GYR2_RT, 2, BC, 3, 12, INTOFF XFER: RWL1SA2BCRT, RWL1_RT, 2, BC, 2, 12, INTOFF XFER: RWL2SA2BCRT, RWL2_RT, 2, BC, 2, 12, INTOFF XFER: RWL3SA2BCRT, RWL3_RT, 2, BC, 2, 12, INTOFF XFER: RWL4SA2BCRT, RWL4_RT, 2, BC, 2, 12, INTOFF XFER: THRMSA2BCRT, THRM_RT, 2, BC, 2, 32, INTOFF XFER: POWRSA2BCRT, POWR_RT, 2, BC, 2, 32, INTOFF XFER: POWRSA3BCRT, POWR_RT, 3, BC, 3, 17, INTOFF

#Sensors and Actuator commands XFER: GYR1SA2RTBC, BC, 2, GYR1_RT, 2, 1, INTOFF XFER: GYR2SA2RTBC, BC, 2, GYR2_RT, 2, 1, INTOFF XFER: RWL1SA2RTBC, BC, 2, RWL1_RT, 2, 5, INTOFF XFER: RWL2SA2RTBC, BC, 2, RWL2_RT, 2, 5, INTOFF XFER: RWL3SA2RTBC, BC, 2, RWL3_RT, 2, 5, INTOFF XFER: POWRSA2RTBC, BC, 2, POWR_RT, 2, 2, INTOFF XFER: SSMMSA2RTBC, BC, 2, SSMM_RT, 2, 2, INTOFF XFER: PAYLSA2RTBC, BC, 2, PAYL_RT, 2, 11, INTOFF

#Minor Frame definition: Name, MINOR: MINOR1, SYNC, GYR1SA2BCRT, GYR2SA2BCRT, RWL1SA2BCRT, RWL2SA2BCRT, RWL3SA2BCRT, THRMSA2BCRT, POWRSA2BCRT, POWRSA3BCRT,

534 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

RWL1SA2RTBC, RWL2SA2RTBC, RWL3SA2RTBC, POWRSA2RTBC, SSMMSA2RTBC, PAYLSA2RTBC

#Major Frame definition (there can only be one) MAJOR: MINOR1

The API contains the following functions: TODO elaborate API

The configuration file defines the BusController, Remote Terminals, Transfers, Minor and Major frames. The Syntax is

BC: minor_cycle_time, major_cycles (0=continuous), bus where: minor_cycle_time is float in msec, bus is PRIM | SEC RT: RT_label, RT_address, bus(PRIM | SEC |BOTH) Where: RT_label=max 16 char XFER: , From_name, From_SA, To_name, To_SA, wordcount, interrupt_generation_request Where: From_name/To_name= BC | RT_label and From_SA/TO_SA the associated subaddress Where: wordcount is integer number of mil words to be transferred Where: interrupt_generation_request= INTOFF | INTON, where INTON generates an interrupt on rec. at RT Where: modecode transmission is achieved by all SAs zero and wordcount is modecode number MINOR: minor_label { ,xfer label>} MAJOR: minor_label {, minor_label }

This configuration file allows an easy definition of the remote terminals, transfers, minor frames and major frames in the Mil Bus scenario. The MILSTD1553 software programss the AIM card accordingly for all RTs and the BC. Entrypoints in the software then allow the user to either setup (open) the device in loopback mode or in transformer coupled mode, and provides a start function to initiate the bus controller scenario if desired. (In most cases the bus controller will be external and transformer (normal) coupled mode will be used. The API offered by the software allows the user to read or write the transfers that have been setup. The user thereto has to find the transfer by label name through the provided find functions which return the handle for read or write access. Additionally, for debugging, functions are provided that allow the user to read and write to explicit device-SubAddress combinations. Interrupt generation is implemented in combination with the euroSim Mk5.3 eventhandler capabilities. The unit automatically installs an eventhandlerfunction. This function checks if an interrupt has an associated AIM loglist (Compatible Device II, EventHandler Plugin), and if so matches the loglist against the transfers that had INTON defined in the configuration file. If so an event is raised with the name of the label of the Transfer in the configuration file. Usage in a EuroSim project is shown in the Aim1553 example. This example allows the user to time the performance of the software and hardware related to the Aim 1553APX as well as Aim 1553 APU USB board. The MMI shows an upperbound for the latency and an accurate measurement for the jitter. (The latency can only be measured from starting the buscontroller scenario upon hadling the event in EuroSim. The goal should be to time the latency from transfer completion to event handling, however additional hardware is needed to synchronize the clock onboard the Mil1553 to the computer clock via Irig-B.

28.4.4 VMICVEM6000 1553 interface (deprecated) Before EuroSim Mk7.1 the EuroSim product baseline included the esimMil1553 interface. This interface was not sufficiently generic, and only implemented for the VMICVME-6000 interface board of SGI

c Airbus Defence and Space 535 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

systems. This interface is deprecated but still available if desired. Users transitioning from IRIX will miss the line item in the ModelEditor support options. If needed this line can be reinstated by the user by uncommenting the related VMIC section in the EuroSim.capabilities file included in the etc directory of your EuroSim installation. System administrator priviledges are required to edit the file. Please inform the EuroSim helpdesk that you are still using this section to postpone the final removal of this capability from the EuroSim product.

536 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 29

Front-End Model Interface Reference

29.1 Introduction

The Front-end models are an abstraction of the electrical interfaces that a real-time simulator can have with the product under test. This abstraction separates the equipment (or unit) models (see Chapter 17) from the interface to the electrical lines and provides a plugin approach to support different implementa- tions of front-end equipment. This has several benefits:

• The same models can be used with with different instantiations of the product under test. For example this can be a configurable stub early on in the system development life cycle to help develop unit models before the product under test is available, a simulated product under test such as an emulator of the hardware running on the on-board software, or the real product under test.

• Different vendors of front-end hardware equipment can be supported with a clear interface def- inition that the provider must support to connect his front-end software library to the front-end model. This gives flexibility in programs with minor influence on the project result. It also means that is possible to provide to a front-end provider early on in a project a EuroSim simulator with only the front-end models. The supplier can use this to do the integration test from electrical line all the way to the interface of models and vice versa. Such test will validate the integration but also provide performance indicators that are relevant to sizing the computer.

• Solve parallel processing concerns and synchronization through its internal buffering and schedul- ing interface.

• Provides general error injection capabilities.

Currently the Front-End models are implemented for the Mil1553 bus and for the discrete lines. Other front-end models are implemented on market demand, examples can be Can bus, Spacewire. The pro- vided front-end plugin for Mil1553 is based on the AIM-APX/APE-1/2/4 cards and is available to all EuroSim users. This plugin uses memory mapped access to prevent latencies and jitter that can be intro- duced by the standard API calls. It has been developed by the EuroSim team with support of AIM ltd. The use of memory mapped access is essential to prevent that hard realtime behavior that is needed for closed loop realtime simulation is comprimised, possibly resulting in using old data and hence make the simulation not reliable. The provided front-end plugin for the Discrete front-end model provides access to analog, bilevel, pulse and serial lines in PowerDNA cubes from United Electronics Inc. (UEI). The plugin is developed by Airbus Defence and Space Netherlands B.V. (Airbus DS NL) and is an entry level to their ESPRiT front-end solution. The entry level plugin allows customers to start with the provided plugin which can already support a range of discrete interfaces such as analog I/O, bilevel I/O, pulses and serial lines and has the protection of the product under test that is already part of the PowerDNA hardware. It is then still possible to scale up to the full ESPRiT solution which incorporates additional specialised signals such as tacho generation, additional electronic protection and signal handling and a solution to route signals such that the connection from the test equipment to the product under test con- sists of straight cables. The latter avoids complicated cable harnesses, which often are a source of errors.

c Airbus Defence and Space 537 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Additionally Airbuds DS NL has the knowledge to support the system engineering aspect to identify the required signal need and can deliver an intergrated and verified solution (including EMC qualification). When scaling up to an ESPRiT solution, the plugin and configuration files are then provided bu Airbus DS NL, no work is lost. Implementations of the devices for the Mil1553 bus and Discrete front-end are not a standard part of the EuroSim delivery, they are packaged separately as they are more environment specific then the other parts of EuroSim. We strive to always include these implementations with the delivery for the RedHawk platform as that is a more controlled environment, Centos is generally available too. Please check with the EuroSim helpdesk on availability of the device implementations for you specific platform. This chapter focuses on the front-end models and interfaces it provides, including the interface to be implemented by a plug-in developer. The front-end models are implemented in C++ and part of the EuroSim CPP API. They publish their interfaces as variables in the dictionary and hence they can also be used with other APIs through the model description/parameter exchange interfaces. Creation however is to be done via the CPP API and configuration via XML files as will be detailed in this chapter. This chapter will first explain the concept of the front-end model further in a use case description (29.2). Thereafter the architecture is introduced (Section 29.3, Common features Section 29.4 and subsequently the details of interfacing for both the Discrete front-end model Section 29.5 and Mil1553 front-end model Section 29.6. The last section explains the front-end model Stub (section 29.8), a configurable model of the embedded computer that model developers can use to test their models early on in the system development life-cycle, prior to integrating with the product under test.

29.2 Use Case description

For the use case description we use the ThermoMra example. The MRA is developed after the Front-end models and follows the same conceptual idea of building a simulator block that is re-usable in different configurations, thus they fit well together. The ThermoMra example models a system that controls the temperature in four cells that are intercon- nected in an array and thus heat can transfer through the wall of the cells and be lost to the environment. To make the example more interesting we have assumed that our heater is controlled via a Mil1553 bus, and the Temperature sensor has a serial line (RS422). The thermal control system is shown in Figure 29.1.

Figure 29.1: Thermal Control system overview

The heater in every cell can add heat, the temperature sensors provide a measurement of the temperature in each cell back to the control computer. The algorithms in the control software in the on-board computer

538 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

(OBC) have to drive the temperature to a set point for each cell based on the measurements received over the serial line and subsequently switch the heaters on/off via the mil1553 bus. Figure 29.2 shows the thermal control loop.

Figure 29.2: Thermal control system control loop

If we add to this system the Front-End models, show the MRA models as the collection of submodels that they are (Tm,Tc,State,Hil) and make the control computer the product under test, we get the picture shown in Figure 29.3:

Figure 29.3: Front-end model position in a real-time simulator

The front-end model is positioned in the simulator on the interface with the product under test, separating the equipment unit models and Thermo Dynamics and Envrironment model (also referred as DKE) from the control computer. The Front-end model provides an external API through which different imple- mentations of the control computer (test stub, software executing on emulator or hardware model) can interface. Early on in the project only the Front-End Model Stub will be available. This stub is configured through an XML file and allows the user to send discrete and mil1553 telecommands to the models to support verification of individual and unit integrated models. Often projects use an emulation of the product

c Airbus Defence and Space 539 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 29.4: Front-end model FE API

under test, in this case the control computer, to support testing of the unit model software. An emulated environment is much easier to use in debugging then a real computer and still runs the control software with ability to inject all kind of errors into the system. Again the FeModel API is used to read and write the lines. Finally the emulation is replaced with the real product under test, being the computer with control software. At this point a device plug in is needed to let the front-end software communicate through the Front-End model device plugin.

29.3 Architecture

The general architecture of a Front-End model is described in Figure 29.5.

Figure 29.5: Front End Model Architecture

Figure 29.5 shows that there are two buffers in the model, which are synchronized on the activation of a sync entrypoint. This approach is vital for the front-end model. The simulator side of the front-end model provides the interface to the models and is exposed as variables in the dictionary. The equipment models interact with the front-end model through these variables, either via the CPP link interface or the classic C model description / parameter exchange solution. The front-end side of the front-end model is more oriented to the API of the unit model and towards the front-end hardware architectures that apply for the kind of hardware that will be connected. When the sync entrypoint is executed the model and the front-end side are synchronized, see figure 29.6. The EuroSim schedule determines at what moment in time the synchronize is executed and at that point in time no other equipment models or Front-End API access must occur. For the simulator side this is easily arranged in the schedule by making sure that no other unit models can execute at the same time. For access to the front-end model front-end side through the Front-End API this depends somewhat on the environment: when a simulator configuration is running with hardware in the loop, it is important to first call read() before the sync() and write() after the sync() to get the data from the front-end system and push it in the API and vice versa pull data from the Fe side API and push it in the front-end system. This is a sequence per front-end, but multiple front-end types can do this in parallel on the

540 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 29.6: Front End Model Synchronization interface

same computer (as the different front-ends do not share data). In the ThermoMra example we have the Mil1553 FeModel and the Discrete FeModel simultaneously active. For further illustration we encourage the user to investigate the front-end models usage in the ThermoMra example which can be found in the src directory of the EuroSim installation directory.

29.4 Common features

A number of features and characteristics are common across the FeModels. These are described in this section and apply to all Front-End Models.

29.4.1 Model Mode and State Similar to the MRA models, the Front-End models publish a mode, and state variables. This is managed by the FeModel::BaseModel class which defines this interface to all models. It can be used by the system developer as the basis to develop his own front-end models that comply to the Front-End model usage. When deriving from the FeModel::BaseModel class, these variables are accessible via the protected variables _modelMode and _modelState. The modelMode variable can have the following values:

• MODEL_MODE_DISABLED (0) : The model will not execute and be silent on interfaces (default),

• MODEL_MODE_SIMULATED (1) : The model is simulated, which means the step functions of the TC, TM and State components are executed as required,

• MODEL_MODE_HIL (2) : The hardware in the loop component is scheduled instead of the TC, TM and State components.

If used in classes that do not inherit from FeModel::BaseModel, the usage of the name must be preceded with FeModel::BaseModel::. The default model mode is DISABLED. The variable can be set from model software via the setMode(ModelMode) method incorporated in the FeModel::BaseModel class. When set to SIMULATED the derived model configures itself for usage with a simulated external envi- ronment (e.g. embedded control computer). It is expected that the product under test is thus in a simulated environment too and uses direct interface access to the Front-End buffer through the Front-End model provided API. When set to HIL, the front-end model expects the read and write entrypoints to be called to let the plugged-in FeDevice implementation fill the front-end side buffer with data received from the front-end hardware and vice verse provide the front-end hardware with the data from the front-end side buffer. A prerequisite thus is that there is a Device object connected to the front-end model, otherwise an error is generated The modelState variable shows the state of the model, which can have the following values:

• MODEL_STATE_CREATED (0) : The model has been created, but not published. It is an error if this is the final state before the inti is called.

c Airbus Defence and Space 541 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• MODEL_STATE_CONFIGURED (1) : The model is configured, which means that the loading of XML configuration files has succeeded.

• MODEL_STATE_PUBLISHED (2) : The mode is published, hence now the state should be visible in the dictionary.

• MODEL_STATE_CONNECTED (3) : The model mode was set to HIL and the front-end model suc- cessfully connected to the Device.

29.4.2 Filtered logging support Similar to the MRA models, the Front-End models publish a log Level variable which configures the level of information logged to the journal. This is managed by the FeModel::BaseModel class which defines this interface to all models. The values that the user can assign at run time to the log Level variable of a Front-Ed model are:

• LOG_ERRORS (0) Only log errors,

• LOG_WARNINGS (1) Also log messages marked as warning,

• LOG_MESSAGE_STATE_CHANGES (2) Also log state chance messages,

• LOG_MESSAGE_INFO (3) Also log messages marked as info,

• LOG_MESSAGE_DEBUG (4) Also log messages marked as debug.

In general, the higher the value the more information is logged. What can be logged depends on the log statements that the Model Developer has added to the model. The FeModel::BaseModel class can even can be used by the user to develop his own front-end models that comply to the Front-End model usage. When deriving from the FeModelBase class, the logLevel variable is accessible as protected variable of the FeModel::Base class. For developers of a class derived from FeModelBase, the logLevel must be used in conjunction with the log_f method and feLog macro: #define feLog(pSeverity, pFormat, ...)

void FeModel::BaseModel::log_f(LogLevel pSeverity, const char* pFunc, const char* pFormat, ...) const; The feLog macro makes the usage of the log function easier. It assumes that there is a pointer _parent is available amongst its members that points to the instance that is derived from the Femodel::BaseModel class. The log_f method can be directly used from a class derived from FeModel::BaseModel. The pFunc is usually filled with the macro __func__ or __FUNCTION__, but can be any text convenient to the user.

29.4.3 Scheduling

The scheduling of the front-end model requires that init, term, sync, read and write functions are used in the schedule. The initialize, synchronize and terminate entrypoints are always scheduled. The initialize entrypoint must be called after the model modes are set for the equipment models. The terminate function has currently no dependencies. The synchronize method must be called normally at the system frequency and may not coincide with the execution of unit models. Finally the read is called before the synchronize and the write after the synchronize activation, they only need to be present in a configuration which has the front-end hardware attached. The read and write entrypoints force the read and write calls on the Device interface for those models that have their state set to CONNECTED. To reach the state CONNECTED the Front-End model must be switched to HIL mode. The read and write entrypoints can thus be scheduled even though there is no front-end hardware present, which is convenient as it prevents the need for for multiple schedules that must be kept synchonous.

542 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

29.4.4 Configuration The Front-End models are configured by XML files. These XML files can be integrated in the .model file just as source files. The change of the files is detected when the model is build to assure a new dictionary generation. The new dictionary generation is only required if path names change in the dictionary, thus when the object name changes in the XML file. Changing values is not affecting the dictionary, it is thus allows to change values in XML configuration files and use these without rebuilding the model. Schema (xsd) files are provided in the EuroSim installed software tree to check the syntac of files (e.g. via xmllint).

29.4.5 Protection When the product under test is hard to replace, it is highly important that the test equipment can be electrically disconnected from the spacecraft. When the simulator is then started the electrical interfaces should not be connected, allowing the operator to check that it is safe to connect and then trigger the system to create the connection. The front-end model provides the interface to support this operating approach with an online and offine entrypoint. These entrypoints can be scheduled or invoked from script and will trigger the connected hardware plugins to perform these functions. The extent of electrical disconnection is thus dependent on the plugin developer and underlying hardware implementation.

29.4.6 Device Plugins The XML configuration files support the identification of plugins that connect the Front-End model to specific hardware. These plugins are thus vendor and hardware type specific. EuroSim Mk7.1 contains the plugin developed by EuroSim for hard realtime access to PCI(e) MIL1553 boards provided by the EuroSim team with support of AIM to adapt features in their board support package. Most plugins how- ever will be developed by the hardware vendor independent of EuroSim. For example, Airbus Defense and Space Leiden provides the Esprit Discrete Front-End EGSE and provides with that a plugin which interconnects the Discrete Front-End model to their Esprit hardware. This plugin provides off the shelff interconnection with ESPRiT solutions and United Electronics Industries based powerDNA cubes. Identifiying the plugin in the XML file with dynamic loading in EuroSim prevents the need for different model files. A single model file then works for software validation facility and hardware in the loop facilities, supporting the concept of one simulator through the life cycle such that you have maximum reuse and minimal error prone duplication. All Device instances must implement the FeModel::DevIf class abstract interface. This interface de- mands the general interface that all devices in EuroSim must implement: class FeModel::DevIf { virtual int offline()=0; virtual int online()=0; virtual int setParameter(const char *parameter)=0; virtual int devctl(int cmd, void *arg)=0; virtual const char* getErrorDescr(int error)=0; virtual bool esimPublish()=0;

} extern "C" void* create(); extern "C" void destroy(void*);

Method Description

c Airbus Defence and Space 543 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

online Connect the software to the electrical interface. This call allows the operator maximum control over the safety of the test operation. He must use this call to explicitly state that it is safe to connect to the electrical lines. Returns 0 on success, -1 on error. offline Disconnect the software from the electrical interface. This is an emergency switch for the operator to disconnect everything when anything goes wrong. Returns 0 on success, -1 on error. devctl This method allows passing of a device specific command to the device in- stance created via the plugin. Returns 0 on success, -1 on error getErrorDescr Get a description for a returned error code. Returns the string that describes the error. esimPublish Ability to publish variables in the EuroSim dictionary. This is not required, but can be used as a debugging aid. Returns true on success, false on failure create This C function must be implemented by the plugin developer to create an instance of the class that he derived from the specific DevIf abstract class (e.g. FeModel::Mil1553::DevIf or FeModel::Discrete::DevIf) and return it to the Front-End model to allow it to invoke the plugin functions. This function only requires implementation if the plugin approach is used destroy This C function is called by the Front-End model to destroy the plugin object created with the create function. This function only requires implementation if the plugin approach is used.

The plugin developer must compiles his code with the implementation of the Discrete::Device class and links it into a shared object. This plugin must be installed in the LD_LIBRARY_PATH or ld.so.conf to be able for the system to find and load it. It is however also possible to list the plugin as a library in the EuroSim ModelEditor build options and then create an instance in the esimCppSetup function of the CPP API. This has one benefit, the plugin interface that the plugin developer must support to inegrate with EuroSim requires the implementation of an esimPublish function. When using this more cumbersome approach of creating an instance in the esimCppSetup, the benefit is that the esimPublish call is performed such that variables of the plugin are published in the EuroSim dictionary. This can aid in debugging and provide spcial configuration abilities that are difficult to achieve with the mechanism provided via the makefile. In this case it is important to override the esimPublish method that is defined in the DevIf abstract base class. For this approach, taking the discrete specialization of the Discrete Front-End model discussed later in this chapter. a discrete device implementer would derived the class MY::DiscreteDevice that implements the abstract Device interface class and its abstract base class. MY::DiscreteDevice (derived from FeModel::Discrete::DevIf). The Simulator developer shall than include in the simulator setup code (esimCppSetup function) the following call: FeModel::Discrete::instance()->setDevice(*(new MY::DiscreteDevice))

29.5 Discrete Front-End model

29.5.1 Introduction The Discrete front-end covers all the single line standard interfaces, of which many can be present in a discrete front-end. A discrete front-end is therefore usually developed for a project to match the lines required to interface with the interfaces required by the product under test. A careful analysis is needed to define the number of interfaces and the protection measures to assure that the product under test can

544 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

not be harmed by the test equipment. The latter depends on the criticality and availability of the product under test hardware. The discrete front-end model is the abstraction of the discrete front-end hardware. The interface lines can be configured and for each line a number of variables contain the characteristic data for that type of line. The EuroSim Discrete front-end model can handle the following types of lines:

LineType Description AnalogAcq Acquisition on an analogue electrical volt or current signal BilevelAcq Acquisition on a bilevel electrical signal PulseCmdAcq Acquisition on a short duration electrical pulse input, typically controlling a switch PulsePowerAcq Acquisition on a longer duration electrical pulse where the state and duration of the pulse is relevant PulseFreqAcq Acquisition on a high frequency pulse input where the number of pulses is relevant SerialAcq Acquisition on a serial message input where a number of bytes are to be trans- ferred on each occurrence AnalogSim Generation of an electrical voltage or current by the Front-End BilevelSim Generation of a bilevel (true/false) electrical signal by the Front-End PulseCmdSim Generation of a short duration electrical pulse, typically operating a switch PulsePowerSim Generation of a longer duration electrical pulse where the state and duration of the pulse are relevant PulseFreqSim Generation of a high frequency pulse sequence as commanded by the simulator and requiring a smooth transition from a previously commanded frequency to new commanded frequency as a continuous sequence of pulses SerialSim Generation of a serial message electrical signal as required

With the above described types of lines, a large number of signal types can be measured by the front- end hardware and transformed into the information that it needs to store for that line in the front-end model. Vice versa it can read the characteristics and generate the appropriate electrical output signal. With each line, the front-end model also knows if it is connected or not, which depends on the model mode for the source and target. Only if one is simulated and the other is real, the line goes through the front-end hardware. This information can be used by the front-end system software to determine (during initialization) which lines are in use in a simulation run, which depends on which hardware is in the loop. In the next sections we will describe the configuration of the front-end model, the simulator internal interfaces (connecting models) and the simulator external interfaces (connecting electrical lines, either simulated or via front-end hardware. Finally a section details the usage for the end-user who operates the simulator and can use the integrated error injection interface to either block lines, insert ramps or scale the values. For an example we refer to the ThermoMra example installed in the src directory of the EuroSim installation directory, which illustrates the usage of the front-end models.

29.5.2 Setup The Discrete Front-End model is a C++ model using the EuroSim CPP API. It must therefore be created and configured from within the esimCppSetup function that simulators using the CPP API must imple- ment. The Discrete front-end model is a singleton, there can only be one instance. The exact interface is defined in the file FeModelDiscrete.h, but only few methods are of interest. It is therefore easier to provide an example that can be adapted. You can copy this and adapt it to your configuration file path and device implementation:

c Airbus Defence and Space 545 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

//create the discrete model through the singleton method FeModel::Discrete::Model *discrete=FeModel::Discrete::Model::instance(); if(!discrete) { Esim::error("Failure allocating Discrete Responder"); return; } //configure the model with the discrete definition xml file if(discrete->configure("/feDiscrete.xml")!=0) { Esim::error("Failure configuring Discrete Responder, bailing out"); return; } //default model mode is disabled, if you want it to be simulated do this discrete->setMode(FeModel::BaseModel::MODEL_MODE_SIMULATED);

#if0 //this section only if you do NOT want to use the plugin solution //but for instance include the device library code in your simulator //which is not advised because the simulator becomes dependent on hardware drivers

//create an instance of the discrete device //here it is assumed that your derived class is called MyDiscreteDevice ThermalControl::MyDiscreteDevice *discrete_dev=new ThermalControl:: MyDiscreteDevice(); if(!discrete_dev) { Esim::error("Failure allocating Discrete Responder Device for Proust"); return; } //add the discrete device to the front-end model instance if(discrete->setDevice(*discrete_dev)!=0 ) { Esim::error("Failure connecting discrete FeModel device"); return; } #endif

//set the model mode handler, see section on model mode handler interface //You do not have to do this if all your equipment models are MRA models if(discrete->setModelModeHandler(*handler)!=0 ) { Esim::error("Failure connecting model mode handler"); return; } //Publish the discrete model with a model icon in the EuroSim dictionary if(!Esim::addModel(discrete,"/System/Discrete","")){ Esim::error("Failure publishing the Discrete FeModel"); return; } The nominal solution for device access is to use plugins that are dynamically loaded. These plugins are referred to in the configuration file and their interface (FeModelDiscreteDevice) is detailed later on in this chapter. However, it is possible to include for instance such code in the list of files in the simulator. In that case the programmer can create an instance of this object and set it as device in the esimCppSetup function as defined above. There are benefits to this approach as it means that the esimPublish of the device is activated and this places more details in the dictionary. The downside is that the code is usually dependent on installed device driver software and will force different model files for different configurations.

29.5.3 Configuration The configuration of the discrete front-end model is performed through an XML file. This XML file defines the lines that the front-end model should contain. The lines are grouped in Groups which usually match the different equipment instances in the system. Following XML file snippet shows a definition of a group of lines, of which a discrete front-end configuration file can contain many:

546 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

TBD libAirbusEspritDiscrete.so device specific string TBD oa Description is free text shown with a line object a Vdescription is free text shown with the variable The Board section identifies the plugin (shared library) that is provided to connect the Discrete Front- end model API to the EGSE software. The plugin is normally supplied by the manufacturer of the discrete hardware and follows the API prescribed in the file FeModelDiscreteDevice.h. The plugin will be provided with information on how to use it. If it requires a device path it can be provided via the tag. If additional parameters are needed, the manufacturer will state which parameter strings can be passed to the plugin. Multiple lines with tag can be provided to allow multiple parameters to be provided to the plugin prior to its initialization. For the discrete device there can currently be only one Board section. Though this is normally sufficient, future versions of EuroSim are anticipated to resolve this restriction in order to allow splitting up the lines over board and support parallel reading and writing to the discrete front-end hardware. The group section defines a group of related lines, typically the group name mimics model names as this supports in deducing the status of lines, whether they require EGSE support or are internal. The Name attribute is the name with which the group and subsequently the line show up under the Discrete Front-End model node in the EuroSim dictionary. The group becomes a folder with the Group name and that folder is filled with lines named according to the name in the Line definition Name attribute. The LineType attribute determines the type of the line and can have the following values, where Acq defines that it is an Acquisition (thus incoming) into the simulator, whereas Sim shows that it is a output of the simulator:

LineType Direction Description AnalogAcq To simulator Acquisition on an analogue electrical volt or current signal BilevelAcq To simulator Acquisition on a bilevel electrical signal PulseCmdAcq To simulator Acquisition on a short duration electrical pulse input, typically controlling a switch PulsePowerAcq To simulator Acquisition on a longer duration electrical pulse where the state and duration of the pulse is relevant PulseFreqAcq To simulator Acquisition on a high frequency pulse input where the number of pulses is relevant SerialAcq To simulator Acquisition on a serial message input where a number of bytes are to be transferred on each occurrence AnalogSim To front-end Generation of an electrical voltage or current by the Front-End BilevelSim To front-end Generation of a bilevel electrical signal by the Front-End PulseCmdSim To front-end Generation of a short duration electrical pulse, typically operating a switch PulsePowerSim To front-end Generation of a longer duration electrical pulse where the state and duration of the pulse are relevant

c Airbus Defence and Space 547 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

PulseFreqSim To front-end Generation of a high frequency pulse sequence as commanded by the simulator and requiring a smooth transition from a previ- ously commanded frequency to new commanded frequency as a continuous sequence of pulses SerialSim To front-end Generation of serial message electrical signal as required

The Enabled attribute defines the manner in which the front-end model is to determine if the line is connected. This can have the values:

• Never

• Modes

• Always

The values Never and Always are the equivalent of disconnected and connector, but the most interesting value is Modes, which states that the connect state depends on the mode type statement that follow hereafter. This Mode statement, as shown in definition above, contains the modes in which the named unit models must be active for the line to be recorded in the front-end model data as connected. The model type must be one of the following:

• Disabled

• Simulated

• Hil

Here we see the link with the MRA architecture. If the simulator developer wants to use the connection status determination based on Modes, he must implement an object that implements the mode determi- nation callback interface of the front-end model and register it with the discrete front-end model. When the init entrypoint of the Discrete Front-end model is invoked by the scheduler, this interface is called to ask for the actual model mode of the model with the name of the model as argument. The simula- tion developer can find the model via the MRA system class and ask for the model mode (or implement some other means to determine the model mode for that name). If (in the XML example shown above) for the model1 and model2, the actual modes requested at runtime match the mode stated in the Modes line of the configuration file, the line is connected. This information is then available to the discrete front-end library such that it knows which lines to read and stimulate (write) at runtime in sync with the configuration of simulated and equipment and equipment that is included as hardware in the loop. The Channel-attribute is a tag for the front-end developer. He can pass a constant value to the simulator developer which provides specific data. The value is a 64 bit unsigned integer in which he may encode specific details that provide fast access in his front-end hardware. The value can be requested through the Front-End API of the front-end model. Finally lines that define the Connector-type, the Analog Signal-type and the Digital Signal-type and Description are for information only. The front-end hardware can access this information at runtime if desired through the front-end API of the front-end model. The line and connector types are tailored to the definitions from ESA. Values of the Analog Signal-type are A1, A2, A3, ASM, SASM, FSSM, RWTC, RWTDC, TSM1, and THCM. Values of the Digital Signal-type are BSM, BDM, RWTDM. The Connector-type and Description are free text.

29.5.4 Mode Connection interface When the init entrypoint of the Discrete Front-end model is called, the front-end model will determine the connection status of all configured lines. This combines the Modes statement in the configuration file with the actual value of the ModelMode variable as set by the end-user in the simulation.

548 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

If all the models used by the Simulator Developer are MRA models, thus derived from MRA classes and registered with the MRA System class (Chapter 17) then no action is needed for the mode connec- tion interface cause the Discrete Front-End Model knows how to get model modes from MRA models. However if this default assumption does not apply or the model names in the XML files for some reason do not directly map to an MRA model name, then the Simulator Developer must implement a callback solution that is invoked when the init entrypoint is executed by the scheduler. In this case the interface that is to be implemented by the Simulator Developer to allow the Discrete Front-end model to find the actual model mode is the following: class ModelModeIf { public: virtual DiscreteModelMode getModelMode(const char* modelname)=0; }; The Simulator developer must thus create and implement his own class that provides this interface. An object (and only one object) of that class should then be registered with the discrete front-end before the init entrypoint is called. This is often combined with a constructor or factory type object that creates all the models. In the MRA it is common to implement such a class that knows the pointers to all models as getModelMode then often is addressed by getting the model with the passed name from the MRA::System instance and ask it its model mode. FeModel::Discrete::Model::instance()-> setModelModeHandler(*MyModelModeIfObject);

29.5.5 Dictionary interface The interface to the models offered by the Discrete front-end model in the form of dictionary variables is shown in 29.7.

Figure 29.7: Discrete Front-End Model in dictionary

The discrete front-end model exposes itself with the path en name chosen by the model developer when calling Esim::publish on the model after creation. The model in the dictionary then shows a subdivision of groups and lines matching the definition in the configuration file. When opening a line object definition the standard layout in the dictionary of a line is exposed. Here we see the info, config, sim, fe, status and error variables, which are structures defined in the file FeModelDiscreteTypes.h included in the include directory of the EuroSim installation.

Variable Description

c Airbus Defence and Space 549 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

info The info variable is of type DiscreteInfo_t. This structure contains the in- formation read from the Discrete configuration file to make this visible to the end-user. The info field information is used by the front-end model when its init entrypoint is activated by the scheduler. sim The sim variable type depends on the type of the line and the direction of the line. Six types are defined in both Acq (to the simulator) and Sim(to front- end) direction. The structures represent the characteristics of the electrical line as visible to the end user. The sim variable is updated by the sync if the line direction is to the simulator. After the sync the unit model can use these variables when updating the equipment model. If the line direction is out of the simulator the sync entrypoint reads the sim variable and copies the values to the front-end variable. Note that for acq lines, the sim variable provides the time stamp at which time the data was sampled . This stamp is in system time, hence care must be taken because the stamps are not bound by the simulation speed in a software only simulator configuration. fe The front-end variable is the counterpart of the sim variable. The front-end variable is read and written by the product under test, either via front-end inter- faces or directly through the front-end model API in a software only simulator configuration. status The status variable only contains the status of the line. This status is updated in the init entrypoint activation based on the modes line in the discrete config- uration XML file and the actual model modes set by the user. See the Model Mode interface paragraph in Section 29.4.1 error The error variable allows the user to configure error injection on the line. This is further detailed in the Error Injection section for Discrete Front-End models (Section 29.5.9).

29.5.6 Simulation model interface Simulation models can access the the discrete lines in the discrete front-end model in two different approaches. The first approach is to access the discrete lines using the variables that are exposed in the dictionary. In this approach the model developer uses either the classic C ModelDescription/Parameter Exchange leading to transfer entrypoints or the more efficient CPP API’s Link objects to provide a direct pointer access to the variables. The second approach is to use a pointer to a Discrete line object, for instance to connect the Esim::Link to the object in the dictionary that represents the line in the discrete Front-End model. The latter is a more object oriented approach where the attributes are only access through the methods in the object. The first approach is used in the ThermoMra1 example the second in the ThermoMra2 example.

29.5.6.1 Access through variables Because the front-end model exposes its variables in the dictionary, the user can use both the generic EuroSim ParameterExchange (PX) solution as well as the Esim::link interconnection approach from the CPP-API to connect variables in one model to variables in another model. (Note that the Front-End models do not expose ports so the CPP port-channel solution is not available there).

• When the PX solution is selected, the user can use the Parameter Exchange editor to define the data transfers between Model fields in the dictionary. This creates parameter exchange entrypoints in the EuroSim dictionary which can be schedule to trigger the specified data copy.

• For C++ models, such as the MRA models, the easier approach is the Esim::link interface. Instead of adding a variable to the dictionary the developer adds a CPP Link object which can point to the variable in the Front-End model. The Esim::link function then connects the pointer to the sim

550 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

variable using dictionary paths to designate the variables. This simplifies scheduling and avoids copying.

29.5.6.2 Access through objects The variables exposed in the dictionary are child attributes that are published by their parent, the discrete line object. Instead of accessing the dictionary variables through Links, it is also possible to let the Link object point to the front-end object. The Link acts as a pointer and through that becomes possible to invoke the methods of a discrete line object such as an analog acquisition. These methods are setters and getters that manupulate the variables that are visibible as children of the object, hence the end effect is similar as linking to the variable but the interaction is more in line with the object oriented nature of C++. There are two methods to point to the Discrete line objects. If the code is set, the Esim::Link can be pointed to a line in the discrete front-end, which is accomplished using the Esim::link function that connects a link object or link path to the path to the object in the dictionary or the pointer to the object itself as long as that pointer is of the type that matches the Link. the alternative is to ask the Discrete Front-end Model for a pointer to the Discrete Line object. That can be performed using

FeModel::Discrete::LineIf* FeModel::Discrete::Model::instance()->get("groupname","linename");

You then have to dynamic down cast tot he correct Link object type (E.g. AnalogAcqIf*). Finally all lines are Esim::Object and expose their id in the dictionary. This or the path in the dictionary can be used to object an Esim::Object* that can be downcast to the correct LineIf* as well. This interface that is exposed to the models is mostly to write or read data and it is quite dependent on the line type:

AnalogAcq int get(double &val) const=0;

AnalogSim int set(double val) =0;

BilevelAcq int get(bool &level) const=0;

BilevelSim int set(bool level) =0;

PulseCmdAcq int get(uint64_t &duration, uint64_t &acc_count) const=0;

PulsePowerAcq int get(double &duration, double &litude, uint64_t &acc_count) const=0;

PulseOntimeAcq int get(double &acc_ontime)const=0;

PulseFreqAcq int get(uint64_t &acc_count)const=0;

PulseCmdSim int set(uint64_t acc_count) =0;

c Airbus Defence and Space 551 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

PulsePowerSim int set(uint64_t duration, double amplitude, uint64_t acc_count) =0;

PulseFreqSim int set(double period) =0;

SerialAcq int get(size_t &size, uint8_t *data) =0;

SerialSim int set(size_t size, const uint8_t *data) =0;

29.5.7 Front-end interface The Front-end interface is a set of C++ classes and methods that can be invoked to read and set the variables in the front-end side buffer of the FeModel. In the dictionary this shows up as the fe variable for each line. Each electrical line type identified in the XML file is reflected as a C++ class derived from the C++ Line class in the Discrete Front-End Interface class hierarchy. A derived LineIf class contains the getter or setter method for each type of line implemented by the Front-End Model. The Front-End developer must call these get and set methods to exchange data between the Front-End software and the simulator. Classes and associated methods provided to the Front-End Developer are:

Class Method / Description LineIf uint64_t getChannelId() Return the unique channel id defined in the XML configuration file associated to this line

LineIf const char* getName() Return the name of the channel as defined in the XML configuration file LineIf uint64_t getLineType() Returns the linetype as defined in the xml file LineIf DiscreteConnectionState getConnectionState() Returns the connection status of the LineIf (Unconnected, Connected) LineIf Int getEnabled() Returns if the line is enabled AnalogAcqIf int set(double value) Write the acquired current or voltage value to the Front End Model. Return value: zero on success, unique negative number indicative for the error other- wise. BilevelAcqIf int set(bool level) Write the bilevel value to the Front End Model. Return: zero on success, unique negative number otherwise returns zero on success PulseCmdAcqIf int set(uint64_t duration, uint64_t acc_count) Writes the following values to Front-end model

552 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

duration: duration of the acquired pulse in msec acc_count: accumulated pulse count (wraps) Return: zero on success, unique negative number otherwise PulsePowerAcqIf int set(double duration, double amplitude, double acc_ontime) Write the following values to the Front End model duration: duration of the last acquired or ongoing pulse in seconds (to be updated on every acquisition) amplitude: amplitude of the acquired pulse acc_ontime: accumulated time that the pulse was active in seconds not count- ing an ongoing pulse Return: zero on success, unique negative number otherwise PulseOntimeAcqIf int set(double acc_ontime) Write the total ontime (past and in progress at sampletime) to Front End Model acc_ontime: accumulated ontime PulseFreqAcqIf int set(uint64_t acc_count) Write the following values to Front End Model acc_count: accumulated pulse count (wraps) Return: zero on success, unique negative number otherwise

SerialAcqIf int set(double stamp, size_t size, const uint8_t *data) Write the following values to Front End model stamp: sample time in seconds since Unix Epoch size: number of uint8_t in serial message data: message data Return: zero on success, unique negative number otherwise AnalogSimIf int get(double &value) Read the value of current or voltage from the Front End Model Return: zero on success, unique negative number otherwise BilevelSimIf int get(bool &value) Read the boolean value from the Front End Model Return: zero on success, unique negative number otherwise PulseCmdSimIf int get(double &litude) Read the following values from the Front End Model Amplitude: amplitude of the pulse Return value: zero on success, unique negative number otherwise Note that if the amplitude of the voltage or current is set to a fixed value and that value is configured in the FE then the amplitude argument can be ignored. PulsePowerSimIf int get(uint64_t &duration, double &litude) Read the following values from the Front End Model Duration: duration of the to be generated pulse Amplitude: amplitude of the to be generated pulse Return: zero on success, unique negative number otherwise

c Airbus Defence and Space 553 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Note that if the amplitude of the voltage or current is set to a fixed value and that value is configured in the FE then the amplitude argument can be ignored. PulseFreqSimIf int get(double &period) The FreqSim interface relates to a tacho signal to be generated by hardware in the loop. The card generates the frequency from a requested period, which defines the frequency at that point in time. Read the following values from the Front End Model period: the current period of the frequency to be generated pulse Return: zero on success, unique negative number otherwise Note 1) that if the amplitude of the voltage or current is set to a fixed value and that value is configured in the FE then the amplitude argument can be ignored. Note 2) That the FE should adjust the duration of pulses to match the target frequency without causing phase shifts

SerialSimIf int get(size_t &size, uint8_t *data) Read the following values from the Front End Model size: must contain the size of the data buffer passed as second argument on call, is set to the actual data size on return. data: pointer to the databuffer where the data is written to Return: zero on success, unique negative number otherwise ModelIf int setDevice(FeModel::Discrete::DevIf & dev) Registers a hardware specific DevIf instance with the Front-End model Return: zero on success, -1 on failure.

ModelIf ModelIf* instance();

The front-end developer is provided with a list of handles to the classes via the device interface described in the next section. To connect in an SVF however there is an interface need to retrieve a line based on the groupname and linename. This interface is provided by the discrete model interface class. The developer must retrieve a pointer to the front-end model class to find the line based on the groupname and line name. FeModel::Discrete::LineIf* line=FeModel::Discrete::Model::instance()-> getLine("groupname","linename"); Alternatively there is a C interface available in the file FeModelDiscreteCmduIf.h that wraps the above interface and is potentially easier to use for integration in an SVF.

29.5.8 Device interface The discrete device interface is a class that the Front-End hardware developer must implement in a dynamic library (plugin) to glue the interface of the front-end system software to the front-end model. The discrete front-end model reads which plugin to load from its configuration file and performs the loading on startup of the simulator. The discrete device interface class to be implemented is defined in the file FeModelDiscreteDevice.h but including either esim++fe.h or esim++.h is sufficient. The front-end developer must implement a class that implements the interface, create an instance and add it to the FeModel. The implementation can also be linked into a shared library to become a plugin to which the XML configuration file can refer such that is loaded if and only if the model is switched to HIL mode.The provider of the plugin must provide details on the implementation, in particular in relation to what is defined in the board section of the XML configuration file where board specific initialization strings are allowed to be passed to the device.

554 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The EuroSim consortium strives to provide pre-built plugins with the device interface implementation for specific boards in oprder to provide proven solutions. This requires collaboration with the manufacturer and can only be done for select devices. Currently EuroSim supports the ESPRiT for EuroSim discrete front-end interface from Airbus Defence and Space Netherlands B.V. which interfaces the Discrete Front- End model out of the box with United Electronics Inc. PowerDNA hardware and has a range of avialable extensions. More information on can be found here Section 29.5.10. To built your own plugin for the Discrete Front-End model is not difficult, yet it must be done in such a way that it does not cause the read() and write() calls of the Front-End model to show jitter as a consequence of the plugin reading the hardware. The following listing shows the discrete device interface from which a class should be derived that fills this interface with hardware specific access: class FeModel::Discrete::DevIf : public FeModel::DevIf { public: virtual int init(std::vector &lines)=0; virtual int read(std::vector &inlines)=0; virtual int write(std::vector &outlines)=0; virtual int term(std::vector &lines)=0; };

Method Description init Called once by the simulator to allow the Front-End model to initialize the FE software for the electrical lines configured in the felines argument. The methods returns zero on success. read Called cyclically by the simulator to read all the electrical lines identified in the acqlines argument. The methods returns zero on success. write Called cyclically by the simulator to write all the electrical lines identified in the simlines argument. The methods returns zero on success. term Called once by the simulator to allow the Front-End model to terminate the FE software for the electrical lines configured in the felines argument. The methods returns zero on success.

Note that the derivation of this class reuqires the implementation of the methods in the FeModel::DevIf class described previously in this chapter. In the init, read, write and term methods the front-end developer must iterate through the provided vector of connected lines and handle each line according to its type. This type is available for each line via the LineIf class and must be used to cast to the appropriate type to read further type specific attributes or set type specific attributes. Note that for the Discretes a single device object is installed for the entire model instead of for each single line or type of line. This approach is chosen for timing reasons as it allows the front-end developer to optimize access to hardware by getting sets of lines. An initial scan of the provided line vector is needed to assess which lines are requested. Here another level of optimization could be included where the vector changes depending on the cycles in the simulator. This is currently not foreseen, but the Front-End developer should not assume that the provided LineIf vector remains constant.

29.5.9 Error Injection Error injection is supported for every type of line by means of a generic approach. When configured and activated, the error injection takes place in the execution of the sync entrypoint of the front-end. If the line is going from fe to sim, the sim buffer values will be different from the fe values, whereas normally it should be a copy. The result of error injection is thus viewable in the front-end model. Similar holds

c Airbus Defence and Space 555 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

for the copying of data from sim to fe, here the fe will differ from the sim side when error injection is active. The general mechanism for error injection is in line with the EuroSim error injection approach. The user of the simulator can configure an error injection anytime in terms of a number of samples of injection of a specific type of error. The error type is configured with parameters. The set of parameters and the error injection capabilities depend on the type of line. In general this follows the same approach as the standard error injection capabilities in the various APIs. Figure 29.8 shows a fully unfolded error injection for an analog line.

Figure 29.8: Discrete error injection snapshot

The concept is that the user first configures the error injection through the fields of the configure variable and then applies the configured error injection by setting enable to true. The configuration fields are:

• reps This defines the number of activations the error injection will be active until. The status variable has a field steps that runs up and when equal to the configured number of repetitions, the error injection shuts of automatically (enabled field will become 0).

• type The type ERR_IN_NONE (0) means that there is no error injected, the type ERR_INJ_IGNORE (1) means that the only the time stamp is copied from fe to sim, and for sim to fe no data is copies at all. This type of error is possible on all lines. The type ERR_INJ_INSERT (2) inserts new data instead of copying data in the sync entrypoint. Finally the type ERR_INJ_ADJUST (3) first applies a function on the source data before it writes it in the other buffer.

• a,b,c These are parameters that apply to the insertion and adjustment types. The effect depends on the line type and will be discussed in the table below. The type for these parameters is double

• n As for a and b this variable parameterizes the insert and adjust error type and its applicability depends on the line type. The type for this parameter is integer.

The status variable stores internal variables of the error injection and depend on the line type. It is usually self explaining, as for instance in Figure 29.8, the variables show if the error injection is active, the number of activations of the error injection (counting up) while calling the sync entrypoint when the error injection is active. The slope is related to the ramp function that can be applied in insertion, where the value runs from a up to b in n cycles and then hold to the value of b until the steps reached the configured number of repetitions of the error injection. The following table describes the use of the variables a,b,c,n to configure the errors of type ERR_INJ_INSERT and ERR_ING_ADJUST. In this table two function names occur: the scale multiplies a variable with a and

556 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

adds b. The slope runs on the y-axis from a to b in n steps and then remains on value b. If n is zero, the slope does not run up and the resulting value remains a. For the latter the slope is the derivative (b-a)/n calculated at the start of the error injection. The ramp is most of the time the function applicable to insertion, whereas the scale relates to the adjustment type.

type configuration parameter effect AnalogAcq/Sim INSERT is a ramp, ADJUST a scale BilevelAcq/Sim INSERT sets the level to a, ADJUST sets the level to (a && level) || b PulseCmdAcq INSERT injects a pulse of duration a ADJUST scales the measured amplitude with a and the measured duration with b PulseCmdSim INSERT is limited to generation of one pulse ADJUST is not supported (its a pulse of predefined amplitude and duration) PulsePowerAcq INSERT inserts pulses with amplitude a and duration b and repeats this after interval c ADJUST scales the amplitude with a, duration with b PulsePowerSim INSERT inserts pulses with amplitude a and duration b and interval between pulses c over the number of repetitions ADJUST scales the amplitude with a, adds bias to amplitude with band scales duration with c PulseOntimeAcq INSERT inserts pulses with duration a and repeats this after interval duration b ADJUST scales the accumelated ontime increment with a PulseFreqAcq/Sim INSERT performs a ramp function (a,b,n) on the accumulated count ADJUST scales the accumulated count contribution SerialAcq/Sim INSERT overwrites the data in the serial line with either a repetitive insert of the same packet or with a stream of packets prepared in a queue. Which ap- proach is taken depends on the configuration field strategy. If strategy=0 (default), the repetitive strategy is selected. This strategy mimics the ramp function in that it repeatedly inserts data from parameter a and then after n packets switches to using data from b. More precise: while [0n] size bytes are inserted starting from b[0]. If n=0 (default), the data is read always starting from b[0]. If strategy=1 the data is taken first sequen- tially from a and then from b untill all data is used. More precise: the insert function first reads size bytes from a[i] as stream each repetition, where i starts at zero and increases with size on each repetition. When all data from a is used (reaching a[256]), the insertion continues reading from b[0] as stream. Both a and b are 256 bytes. A total of 512 bytes can thus be injected in packets of size bytes. When there is no full packet left (size& bytes) in buffer b the error injection stops. ADJUST changes the data in the serial line using the formula (a[i] & data[i]) | b[i] for each byte i in the packet where 0

29.5.10 Supported Discrete Devices To utilize the Discrete Front-End model, a plugin must be written that maps the EuroSim discrete generic device interface on the software interface provided by a specific hardware front-end device. An important

c Airbus Defence and Space 557 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

factor is that this must be done in such manner that realtime access is guaranteed as jitter in the hardware access encapsulated in the plugin will directly translated into jitter in the EuroSim scheduler. This section lists pre-built plugins available to EuroSim users, either in the form of an RPM delivered with EuroSim or a delivery obtainable from the device supplier or other third party.

29.5.10.1 Airbus ESPRiT for EuroSim The Airbus ESPRiT EGSE solution is a scalable discrete front-end solution that is adaptable to the needs of small and high-end systems. The solution uses an architecture that harnasses commercially avialable components for standard interfaces and own developed boards for those cases where commercial compo- nents are not available. The commercial and own boards are housed in an architecture that allows extra protection towards hardware in the loop as well as a mapping of signals to connectors to keep cable har- nesses limited to simple straight cables. The ESPRiT plugin communicates with the electrical interface hardware using a realtime network, preventing the more dangerous approach of combining PCIe boards which are prone to giving unpredictable performance when combined in a single computer. The ESPRiT for EuroSim plugin supports an entry level configuration of the Airbus Defence and Space Netherlands B.V. modular ESPRiT EGSE solution based on the usage of the commercially available PowerDNA hardware from United Electronics Inc. (UEI). Though for the ESPRiT technology this is an entry level configuration, this stil packs an extensive level of interfaces in a convenient out of the box form with a reasonable protection of hardware. The UEI PowerDNA cube is a mini rack that can house different UEI compliant cards and communicates realtime over ethernet with the host. This allows the cube to be kept seperate from the simulator host computer and does not require PCI slots. Multiple PowerDNA cubes can be used. Additionally the benefit of the PowerDNA cube as starting point is that this can scale up to the Airbus EGSE solution. Should specific needs arrise, Airbus Defence and Space Leiden B.V. can be contacted for a more extensive customer specific solution. Such solution will lead to a replacement of the plugin with an extended version and additional more dedicated hardware that is either available in the ESPRiT product catalog or developed specifically for the customer. The EuroSim consortium does not provide support on the plugin other then the information in this manual. However additional support can be acquired seperately from Airbus on the plugin usage and on domain specific building of test equipment for control systems in space and defence. When switching to a larger Airbus ESPRiT configuration from the ESPRiT for Eurosim plugin, the architecture and interface with EuroSim in these cases will not change and hence no work is lost. The entry level ESPRiT for EuroSim discrete plugin supports the following interfaces from UEI:

• DNA-PPC8-1G: Chassis

• AI-201-100: Analog input E.g. torque command

• AO-308: Analog output E.g. motorcurrent, analog status output

• DIO-403: RS-422 style bi-level inputs and outputs.

• DIO-430: Relay output On/off status

• DIO-449: Pulse input On/off command

• SL-501: UART with RS-485 interface.

Please see the UEI website (see https://www.ueidaq.com) for more details on PowerDNA product infor- mation with respect to the characteristics and performance of these interfaces. The package EuroSim-AirbusEspritDiscrete has three prerequisites:

• Boost: Generic C++ libraries.

• PowerDNA: Driver for the PowerDNA cube.

558 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• log4cplus: Standard package from the EPEL repository.

The plugin has been built with Boost version 1.72.0; this version can be downloaded from: https://dl.bintray.com/boostorg/release/1.72.0/ source-boost\_1\_72\_0.tar.bz2.

There are 5 Boost libraries that need to be compiled into shared objects so you need to run at least the following commands:

./bootstrap.sh --with-libraries=chrono,filesystem, program_options,regex,test,thread ./b2 install

This will install the libraries into /usr/local/lib/ or in the directory specified by the --prefix option. More information can be found on: https://www.boost.org/doc/libs/1 73 0/more/getting started/unix- variants.html . The plugin also needs the PowerDNA software package version 4, preferably version 4.10.1. This soft- ware can be downloaded from the UEI web site. Installation instructions are provided with the software package. Additionally, the plugin requires log4cplus. This package can be found in the EPEL repository. After activating the EPEL repository, the package can be installed in the normal way with: dnf install log4cplus. The plugin requires a set of configuration files that provide the hardware configuration in the PowerDNA cube(s) and configure the details of each specific signal such as the minimum and maximum lenght of a pulse.. When the plugin is installed the plugin (shared object) is installed in /usr/EuroSim/lib64. This plu- gin will read a set of configuration files. Such configuration files are provided with the installation for a 6-slot PowerDNA cube with the cards listed in the order as described above in /usr/EuroSim/etc/share/e- sprit simfe. If the PowerDNA cube configuration is exactly as above, which is a good default set, then you can utilise the configuration files as is, otherwise it is required to adapt these files. The comments in the default file sets are a good guide in what can be adapted. The ESPRiT for EuroSim plugin will search by default for its required configuration files in /usr/Eu- roSim/etc/share/esprit simfe/esprit simfe.json. When found the plugin will copy the identified configu- ration files to /.esprit˜ simfe/ and utilize these. For a default configuration of the PowerDNA cube and settings, no further effort is needed.If derived or alternative configuration files are to be used however these files should be used as an example for making your own esprit simfe like directory. The the plugin can be told to look in another location for the configuration file using the setParameter line in the Discrete Front-End model XML configuration file. E.g. setParameter("{\"simfe_config_file\":\"/abspath/my_config.json\"}")

It is mandatory that the setParameter points with an absolute path to the location of the configuration file if an alternative location is used. In this case the file is loaded from identified location, no copy is made. The final configuration effort is to connect the lines in the Discrete Front-End model to the sign (or channels) provided via the plugin and PowerDNA hardware. This mapping of the logical signal interface defined in the EuroSim model to a specific electrical line interface on the hardware is arranged through the EuroSim Discrete Front-end model configuration file. This file allows to refer to the EuroSim discrete plugin and possible the location of the plugin configuration file, and thenfor each line allows the connec- tion of the logical line in the Front-End model to a specific channel in the hardware via the ChannelID in the line configuration. This channel ID is a positive large number which encrypts the hardware type (enum), slot, layer and channel. which together identify the specific electrical interface in the front-end plugin configuration file (tying the EuroSim higher level logical line to a specific electrical output)

c Airbus Defence and Space 559 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

enum HwType { VOLT_IN, // AnalogAcqIf SBDL_IN, // BilevelAcqIf PC449_IN, // PulsePowerAcqIf UART_IN, // SerialAcq VOLT_OUT, // AnalogSimIf AMPS_OUT, // AnalogSimIf OHM_OUT, // AnalogSimIf SBDL_OUT, // BilevelSimIf PC450_OUT, // PulsePowerSimIf PC450_OUT, // PulseCmdSimIf RWL_TACHO_OUT // PulseFreqSimIf (requires special hardware from ESPRiT) RWL_DIR_OUT // BilevelSimIf RWL_ONOFF_OUT, // BilevelSimIf RELAY_OUT, // BilevelSimIf BLD_OUT, // BilevelSimIf UART_OUT, // SerialSim }; uint16_t slot: ; TODO uint16_t layer,channel; //identified in the configuration file

uint64_t composeChannelId(HwType t, uint16_t s, uint16_t l, uint16_t c) { uint64_t cid=(t<<48) + (s<<32) + (l<<16)+c; return cid; }

The above function thus composes the channel id value that is to be set with the ChannelID label in the Discrete Front-End model. To further elaborate the Discrete plugin usage, an example application is included with the ESPRiT for EuroSim plugin that is intended as a test application. It shows that the electrical interfaces can be set to specific output from within a EuroSim simulator as well as acquire input from the environment into a realtime simulator. Please do check the json configuration files to adapt to specific IP addressing or different hardware interfaces. (TODO)

29.6 Mil1553 Front-End model

29.6.1 Introduction The Mil1553 Front-End model can be configured for the number of busses and the remote terminals included in those busses. The configuration file is an XML file. The file allows the setup of busses with remote terminals, subaddresses and default values. Although the file allows for the definition of the details of remote terminals and subaddresses, these values are only defaults and are not mandatory. The final configuration can be performed by the equipment model in the initialization phase of the sim- ulation as it is the equipment that defines on which remote terminal number it is operating and how it is using the subaddresses on the remote terminal. Being able to set the default in the XML configu- ration file is however convenient in testing. Note that the configuration file defines which hardware is available, hence in the end the configuration file must contain the maximum set of remote terminals and subaddresses/modecodes that can occur to make sure sufficient resources are available.

560 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

29.6.2 Setup The Mil1553 Front-End model is a C++ model using the EuroSim CPP API. It must therefore be created and configured from within the esimCppSetup function that simulators using the CPP API must imple- ment. The Mil1553 front-end model is a singleton, there can only be one instance. The exact interface is defined in the file FeModelMil1553.h, but only few methods are of interest. It is therefore easier to provide an example that can be adapted. You can copy this and adapt it to your configuration file path and device implementation. The ThermoMra example/Simulator/Fe directory provides a good example using stubbing instead of models. //create the mil1553 model through the singleton method FeModel::Mil1553::Model *mil=FeModel::Mil1553::Model::instance(); if(!mil) { Esim::error("Failure allocating Mil FeModel"); return; } //configure the model with the mil1553 definition xml file mil->configure("../../Configuration/feMil.xml"); if(!mil) { Esim::error("Failure allocating Mil FeModel"); return; } //the default mode is DISABLED, if you want a different initial mode //e.g. SIMULATED then do the following call mil->setMode(FeModel::BaseModel::MODEL_MODE_SIMULATED);

#if 0 //this section only if you do not want to use the plugin solution //but for instance include the device library code in your simulator //which is not advised because the simulator becomes dependent on hardware drivers

//create an instance of the mil1553 device, see section on discrete device implementation //here it is assumed that your derived class is called MyDiscreteDevice ThermalControl::MyMil1553Device *mildev=new ThermalControl:: MyMil1553Device(); if(!mildev) { Esim::error("Failure allocating Mil FeModel Device for AimMil1553"); return; } //add the mil1553 device to the front-end model instance

//In following line brdIdx and busIdx are counting upward from zero in the configuration file mil->getBoard(brdidx)->setDevice(*mildev); //links your device to the board //In following line device specifc parameters are set, must be documented as part of the //device. mil->getBoard(brdIdx)->setParameter("device specific setting"); #endif

//set the Sync handler (see the paragraph on the sync handler in this chapter) if(mil->addSyncHandler(*handler)!=0 ) { Esim::error("Failure adding sync handler"); return; }

c Airbus Defence and Space 561 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

//Publish the mil1553 model with a nice model icon in the EuroSim dictionary if(!Esim::addModel(mil,"/System/Mil1553","") ) { Esim::error("Failure publishing the Mil1553 FeModel"); return; } The setup above as a section that is not enabled in the code. The nominal solution for device access is to use plugins that are dynamically loaded. These plugins are referred to in the configuration file and their interface (FeModelMilDev) is detailed later on in this chapter. However, it is possible to include for instance such code in the list of files in the simulator. In that case the programmer can create an instance of this object and set it as device in the esimCppSetup function as defined above. There are benefits to this approach as it means that the esimPublish of the device is activated and this places more details in the dictionary. The downside is that the code is usually dependent on installed device driver software and will force different model files for different configurations.

29.6.3 Configuration The configuration of the mil1553 front-end model is performed through an XML file. This XML file defines the remote terminals that the front-end model should simulate, grouped per bus. The name of the remote terminal should match the name of the equipment model that that remote terminal belongs to. This remote terminal name in the XML file will also be the name through which they will become visible in the EuroSim dictionary as submodel of the bus.

/dev/aim_milx libEsimAimMIl1553.so Module=0 Verbose=1 2,3,6,16,6,2

Active Both 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 0 0.00001

The Mil1553 Front-end model supports multiple boards and multiple busses per board. The busses are internally counted upwared in the order of reading and each bus associates itself to a Board with a specific bus on that board. The Board section identifies the plugin (shared library) that is provided to connect the Mil1553 Front-end model API to the EGSE software. The plugin is oftend supplied by the manufacturer of the hardware but because Mil1553 is a standard, EuroSim together with the company AIM provided a realtime plugin to connect AIM mil1553 cards to the MIL1553 Front-End model. Multiple Board

562 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

sections can occur, related to the amount of boards in the computer. In most cases the Device Path will be essential to the plugin to identify which board to use. However in the case of the EsimAimMil1553 plugin an AIM API module number is needed, which is passed as parameter to the plugin. If more then one board is present this parameter is required, if only one board is present it must be zero and the plugin assumes this is the case if no Module parameter is provided.Tto identify the relation between the module number and the board we advise to use the sample program provided with the AIM BSP package which can print out all details of a board per module. The Board also defines the Plusbuffer configuration. These plusbuffers are queues that support so called deep addressing where within one minor frame the bus controller sends a sequence of transmissions to the same mil address. The receiving remote terminal must be able to buffer these subsequent transmissions of each up to 32 milwords in a queue manner. This is an advanced capability, it is advised to avoid this approach and flatten the queue over subsequent mil1553 subaddresses instead if possible. It may not be possible though due to the limited amount of subaddresses. The Plusbuffers line allows defining how many buffers of subsequent 2, 4, 8, 16, 32 and 64 depth are available in the front-end model. The total amount of memory is usually limited on mil1553 simulation cards and hence the distribution over the amount of each type is to be tailored. A buffer of depth 2 can contain 2 x 32 milwords.Caveat: in the ccurent EuroSim Mk7.1 version this tailoring is not supported and the definition must be present as shown in the example. After the Board section the front-end model configuration file for mil1553 defines the bus and the con- tained remote terminals. Each bus points to the board and bus on that board that it is mapped to. The busses are then counted upward starting from zero. The the tents bus would be bus 9. A this level the bus numbers are logical, internally they then know that this may fit on board ”X” bus 1. The Name of the bus is found back as the name of the bus object in the EuroSim dictionary after publication of the model. The Mode is either On or Off, and normally initially On. The Board and Stream parameters are passed to the Device object that will be plugged in to link the bus to a specific mil 1553 bus simulated by a specific board. The first section within the bus is the Defaults section. This lines in this section can also occur separately defined for each remote terminal, and in fact if that is done it will override the default. The Defaults section is thus present to simplify the configuration file. It can contain the following:

Keyword Description / values RtMode defines the initial state of the remote terminals when the simulator starts. The values are Active (1) to specify that remote terminal is used in simulation. Passive (2) to specify that remote terminal is used passively (only listening) in simulation. When connected to hardware, the card is not configured for sim- ulation, when the API is used, the reply message has a size member variable which is set to -1 ListenTo to specify which of the two redundant MIL busses is being used. Primary (0) to specify the primary MIL bus Secondary (1) to specify the secondary MIL bus Both (2) to specify both primary and secondary MIL bus None (3) The light is on but nobody is home McEnable to specify the mode for every mode code (0..31] as an array Disabled (0) to specify that the mode code is disabled Enabled (1) to specify that the mode code is enabled Interupt (2) to specify that the mode code is enabled and an interrupt should be generated on reception

c Airbus Defence and Space 563 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Options A bit mask of options for RT simulation passed as non negative decimal, cur- rently only one option value is available MIL_RT_OPTION_ILL_CMD (0x0001) The remote terminal will respond with sta- tusword bit 0x0400 set to 1 when a command is received for a subaddress that is not configured. If this option is not set the remote terminal will not respond at all. Supported on a simulated mil1553 bus only. Latency A double value defining the response time of simulated remote terminals

Finally the definition of remote terminals can be created. Each remote terminal consists of multiple lines of receive or transmit subaddresses. Additionally the lines already mentioned on defaults can also occur in the remote terminal section and overrules the default.

Keyword Description / values SaRx/SaTx defines a receive subaddress and resp. transmit subaddress in the remote ter- minal. Following attributes can be defined Name A required attribute that defines the logical name of the subaddress for error reporting Address A required attribute that defines the sub address number Address A required attribute that defines the sub address number Int An optional attribute, which can be set to ”On” to force the generation of an interrupt when the SA is accessed Bcast An optional attribute that determines if the subaddress can receive broadcast transmissions. Set ”On” to enable, default is ”Off” Size A required attribute that determines how many words can at most be stored in this subaddress Plus An optional attribute to map the the subaddress to a plusbuffer. The argument is a string containing two comma separated digits, the first refers to the depth of the buffer, which is 2,4,8,16,32 or 64. The second digit refers to the index in the number of those buffers configured. E.g. if the configuration states that there are 3 buffer of size 32, then the first digit is 32, the second digit is either 0,1 or 2. Hence the string could be "32,2" Mc defines a specific mode code. This overrides the default setting. Following attributes can be defined Name A required attribute that defines the logical name of the subaddress for error reporting Number A required attribute that defines the mode code number Int An optional attribute, which can be set to ”On” to force the generation of an interrupt when the SA is accessed Error Configure an error injection on the remote terminal,which can have values None, No_response, Parity, BitCntLo, BitCntH,Gap, Manch_L, Manch_hi, Sync,AltBus,WordCount_Lo, Wordcount_Hi. This however is usually per- formed later on by the user.

29.6.4 Sync interface The mil1553 front-end model has the ability to activate callback on reception of a synchronization mod- ecode, either the Mode Code without data word (MC1) or the Mode Code with dataword (MC17). The sync interface is triggered as soon as such mode code is injected in the front-end model interface. The rationale for this interface is that the Model Reuse Architecture requires direct notification of such sync

564 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

mode codes to align its timelines. class FeModel::Mil1553::SyncIf { public: virtual void updateSyncInfo(double timestamp)=0; //mc1 callback virtual void updateSyncInfo(double timestamp, unsigned int framenr) =0; //mc17 callback }; The Simulator developer must thus create and implement his own class that implements this interface. An object of this class should then be registered with the mil1553 front-end before the init entrypoint is called. Multiple handlers can be installed. FeModel::Mil1553::Model::instance()-> addSyncHandler(*MySyncIfObject);

29.6.5 Dictionary interface The interface to the models offered by the Mil1553 front-end model is shown in 29.9.

Figure 29.9: Mil1553 Front-End Model in dictionary

The layout of the mil1553 front-end model is considerably different then the layout of the discrete front- end model. The main cause is that the discrete front-end contains a large amount of single stream lines. The mil1553 model, being a bus, has a single line that is highly complex as it splits out in multiple remote terminals. The same principles however still apply. The bus has info and config variables that tailor the bus behavior. The sim and fe folders each contain variables that describe the remote terminals. The fe folder contains this in a raw approach where all remote terminals are visible in a single structure. The sim folder contains a more object oriented view that shows the remote terminals that are defined in the XML file. The details of this mil1553 front-end model single ’line’ can be accessed by means of a number of structures that are defined in the file FeModelMilTypes.h. Using the Esim::link API can be used to create links to the appropriate granularity level of the information available: Remote Terminal, Sub Address,

c Airbus Defence and Space 565 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Dataword, Mode code data words. In the following table receive and transmit are defined from the perspective of the unit model.

566 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Structure Description MilEmRtData Remote Terminal data: The top level data storage structure including all data words and mode code data for all sub addresses of a remote terminal. This includes: MilEmSaData rSa Receive data words for all SAs of a RT: includes the data words: dw[...] MilEmSaData tSa Transmit data words for all SAs of a RT: includes the data words: dw[...] MilEmRMcData rMc Receive mode code data: mc17Dw, mc20Dw, and mc21Dw MilEmTMcData tMc Transmit mode code data: mc16Dw, and mc19Dw MilEmRtStatus Remote Terminal status: The top level send / receive status structure for all sub addresses of a remote terminal (data words and mode code data). This includes: MilEmSaStatus rSaStatus[...] Receive status for all SAs of a RT: includes message count, timestamp, and number of datawords written by the Front-End model: count, stamp, and size respectively MilEmSaStatus tSaStatus[...] Transmit status for all SAs of a RT (rele- vant for the Front-End model) MilEmMcStatus mcStatus[...] Mode Code status of a RT: : includes mes- sage count, and timestamp: counter, stamp respectively int numCmdsInHistory The actual number of Mil commands recorded in cmdHistory MilCmdHistoryItem cmdHistory[...] Mil commands are recorded for debug purposes until the cmdHistory array is full. To flush the recorded history and to restart the record- ing, set the following attributes in the MilEmRtConfig structure: mMilEmRtConfig->resetCmdHistoryCnt += 1; (add 1 to the resetCmdHis- toryCnt), mMilEmRtConfig->handledCommands = mMilEmRtStatus->numCmdsInHistory; (assign numCmdsInHistory from MilEmRtStatus to handledCommands) and subsequently, and mMilEmRtStatus->numCmdsInHistory = 0; (set num- CmdsInHistory to 0). MilEmSaData The data words for regular sub addresses: Provides an array of 32 data words: dw[...]

The Mil1553 Front-End model also provides facilities for Deep addressing, which allows the data of a sequence of transmissions to the same subaddress to captured in Plus buffers.

Structure Description MilEmSaData.. Plus buffer data areas for sub addresses that require deep addressing: The following buffer size / message depths are available (each provides: dw[...] of appropriate size) MilEmSaData02 Buffer for 2 messages: provides an array of 2 * 32 data words MilEmSaData04 Buffer for 4 messages: provides an array of 4 * 32 data words MilEmSaData08 Buffer for 8 messages: provides an array of 8 * 32 data words MilEmSaData16 Buffer for 16 messages: provides an array of 16 * 32 data words

c Airbus Defence and Space 567 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

MilEmSaData32 Buffer for 32 messages: provides an array of 32 * 32 data words MilEmSaData64 Buffer for 64 messages: provides an array of 64 * 32 data words

With respect to deep addressing or the use of Plus Buffers the following notes are relevant:

• The XML configuration file supports different configurations of the type of buffers where the type differs in the depth of the buffer. This is defined in the Configuration section: 2,3,6,16,6,3 .

This mapping must be present if plusbuffers are used AND must be 2,3,6,16,6,3 which means that there are 2 buffers of length 2, 3 buffer of lento 4, 6 buffers of lent 8, 16 buffers of length 16, 6 buffers of length 32 and 3 buffers of length 3. In future versions this configuration setting will allow more flexible definitions.

• Instead of using Esim:links to individual dataword variables or to variables of the MilEmSaData type, links are created to Plus Buffer variables MilEmSaData<..> variables (where <..> represents the depth of the of the buffer (the number of messages of data it can hold) as described above: 02 - 64).

• A deep addressing protocol implementation is required in the Unit Models that exchange data through deep addressing to manage the data flows and the amount of data that is made available. This protocol is typically implemented using data words on other sub addresses than are used for the deep addressing itself. For example a descriptor is send to a subaddress of an RT, where that descriptor defines that x messages are send to address y. Then the RT knows where which data is to be found and responds with a descriptor to the BC to confirm that it has processed the information. The BC is then allowed to do another transmission.

• The Sub Addresses that require deep addressing are configured using the same XML file that is used to configure the regular sub addresses and remote terminals as described in section 29.6.3.

• The plus buffer functions as a queue. The programmer of the model should set the variable resetSaPlusOffsetCnt of the MilEmRtConfig structure to reset the index that is used when a series of transfers is complete. The next series of transmit or receive messages will then be stored or retrieved start again from index 0.

29.6.6 Simulation model interface Simulation models can access the remote terminals and sub addresses in the mil1553 front-end model in two different approaches. The first approach is to access attributes through direct reading and writing of the variables in the dictionary. In the first approach the model developer uses either the classic C ModelDescription/Parameter Exchange leading to transfer entrypoints or the more efficient CPP API’s Link objects to provide a direct pointer access to the variables. The second approach is to use the Link to point to the object in the dictionary that represents the remote terminal in the discrete Front-End model and invoke its methods to manipulate it. The latter is a more object oriented approach where the attributes are only accessed through the methods in the object. The first approach is used in the ThermoMra1 example, the second in the ThermoMra2 example.

29.6.6.1 Access through dictionary variables For C++ models, such as the MRA models, the easier approach to exchange data between the Unit Model Software and the Front-End Model is to use the Esim::link API. Instead of adding a variable to

568 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

the dictionary, the Unit Model gets direct access to the variables that are published in the dictionary by linking an Esim::Link object to the variable in the dictionary. Depending on the desired level of granularity the link can be established on remote terminal status, remote terminal data, Sub Address status, Sub Address data, or an individual data words. The Esim::link fnction connects the Esim:Link in the Unit Model to the variable in the Front-End model, avoiding the need to copy the data at run time. The copy is not needed the Front-End Model already provides protection against mutual access. The use of the Esim::Link object to point to directly access the attributes of the Mil1553 front-end model is illustrated in the ThermoMra1 example provided in the EuroSim distribution.

29.6.6.2 Access through dictionary objects The variables exposed in the dictionary are child attributes that are published by their parent, the MIL1552 remote terminal object. Instead of accessing the dictionary variables through Links to variables, it is also possible to let the Link object point to the front-end object. The Link acts as a pointer and through that it becomes possible to invoke the methods of a Mil1553 remote terminal object. The effect is similar to direct manipulation of the attributes that are published by the remote terminal but the interaction is more in line with the object oriented nature of C++. Setting the link to a line in the discrete front-end is accomplised using the Esim::link function to connect a link object or link path to the path to the object in the dictionary. The interface that is exposed by the remote terminal object in the front-end model is mostly to write or read data. Error injection etc. is performed using scripting and hence accesses the variable through the dictionary. The method names are self explanatory:

const char* getName()=0;

MilRtMode getMode()=0; void setMode(MilRtMode mode)=0; void setError(const MilErrorRequest &protocol_error )=0; MilBusChannel getListenTo()=0; void setListenTo(MilBusChannel listento)=0;

void resetCmdHistory()=0; void resetSaPlus()=0;

//SA int getSaWord(MilTx tx, uint8_t saidx, uint16_t offset, MilWord &word) =0; int getSaWords(MilTx tx, uint8_t saidx, uint16_t offset, MilWord *words, size_t &wordcnt) =0; int getSaData(MilTx tx, uint8_t saidx, MilEmSaData &sadata) =0; MilWord& getSaWord(MilTx tx, uint8_t saidx, uint16_t offset) =0; MilWord* getSaWords(MilTx tx, uint8_t saidx, uint16_t offset) =0; MilEmSaData* getSaData(MilTx tx, uint8_t saidx) =0;

int setSaWord(MilTx tx, uint8_t saidx, uint16_t offset, const MilWord& word) =0; int setSaWords(MilTx tx, uint8_t saidx, uint16_t offset, const MilWord *words, size_t wordcnt) =0; int setSaData(MilTx tx, uint8_t saidx, const MilEmSaData &sadata) =0;

int getSaStatus(MilTx tx, uint8_t saidx, MilEmSaStatus& sastatus)=0; MilEmSaStatus* getSaStatus(MilTx tx, uint8_t saidx)=0;

int setSaError(MilTx tx, uint8_t saidx, const MilEmSaError &saerror)=0;

//MC int getMcWord(uint8_t number, MilWord &word)=0;

c Airbus Defence and Space 569 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

const MilWord* getMcWord(uint8_t number)=0; int setMcWord(uint8_t number, const MilWord &word)=0; int getMcStatus(uint8_t number, MilEmMcStatus& status)=0; const MilEmMcStatus* getMcStatus(uint8_t number)=0;

29.6.7 Front-end interface The front-end interface for the Mil1553 front-end model emulates the sending of mil commands by the bus controller and the subsequent reply message by the remote terminal over the bus. This is captured in one mil1553 front-end API call which has a Command structure as input argument and Reply struc- ture as output argument. The Command structure contains the details over the command including the datawords that are transmitted. The Reply structure contains the parameters of the message returned by the remote terminal, including datawords for a transmit command. The interface is defined in the file FeModelMilCdmuIf.h. The types used can be found in the file FeModelMilTypes.h. // Mil Command message transmitted by BusController. typedef struct MilCmdCommand { MilBusId bus; /*!< The milbus to which to send the command.*/ MilBusChannel channel; /*!< Over which of the redundant busses to send .*/ uint16_t cw; /*!< command word */ uint16_t dw[MAX_BUF_SIZE]; /*!< data words from CDMU to remote * terminal. Only useful for receive * commands */ double timestamp; /*!< time that the command is send. This must be * simulation time. */ } MilCmdCommand;

//Mil reply data that is filled by the remote terminals. */ typedef struct MilCmdReply { uint16_t sw; /*!< status word */ uint16_t dw[MAX_BUF_SIZE]; /*!< data words from remote terminal to CDMU */ int size;/*!< nrof data words returned. If negative then also no * status word is returned (sw is invalid) */ float responseTime; /* What was the response time of the rt.*/ MilErrorOccur milError; /* indicate if an error occurred in this command */ } MilCmdReply;

/************************************************************ * CDMU Interface functions declarations ************************************************************/ /*! * CDMU interface function to send/receive data and commands over the mil bus. * Note that caller is responsible for allocating memory for reply structure. * \param cmd The command from the CDMU to the RT * \param reply The reply data from the RT to the CDMU * \return - */ void MilCommand (const MilCmdCommand *cmd, MilCmdReply *reply);

570 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

29.6.8 Device interface 29.6.8.1 Introduction To develop a device interface for the front-end model, the developer has to derive his device specific class from the FeModel::Mil1553::DevIf class defined in the file FeModelMilDev.h (simply include esim++.h and it will include all relevant files for you). The device interface class defines the abstract methods that must be implemented for the simulation of remote terminals for a specific bus. The class also defines the methods that are to be implemented for the bus controller, which is used by the Stub in testing the simulator in loop-back. The implementation of this class is compiled and linked into a plugin (dynamic library) and loaded by the front-end model at runtime. The FeModel::Mil1553:DevIf class is in turn derived from the EuroSim FeMode::Device interface base class which requires the implementation of the standard methods that must be present in all EuroSim device classes. This interface has been discussed earlier in this chapter. It includes the create and destroy C functions that instantiate an object when the plugin approach is used. For this plugin approach the plugin developer must implement the functions that return the Mil1553 specific device object in the create function and delete this object in the destroy function. The implementation can be linked into a shared library to become a plugin to which the XML configuration file can refer such that is loaded if and only if the model is switched to HIL mode. The EuroSim consortium strives to provide pre-built plugins with the device interface implementation for specific boards. This requires collaboration with the manufacturer and can only be done for select devices. Currently EuroSim supports the Mil1553 PCI(e) cards from AIM. More information can be found here Section 29.6.13.

29.6.8.2 System functions The following interface provides support methods, which use is optional and do not relate directly to remote terminals or the buscontroller:

• MilHandle boardOpen(const char *devpath) Purpose: Open the device and setup all administration. The device path is the content of the tag in the Mil1553 xml configuration file. This may be zero or a string of length zero. The plugin provider must inform the user how to parameterise the plugin. Note that these calls are always performed by the Mil1553 Fe Model if the board is mentioned in the XML con- figuration file. Rather then directly interfacing with Mil1553::DevIf functions, the user can call FeModel::Mil1553::instance()->getBoard(index). The returned board object understands the same interface as documented below for DevIf. This only applies to user users that want to utilize the bus controller functions. Return: board handle to pass as argument to subsequent interface functions or zero on failure.

• MilRetVal boardClose(MilHandle brdHnd) Description: Close the board on the hardware defined by the brdHnd returned from boardOpen(...) Return: Zero on success or a unique negative value indicating the result

• MilHandle busOpen(MilIdx boardIdx, MilIdx streamId) Purpose: Open the bus on the hardware identified with boardIdx and streamIdx which can be configured in the Mil1553 front-end configuration file. The streamIdx counts up from one per board. Return: bus handle to pass as argument to subsequent interface functions or zero on failure.

• MilRetVal busClose(MilHandle busHnd) Description: Close the bus on the hardware defined by the busHnd returned from busOpen(...) Return: Zero on success or a unique negative value indicating the result

c Airbus Defence and Space 571 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• MilRetVal setCouplerMode(MilHandle busHnd,MilBusCouplerMode cplModeA,MilBusCouplerMode cplModeB) Purpose: set the coupler mode of the bus according to CplrMode which can have the following values: MIL_BUS_CPL_ISOLATED (0) MIL_BUS_CPL_NORMAL (1) Transformer coupled MIL_BUS_CPL_DIRECT (2) Direct coupled MIL_BUS_CPL_NETWORKEMUL (3) Transformer coupled with resistive network emulation MIL_BUS_CPL_WRAPAROUND (4) Digital on-board wrap-around between Encoder and Decoder

• MilRetVal getCapacity(unsigned &capacity) Purpose: Set capacity to the actual number of busses supported by the board. Returns: 0 on success, -1 on error

• MilRetVal busSetDefaultGap(MilHandle busHnd, MilBusGapMode gapmode, uint16 t gap) Purpose: Change the default inter-message gap for all transfers on a bus. The hard-coded default is 0, 0. Parameters: busHnd Bus handle returned by busOpen(). gapmode MIL BC GAP MODE DELAY (0), MIL BC GAP MODE STANDARD (1) or MIL BC GAP MODE FAST (2). gap Transfer wait time.

• MilRetVal busSetResponseTimeout(MilHandle busHnd, float timeout) Purpose: Set the response timeout of the bus (A and B). Parameters: busHnd Bus handle returned by busOpen(). timeout Time out in usec [0 .. 63.75].

• MilRetVal getTime(double &now) Purpose: Store the current time of the clock used for timetagging mil commands in the variable now, converted to UNIX epoch in seconds Returns: 0 on success, -1 if the clock interface is not supported, <-1 on other errors

29.6.8.3 Remote Terminal simulation The following list contains all the methods and their parameters required for remote terminal simulation as defined in the class FeModel::Mil1553::DevIf. Note that when the argument is defined to be the wordcount (wc) it means that 32 is encoded as zero in accordance with the Mil1553 standard.

• MilHandle rtOpen(MilHandle busHnd, MilIdx rtIdx, MilBusChannel chn, float responsetime) Purpose: Open the remote terminal with index rtIdx on the hardware and return a handle that will be provided as argument to subsequent interface functions on Remote Terminals. The created remote terminal is started but disabled. Parameters: MilBusChannel can have the following values MILBUS_PRIMARY (0) ID to specify the primary MIL bus MILBUS_SECONDARY (1) ID to specify the secondary MIL bus MILBUS_BOTH (2) ID to specify both primary and secondary MIL bus MILBUS_NONE (3) The light is on but nobody is home Return: A handle to the created remote terminal or zero otherwise. On failure all allocated and associated resources must be deleted.

• MilRetVal rtClose(MilHandle rtHnd) Purpose: Close the remote terminal identified by rtHnd. This disables the Rt and deletes all created and associated resources.

572 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• MilRetVal rtEnable(MilHandle rtHnd,MilBusChannel chn) Purpose: Enable the remote terminal identified by the handle rtHnd for simulation on channel chn

• MilRetVal rtDisable(MilHandle rtHnd ) Purpose: Disable the remote terminal identified by the handle rtHnd. (Note that the initial state of a remote terminal is determined by the RtMode statement in the XML file).

• MilRetVal rtSetSw(MilHandle rtHnd, MilWord statusword) Purpose: Set the statusword for the Remote Terminal identified by rtHnd to statusword.

• MilRetVal rtErrSet(MilHandle rtHnd,MilTx tx,MilError type,MilWord extra,MilWord word) Purpose: Set error injection on all sub addresses configured on the remote terminal identified by the handle rtHnd. This calls saErrSet for all sub addresses, see the description for saErrSet for the parameter values.

• MilRetVal rtErrClear(MilHandle rtHnd, MilTx tx) Purpose: Clear error injection on the remote terminal identified by the handle rtHnd. This per- forms an saErrClear on all sub addresses configured on the remote terminal, See saErrClear for parameter values

• MilRetVal saErrSet(MilHandle saHnd, MilError type, MilWord extra, MilWord word) Purpose: Set error injection of type errortype on the SubAddress. Extra and word are additional parameters dependent on the error type. Parameters: type, word and extra have the following set of values MIL_ERROR_PARITY (2) Emulate hardware parity error MIL_ERROR_BITCNT_LO (3) Bit count low in word. (extra=nr of errorbits) MIL_ERROR_BITCNT_HI (4) Bit count high in word. (extra=nr of errbits) MIL_ERROR_GAP (5) Gaperr after word. (extra=time in halfbits incr) MIL_ERROR_MANCH_LO (6) Hardware manchester error (extra=databit) MIL_ERROR_MANCH_HI (7) Hardware manchester error (extra=databit) MIL_ERROR_SYNC (8) Sync field error. (extra=syncfield in halfbits) MIL_ERROR_ALTBUS (9) Alternate bus error MIL_ERROR_WORDCOUNT_LO (10) Transmit less datawords (extra=delta) MIL_ERROR_WORDCOUNT_HI (11) Transmit more datawords (extra=delta)

• MilRetVal saErrClear(MilHandle saHnd) Purpose: Clear error injection on the sub address identified by saHnd

• MilHandle saId(MilHandle rtHnd, MilTx tx, MilIdx saIdx, MilSaPlusBufferType plusType, Mil- IntrRequest defIntReq=-1 ) Purpose: Configure the sub address code with Transmission direction tx and index saIdx. The plusbuffer type identifies the deep addressing capability needed, for normal cases this is zero. The defIntReq argument allows to set the default interrupt settings, -1 means not set by the programmer and results in a default of MIL_INTR_NONE as defined in FeModelMilTypes.h Returns: Handle to the configured sub address code, required in sub address access functions.

• MilRetVal saEnable(MilHandle saHnd, MilIntrRequest intreq=-1) Purpose: Enable the sub address for the given sub address handle. Using intreq the caller can request an interrupt generation when a transfer completes on the subaddress. This instruction currently is not using memory mapping hence use with care Parameters: MIL_INTR_NONE (0) Do not generate the interrupt on transfer MIL_INTR_XFER (1) Generate an interrupt when data transfer in the subaddress completes MIL_INTR_ERR (2) Generate an interrupt when an error occurs on the subaddress A value of -1, which can be achieved by not specifying the argument in the call leaves the current interrupt setting for the MC unchanged.

c Airbus Defence and Space 573 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• MilRetVal saDisable(MilHandle saHnd) Purpose: Disable the sub address for the given sub address handle. This instruction currently is not using memory mapping hence use with care • MilHandle mcId(MilHandle rtHnd, MilTx tx, MilIdx mcIdx) Purpose: Configure the mode code with Transmission direction tx and index mcIdx. Parameters: The mode code index can have the following values MC_TRANSMIT_VECTOR ((uint16_t) 0x10) MC_TRANSMIT_BIT ((uint16_t) 0x13) Returns: Handle to the configure mode code, required in mode code access functions. • MilRetVal mcEnable(MilHandle mcHnd, MilIntrRequest intreq=-1) Purpose: Enable the ModeCode for the given mode code handle Using intreq the caller can request an interrupt generation when a transfer completes on the subaddress: Parameters: MIL_INTR_NONE (0) Do not generate the interrupt on transfer MIL_INTR_XFER (1) Generate an interrupt when data transfer in the subaddress completes MIL_INTR_ERR (2) Generate an interrupt when an error occurs on the subaddress A value of -1, which can be achieved by not specifying the argument in the call leaves the current interrupt setting for the MC unchanged. This instruction currently is not using memory mapping hence use with care • MilRetVal mcDisable(MilHandle mcHnd) Purpose: Disable the ModeCode for the given mode code handle This instruction currently is not using memory mapping hence use with care • MilRetVal saRead(MilHandle saHnd, MilWord wc, MilWord *data, Milword plusIdx=0) Purpose: Read wordcount (wc) words from a sub address on the device into data. Wordcount zero is assumed to be equal to 32. The argument plusIdx identifies which 32 milword element of the plusbuffer is the starting point. A wordcount Larger then 32 is allowed, which can be used to write subsequent subaddress parts of the plusbuffer • MilRetVal saWrite(MilHandle saHnd, MilWord wc, MilWord *data, MilWord plusIdx) Purpose: Store wordcount (wc) words of the provided data array into a sub address on the device. Wordcount zero is assumed to be equal to 32. The argument plusIdx identifies which 32 milword element of the plusbuffer is the starting point. A wordcount larger then 32 is allowed, which can be used to write subsequent subaddress parts of the plusbuffer. • MilRetVal mcRead(MilHandle mcHnd, MilWord dataword) Purpose: Store the dataword for a mode code on the device • MilRetVal mcWrite(MilHandle mcHnd, MilWord &dataword) Purpose: Read the dataword from a mode code on the device

29.6.8.4 Bus Monitor operation The following list contains all the methods and their parameters required for busmonitor operation as defined in the class FeModel::Mil1553:DevIf. Bus Monitor, also referred to as bus spying, can record all the mil words on the bus into a circular buffer. The Mil1553 Front-End model uses this buffer to transfer the messages on the bus to the FeModel Mil1553 command interface. The interface uses callbacks to allow applications like the Mil1553 Front End model to get the data from the Monitor buffer. Note that the Mil1553 FeModel installs its callbacks when its init function is called. The functions below are also present in the FeModel::Board class, which wraps the management of the loading of the plugin.

• typedef MilRetVal (*BmMsgCbk)(void *userarg,MilWord chan,MilWord rt,MilWord sa,MilWord wc,MilTx tx, MilWord sw,MilWord dw[],double ts); Purpose: Prototype of the message callback function used in the bmSetMsgCbk and bmGetMs- gCbk functions

574 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• MilRetVal bmSetMsgCbk(MilHandle busHnd, BmMsgCbk cbk, void *userarg) Purpose: Install the Message Callback function, which will be invoked for every complete mes- sage in the monitor buffer as a consequence of calling the bmRead function. The parameter userarg is passed on as argument to the callback. Returns: 0 on success, -1 on error

• MilRetVal bmGetMsgCbk(MilHandle busHnd, BmMsgCbk *cbk, void **userarg) Purpose: Retrieve the currently installed message callback function and argument EuroSim. Returns: 0 on success, -1 if no callback wass installed

• typedef MilRetVal (*BmDataCbk)(void *userarg, const void* data, size t size); Purpose: Prototype of the data callback function used in the bmSetDataCbk and bmGetDataCbk functions

• MilRetVal bmSetDataCbk(MilHandle busHnd, BmMsgCbk cbk, void *userarg) Purpose: Install the Data Callback function, which will be invoked for a list of datawords. This is most usefull for storage to file. The plugin developer determines the data. The parameter userarg is passed on as argument to the callback. EuroSim. Returns: 0 on success, -1 on error

• MilRetVal bmGetDataCbk(MilHandle busHnd, BmMsgCbk *cbk, void **userarg) Purpose: Retrieve the installed data callback function EuroSim. Returns: 0 on success, -1 if no callback wass installed

• typedef MilRetVal (*BmTextCbk)(void *userarg, const void* data, size t size); Purpose: Prototype of the data callback function used in the bmGetTextcbk and bmSetTextCbk functions

• MilRetVal bmSetTextCbk(MilHandle busHnd, BmMsgCbk cbk, void *userarg) Purpose: Install the Text Callback function, which will be invoked for every dataword. This output is a string which decodes the dataword to a message. Note that this is computationally more expensive then logging the datawords, and hence should be used with care. EuroSim. Returns: 0 on success, -1 on error

• MilRetVal bmGetTextCbk(MilHandle busHnd, BmMsgCbk *cbk, void **userarg) Purpose: Retrieve the installed text callback function EuroSim. Returns: 0 on success, -1 if no callback wass installed

• MilRetVal bmRead(MilHandle busHnd, unsigned maxwords, uint32 t flags) Purpose: read and process the monitor buffer. The maxwords is nominally zero, but can be set to limit the amount of words to be read and processed in the call. The benefit is that this limitation may help in scoping the amount of time spent in the bmRead function. Finally the flags argument passes settings via the bits. Setting the least significant bit to 1 (0X01) enables the message call- back callback, setting the second bit (0x02) enables the data callback and or’ing with 0x04 will enable the text callback. EuroSim. Returns: 0 on success, -1 if no callback wass installed.

29.6.8.5 BusController simulation The following list contains all the methods and their parameters required for buscontroller simulation as defined in the class FeModel::Mil1553::DevIf. This buscontroller interface is currently tailored to the usage by the Front-End model Stub. One of the limitations is that it can only operate on channel A. In subsequent minor versions we anticipate updates on this interface to widen the applicability of the bus controller interface.

c Airbus Defence and Space 575 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• MilHandle bcOpen(MilHandle busHnd, float cycletime=100.0, uint8 t primsec=MILBUS PRIMARY) Purpose: Open Bus Controller. Specify the cycletime and the channel to operate on. The float cy- cletime is a float in msec, with usec precision and represents the length of the minor frame time. Returns: Opague BC handle on success or null pointer on failure

• MilRetVal bcStart(MilHandle bcHnd, unsigned repetitions=1) Purpose: Start the Bus Controller, for either a fixed number of repetitions or cyclic (0) repetition. Note that here we currently use the AIM API to start the buscontroller. Some optimalisations are anticipated for next minor releases to utilize mode memory mapped access to increase the performance. Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal bcStatus(MilHandle bcHnd, unsigned &state, unsigned &xfercnt, unsigned &errcnt) Purpose: Read the status of the buscontroller. Parameters: state: the buscontroller is either not started(0), stopped at a halt instruction(1) or busy(2) xfercnt:the number of transfers executed by the bus controller errcnt: the number of errors executed by the bus controller Returns: Error value (error=-1, not supported=-2, ok==0)

• MilRetVal bcClose(MilHandle bcHnd) Purpose: Close Bus Controller Returns: Error value (error < 0, warning > 0, ok==0)

• MilHandle scenCreate (MilHandle bcHnd) Purpose: Create a BusController scenario on the fly Returns: Scenario Handle on success or null pointer on error

• MilRetVal scenLoad(MilHandle scenHnd) Purpose: Buscontroller scenario load Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenClear(MilHandle scenHnd) Purpose: Clear the contents of a scenario Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenAddXfer(MilHandle scenHnd, MilHandle xferHnd, unsigned label=0) Purpose: Load a xfer instruction in the scenario. The label can be set as reference for the AddJmp instruction. Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenAddWmnr(MilHandle scenHnd, unsigned label=0) Purpose: Load a Wait for minor frame instruction in the scenario, which forces a wait for the start of the next minor frame before continueing with the instructions in the scenarion. The label can be set as reference for the AddJmp instruction. Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenAddWait(MilHandle scenHnd, unsigned sleep, unsigned label=0) Purpose: Load a Wait instruction in the scenario, which waits for the number of microseconds defined with the sleep argument. See the documentation of AIM on the resolution. The label can be set as reference for the AddJmp instruction. Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenAddJump(MilHandle scenHnd, unsigned jumpto, unsigned label=0) Purpose: Load a Jump instruction in the scenario, which jumps to the instruction that has the referenced label.The label can be set as reference for the AddJmp instruction. Returns: Error value (error < 0, warning > 0, ok==0)

576 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• MilRetVal scenAddHalt(MilHandle scenHnd, unsigned jumpto, unsigned label=0) Purpose: Load a Halt instruction in the scenario, which stops the execution on the board. The bc- Continue command can be used to continue the execution of the scenario from the halt instruction. The label can be set as reference for the AddJmp instruction. Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal scenDelete(MilHandle scenHnd) Purpose: Delete the Bus Controller Scenario Returns: Error value (error < 0, warning > 0, ok==0)

• MilHandle xferCreate(MilHandle bcHnd, char* name, uint8 t rt, uint8 t tx, uint8 t sa, uint8 t wc) Purpose: Create a xfer Returns: Xfer handle on success, null pointer on error

• MilRetVal xferSetGap(MilHandle xferHnd, MilBusGapMode gapmode, uint16 t gap) Purpose: Set the gap of the xfer. Parameters: xferHnd Transfer handle returned by xferCreate(). gapmode 0=Delay mode, 1=standard gapmode, 2=fast gapmode gap gap in usec, definition depending on gapmode

• MilRetVal xferUpdate(MilHandle xferHnd, uint8 t rt, uint8 t tx, uint8 t sa, uint8 t wc) Purpose: Update the parameters of a transfer Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal xferRead( MilHandle xferHnd, MilWord dw, uint8 t wc /*words*/) Purpose: Read data from the buscontroller SA buffer associated withe the transfer Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal xferWrite(MilHandle xferHnd, MilWord dw, uint8 t wc /*words*/) Purpose: Write data in the buscontroller SA buffer associated with the transfer Returns: Error value (error < 0, warning > 0, ok==0)

• MilRetVal xferStatus(MilHandle xferHnd, uint16 t &lcwd, uint8 t &chn, uint16 t &sw, uint8 t &err, uint32 t <t) Purpose: Read the status of a transfer. Parameters: lcwd: last command word chn: channel on which it occured sw: status word err: error information (0=none,1=any,2=no sw1 3=no sw2) ltt: lower time tag (32 bit min of hour(31-26 )+ sec of min(25-20) + usec of sec(19-0))

• MilRetVal xferDelete( MilHandle xferHnd) Purpose: Delete a created transfer Returns: Error value (error < 0, warning > 0, ok==0)

29.6.9 Bus monitoring The EuroSim Front-end model supports two levels of bus traffic monitoring.

• At the level of the MilCommand interface, all Mil1553 commands can be logged to file. This level works in both a software validation facility where all equipment including the omboard computer is simulated, as well as in hardware in the loop facilities where the onboard computer and/or equipment is electrically intergrated.

c Airbus Defence and Space 577 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• At a lower level, it is also possible to log all the transfers over the bus to file. This is referred to as (raw) data logging. This bus monitoring capability streams card specific data words to file in a realtime safe manner. A post processing tool is needed to decode the data.

• A special case that is supported is text logging to the journal. In this case the logging is per word and thus requires a mil1553 plugin to provide the individual words. However the words are decoded to string and logged in the journal. This is usefull in debugging for specific sections of time. The text logging is sending quite a lot of data and may quickly overload the buffer between the real-time and non real-time domain.

Normal operation of the bus monitoring is accomplished through the variables of the Mil1553 model in the EuroSim Dictionary. In the configuration folder of a bus the following variables can be found:

• logCmdEnable Enables the logging of mil1553 message information to file of all commands on the mil1553 bus

• logDataEnable enables the logging of the raw monintoring data on the mil1553 card to file. The file will contain binary data and must be decoded using a tool provided by the Mil1553 plugin developer as the format is card specific. In case of the AIM MIL1553 plugin the messages are preceed in the log by an IRIG-B hi and low timestamp.

• logTextEnable When activated a tring is printed in the EuroSim journal containing the content and description of a recieved data in the mil1553 monitoring buffer on the card.

The recording to file is streamed to files that automatically cycle when the number of contained records (write actions) reaches the number contained in the variable init/logMaxNumRecsInFile that can be found in the init folder underneath a bus in the dictionary. The file is then closed, the sequence number incremented and a new file opened. Following files are created:

• Mil1553Cmds__.log An ASCII file that contains the log at message level, which can be produced with or without a mil1553 card included in the simulation.

• Mil1553Bus__.log The Mil1553Bus file contains the recording at busmonitor level of the mil1553 card streamed by the plugin. The file starts with a generic ASCII header followed by a binary recording in a format determined by the plugin. The plugin provider must thus also support a utility that can print the contained data in a human readable output, potentially providing filters as well.

For the Aim Mil1553 plugin the conversion utility program is called milcat. The usage is

milcat filename

where options are:

• -h Show online help and exit;

• -c <0|1> Filter on messages send on primary (0) or secondary(1) channel

• -r <0..31> Filter on messages from/to specific RT

• -s <0..31> Filter on messages from/to specific subaddress

• -t <0|1> Filter on receive(0) or transmit(1) messages

• -m Filter on messages after simulationtime ¡s¿, with s a float in seconds

• -M Filter on messages before simulationtime ¡s¿, with s a float in seconds

• -w Filter on messages after walltime ¡s¿, with s a float in seconds

578 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• -W Filter on messages before walltime ¡s¿, with s a float in seconds

The milcat utility prints for each word on the milbus the wallclock time, simulation time and the mil1553 time, followed by the type of the word and its decoded contents. For developers that want to install their own monitoring callback, please be aware that the callback is also used by the front-end model hence the user should replace the installed callback after the completion of the Mil1553 Front-End Model init entrypoint is called. The user installed callback should then call first the originally installed callback which should be retreived using the getCbk methods prio to installing the new callback aftern init.

29.6.10 Error injection The mil1553 front-end model supports two types of error injection; The first is related to subaddress data manipulation and occurs in the sync while copying data in the front-end model. this supports the IGNORE, INSERT and ADJUST options on the data in the sub address. Similar to the discrete front-end model the error variable in a remote terminal allows the configuration and activation of the sync error injection for a specific amount of repetitions. For each subaddress of each remote terminal it provides the ability to perform the IGNORE, INSERT and ADJUST options. IGNORE disconnects the subaddres, the synchronization of data from the fe to the sim side and vice versa is skipped. Insert also disconnects the line but in addition copies the values from the parameter a (a subaddress line) in the error structure. Finally ADJUST performs a bitwise and and or to manipulate the bits in a subaddress on the copy from fe to sim and vice versa. The formula for each word is (dw[i] & a[i]) | b[i]. The data error configuration variables in the dictionary are shown in Figure 29.10.

Figure 29.10: Mil1553 data error configuration

The second error injection relates to Mil1553 protocol error injection capabilities. A few of these op- tions are always available but most require support by the Mil1553 interface board. The protocol error injections are enabled by setting the fields of variable config.error as shown in Figure 29.11.

c Airbus Defence and Space 579 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 29.11: Mil1553 protocol error configuration

The subaddress field is encoded:

• -1 will apply the requested error to all subaddresses

• 1-30 are the values to indicate the transmit subaddresses 1-30

• 33-62 are the values to indicate the receive subaddresses 1-30

• 64-95 are reserved for modecode error injection (not supported for the AIM Mil1553)

The following errors can be selected:

• None (0), default value specifying that no error is set

• No Response (1), RT should give no answer

• Parity (2), Emulate hardware parity error

• Bit Count Low (3), Bit count low in word. (ext=number of errorbits)

• Bit Count Hi (4), Bit count high in word. (ext=number of errbits)

• Gap (5), Gaperr after word. (ext=time in halfbits incr)

• Manchester Low (6), Hardware manchester error (ext=databit)

• Manchester Hi (7), Hardware manchester error (ext=databit)

• Sync (8), Sync field error. (ext=syncfield in halfbits)

• Alternate Bus (9), Alternate bus error

• WordCount Low (10), Transmit less datawords (ext=delta)

• Wordcount High (11), Transmit more datawords (ext=delta)

• Set Status (12), Return given status word (ext=sw)

• RT Busy (13), Rt sets busy bit and returns on status word

580 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The range from Parity (2) up to Wordcount High (11) are HW error injections and require a mil1553 card that supports these error injections. The Front-End model will configure the board based on the error injection values through the plug-in interface when the Front-End model is set to HIL mode. Note that the error injection MUST always be cleared before a new error is selected. This requires that first the error must be set to zero, stay on that value for one call of the synchronization entrypoint, then a new error can be selected.

29.6.11 Utility functions For the Mil1553 front-end model a number of convenience functions are provided for the model devel- oper to read and write to and from dataword arrays. This is typically used by the model developer who has a pointer to a MilEmSaData type and needs for instance to read a float which is stored at a specified offset in the dataword (dw) array of the MilEmSaData type. A major factor for these functions is that they take into account endianity conversions, assuming a little endian host computer. The functions swap the milwords in a larger type, but not the bytes in the milword. The latter is up to the Mil1553 Device im- plementation. The AIM Mil1553 cards supported by EuroSim are for x86_64 and automatically swap the byteorder in the mil data words (uint16_t) as the milwords are big-endian as required by the Mil1553 standard. The data swaps are performed in hardware on the write to and from the card in a little endian machine. Higer order swapping is left to the Model Developer, but these convenience functions perform the swapping task. Variants of the functions with extension AsIs are included, which do not perform such swap. The functions below are included from use in projects. In EuroSim we strive to prvide generic services and hence we expect some better defined API in the future. However more experience must first be gained with the reused implementation to be able to create a more flexible solution. Please be aware that changes in this API is likely inevitable, though we will strive to keep these functions available as deprecated if they are used by customers. It is thus relevant to provide your feedback on the use of these functions. If you have additional utility functions that you like to have added this is in principle feasible, of course requirins some explanation for the documentation and internal EuroSim regression testing. The functions are defined in the file FeModelMilUtil.h that is available in the EuroSim include folder.

Prototype Description double getCucValue( uint16_t coarse_msw, get the time as double from CUC formatted data uint16_t coarse_lsw, uint16_t fine); double getDouble( const uint16_t *data, read a double from mil1553 sub address datawords int offset); with endianity conversion completion double getDoubleAsIs( const uint16_t *data, read a double from mil1553 sub address datawords int offset); wihtout endianity conversion completion float getFloat( const uint16_t *data, read a float from mil1553 sub address datawords int offset); with endianity conversion completion float getFloatAsIs( const uint16_t *data, read a float from mil1553 sub address datawords int offset); without endianity conversion completion uintXX_t getUintXX( const uint16_t *data, read a (XX=64,32,16) bit unsigned integer from int offset); mil1553 sub address datawords with endianity con- version

c Airbus Defence and Space 581 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

uintXX_t getUintXXAsIs( const uint16_t *data, read a (XX=64,32,16) bit unsigned integer from int offset); mil1553 sub address datawords without endianity conversion intXX_t getIntXX( const uint16_t *data, read a (XX=64,32,16) bit signed integer from int offset); mil1553 sub address datawords with endianity con- version intXX_t getIntXXAsIs( const uint16_t *data, read a (XX=64,32,16) bit signed integer from int offset); mil1553 sub address datawords without endianity conversion void putDouble( uint16_t *data, write a double to mil1553 sub address datawords at int offset, specified offset double d); void putDoubleAsIs( uint16_t *data, write a double to mil1553 sub address datawords at int offset, specified offset without endianity conversion double d); void putDoubleAsRawInt16Linear( uint16_t *data, int offset, write a double as a signed 16 bit integer to mil1553 double d, sub address datawords at specified offset. The double a, double b); signed 16 bit integer represents a raw value which is calculated from the following formula: raw = d * a + b. The a and b parameters are best derived from two points that represent the translation of the mini- mum and maximum values (both for d and raw). void putDoubleAsUint32WithLsb( uint16_t *data, int offset, write a double at specified offset as an unsigned 32 double d, bit integer where the double is divided by the value double lsb); represented by the least significant bit before being written void putDoubleAsInt32WithLsb( uint16_t *data, int offset, write a double at specified offset as an signed 32 double d, bit integer where the double is divided by the value double lsb); represented by the least significant bit before being written void putDoubleAsUint16WithLsb( uint16_t *data, int offset, write a double at specified offset as an unsigned 16 double d, bit integer where the double is divided by the value double lsb); represented by the least significant bit before being written void putDoubleAsInt16WithLsb( uint16_t *data, int offset, write a double at specified offset as an signed 16 double d, bit integer where the double is divided by the value double lsb); represented by the least significant bit before being written

582 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

void putFloat( uint16_t *data, write a float to mil1553 sub address datawords at int offset, specified offset float f); void putFloatAsIs( uint16_t *data, write a float to mil1553 sub address datawords at int offset, specified offset without endianity conversion float f); void putFloatAsUint16WithLsb( uint16_t *data, int offset, write a float at specified offset as an unsigned 16 float f, bit integer where the double is divided by the value float lsb); represented by the least significant bit before being written void putFloatAsInt16WithLsb( uint16_t *data, int offset, write a float at specified offset as a signed 16 bit in- float f, teger where the double is divided by the value repre- float lsb); sented by the least significant bit before being writ- ten void putUintXX( uint16_t *data, write unsigned (XX=64,32,16) bit integer to int offset, mil1553 sub address datawords at specified offset uintXX_t i); with endianity conversion void putUintXXAsIs( uint16_t *data, write signed (XX=64,32,16) bit integer to mil1553 int offset, sub address datawords at specified offset without en- uintXX_t i); dianity conversion void putIntXX( uint16_t *data, write unsigned (XX=64,32,16) bit integer to int offset, mil1553 sub address datawords at specified offset intXX_t i); with endianity conversion void putIntXXAsIs( uint16_t *data, write signed (XX=64,32,16) bit integer to mil1553 int offset, sub address datawords at specified offset without en- intXX_t i); dianity conversion void putUint32From2Uint16s( uint16_t *data, int offset, write unsigned 32 bit integer to mil1553 sub address uint16_t i, datawords at specified offset by combining the val- uint16_t j); ues of two unsigend 16 bit integers void putScet ( uint16_t *data, write event time to data pointer double scet); void getScet ( const uint16_t *data, read event time from data pointer double *scet); uint16_t parity( uint16_t data, Compute parity for 16 bit dataword, returns parity in bool odd); lsb

c Airbus Defence and Space 583 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

uint16_t parity( uint16_t data, Check parity for 16 bit dataword, returns true if data bool odd); word has the parity as specified by odd (odd==tue)

29.6.12 Tests For testing a simulator can be built with only the Mil1553 device instantiated and published. Please see the front-end test simulator in the provided examples: ThermoMra1/Simulator/Fe. This allows manual testing from a Simulation Controller or automation of testing from either perl, python, tcl or java scripting using the EuroSim batch packages. The MDL realtime scripting can further be used to provide timing specific test control as well as that the Mil1553 front-end model includes error injection to stimulate or alter values. With out of the box provided plugins there are also dedicated test programs available that do not require EuroSim but operate solely on the plugin. See Section 29.6.13.

29.6.13 Supported Mil1553 Devices To utilize the Mil1553 Front-End model, a plugin must be written that maps the EuroSim Mil1553 generic device interface on the Board Support Package of a specific device. This must be done in such manner that realtime access is guaranteed, in particular favoring memory mapped access to the firmware in the device as that is the guaranteed most realtime solution. This often requires collaboration with the manufacturer. The plugin can be either developed by EuroSim and packaged as EuroSim RPM or delivered by a supplier directly.

29.6.13.1 AIM APE/APX Mil1553 EuroSim provides a realtime optimized implementation of the Mil153 device interface for the AIM PCI and PCIe cards. A single plugin can handle multiple boards of different configurations, e.g. single, dual or quad stream. Where the standard API uses kernel IPC (e.g. ioctl) and sometimes DMA, the EuroSim implementation is using memory mapped access for those functions where access performance is critical. The implementation has been supported by AIM and the memory mapping capability has been integrated in the AIM driver software. The plugin is delivered as a seperate EuroSim RPM that is automatically part of the provided RPMs when supported for the particular OS. Because the strategy for this plugin is to use the AIM BSP where possible and only utilize the memory mapped solution for critical functions should make it relatively easy to maintain the driver for BSP releases by AIM. it is however wise to contact the EuroSim helpdesk to check on the availability of the plugin and BSP for for preferred OS as drivers are quite sensitive to OS and Linux kernel. The EuroSim AIM Mil1553 plugin implements the complete interface and combines the Device interface for memory mapped access with the the interface for an event handler in one plugin. The same plugin can thus also be used in the ScheduleEditor as plugin library for an event handler. In EuroSim Mk7.1 the following limitations exist in this plugin (check with helpdesk for latest status):

• interrupt generation on modecode is not yet operational.

• bus monitor operation is default enabled and started as part of the busOpen operation, and disabled on the busClose.

• it is to be tested if a seperate program can access a board that is opened by the simulator in support of testing.

The EsimAimMil1553 plugin understands the following parameters in the Board section of the configu- ration file:

584 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• Module=x Purpose: x is the AimModuleNumber. The Device setting is ignored. To identify which board is connected to a module number, please use the sample program delivered as part of the AIM board support package

• MemSize=BiuNr:BcHipInstr,BcLipInstr,BcAcycInstr,ReplayBuf,BmBuf Purpose: A Memory Size parameter line must be exactly formatted as above and defines the memory size layout of a biu (a bus processor) as defined in the AIM reference manual, see function ApiCmdSysSetMemPartition. The BiuNr must be a number in the range [0::7] to identify which biu is manually defined. Currently AIM provides quad stream cards where the maximum value for biu is then 3. The higher numbers are reserved for future boards. A negative value for a size parameter will silently be ignored and not change the default setting in the board. Allthough all size parameters must be present, this mechanism allows overriding only selective size parameters in a line. Setting of the memory layout is an advanced feature and must keep the entire memory within the available memory size of the board. See the AIM user and reference manual on this topic for more information.

• MemCount=BiuNr:RepBuf,RtBhArea,RtSqArea,RtEqArea,BcBhArea,BcSqArea,BcEqArea,BcXferDescr Purpose: A Memory Count parameter line must be exactly formatted as above and defines the memory counts layout of a biu (a bus processor) as defined in the AIM reference manual, see function ApiCmdSysSetMemPartition. The BiuNr must be a number in the range [0::7] to identify which biu is manually defined. Currently AIM provides quad stream cards where the maximum value for biu is then 3. The higher numbers are reserved for future boards. A negative value for a size parameter will silently be ignored and not change the default setting in the board. Allthough all size parameters must be present, this mechanism allows overriding only selective size param- eters in a line. Setting of the memory layout is an advanced feature and must keep the entire memory within the available memory size of the board. See the AIM user and reference manual on this topic for more information.

• MapEnable=x Purpose: x is limited to 0 or 1, where settign MapEnable to zero forces the plugin to use the AimMil1553 API rather then memory mapped access. This capability is useful for debugging to verify the correct operation of the hard realtime memory mapped interface capability and hence most relevant for the EuroSim consortium that maintains this plugin.

• ResponseTimeout=x Purpose: Change the default bus controller response timeout for all busses on the card from 14 micro seconds to x micro seconds. The argument x must be an unsigned integer value. For each bus this can be changed through the bus controller interface functions.

• Verbose=x Purpose: x is limited to 1 in EuroSim Mk7.1 to force a tracing of all function calls on the plugin and print debug information. In future versions the verbosity value will follow the same value resolution as the Front End Model log values.

To verify the Mil1553 setup of the hardware, device driver and EuroSim AimMil1553 plugin, three test programs are provided in $EFOROOT/bin/testutil. milSelfTest.exe Five self-test cases with an increasing level of complexity. The test cases are described below. testRtMil.exe Verifies the real-time performance of SA read and write operations. To achieve real-time per- formance, run this test with the command line argument -r. Note that this requires the sys nice capability. To allow a normal user to run the test in real-time mode, run this command first: sudo setcap ’cap sys nice+pe’ testRtMil.exe.

c Airbus Defence and Space 585 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

testRtMilProfile.exe Verifies the real-time performance of SA read and write operations on at 16 different sub ad- dresses. Other than the number of sub addresses, this test is identical to testRtMil.

The five test cases of milSelfTest.exe are:

1. A basic health check that verifies that the EuroSim AimMil1553 plugin can be loaded and handles to an AIM board and bus can be obtained. 2. A short internal loopback test. This test uses the digital on-board wrap-around from encoder to decoder — MIL_BUS_CPL_WRAPAROUND. 3. The same loopback test with an external loopback. This test uses the transformer coupled mode — MIL_BUS_CPL_NORMAL. 4. A duration test with internal loopback. 5. A duration test with external loopback.

To get an explanation of the command line arguments that are needed to select a test case, run the program with -h.

29.7 Timekeeper Front-End model

29.7.1 Introduction In hardware in the loop test facilities there are usually different times and clock sources. To investigate the simulation results it is important to be able to correlate recordings base on time. For instance the milcard may stamp its monitor messages in the recording file with its local hardware clock but the EuroSim simulator incorporates its wallclock in the recordings. This is not a problem as long as the correlation between these values is known througout the simulation run. (Note at the start only may not be sufficient due to clock drifts). In some facilities this problem is solved by slaving all systems to a common time source, often via so called IRIG-B interface cards in combination with a central IRIG-B clock, though other solutions also exist. This is not always convenient or possible though, as well as that it may be costly. The Timekeeper follows a different approach where it records all times at the same time at a regular interval in its Timekeeper TimeSet structure. The user can record this structure or parts thereof in the simulation run to support the correlation of results that are tied to different clocks. The Timekeeper Front-End model defines and maintains the following times in its FE::Timekeeper::TimeSet structure:

• smt Simulation time in seconds, start at zero when entering the execution state of a EuroSim simulator and increases with the base frequency of the simulator.

• wct Wallclock timein seconds, start at zero at the start of a EuroSim simulator launch and increases from there in line with the computer clock.

• syt System time in seconds, filled by reading the value of clock gettime, thus deliverering the computer clock with unix epoch.

• tft Test facility time in seconds, filled by reading the value of clock that represents a specific hardware clock in the test hardware. Which clock and what it exactly means is depending on the test facility and the implementation of the Timekeeper class by a simulator developer.

• etft Extrapolated Test facility time in seconds, which is computed by the timekeeper class au- tomatically by adding the difference between in wallclock time since the last time that tft was measured. This is relevant in case the test facility time can not be read at the highest frequency and hence needs extrapolation to provide the time at intermediate steps.

586 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• obt Onboard Time in seconds, the value of the clock on board of the onboard computer which is communicated via some hardware channel. The exact meaning of the time depends on the context.

• eobt Extrapolated Onboard Time in seconds, which is computed by the timekeeper class automat- ically by adding the difference between in wallclock time since the last time that tft was measured. This is relevant in case the onboard time can not be read at the highest frequency and hence needs extrapolation to provide the time at intermediate steps.

The objective of the Timekeeper Front-End model is to update all the fields of the TimeSet structure at the frequency at which it’s step entrypoint is scheduled. For the TFT and OBT fields it requires that the simulation developer implements how to actually read the clock. Additionally the reading of such clock may be possible in a synchronous manner, or it is triggered by some event which updates the field in an asynchronous manner. The TFT is often synchronous by e.g. reading the time from an IRIG-B interface, but the onboard time is updated on demand as result of the arrival of an OBT distribution of the onboard computer. The Timekeeper Front-End model implementation is currently still of a limited scope. A Timekeeper base class is available which is complete and handles all generic features. A timekeeper derived class is available that implements the base class features by reading the Test Facility Time in a synchronous implementation via the Mil1553 getTime() model interface. Additionally it is expected to read the OBT in an asynchronous manner from a Mil1553 model subaddress at a defined access. The derived class is currently configurable via its constructor and setter methods. It is expected that this Timekeeper derived class will be expanded in future releases such that it is configured from an XML file for a wider range of capabilities.

29.7.2 Setup The Timekeeper model can be developed by the simulator developer or be reused from EuroSim which provides prebuilt configurable Timekeeper models. The Timekeeper interface class defines what the simulator developer has to implement namespace FeModel::Timekeeper { class ModelIf : public FeModel::BaseModel, public MRA::TimeManager {

struct TimeSet { double smt; double wct; double syt; double tft; double etft; double obt; double eobt; };

enum TimeUpdateMode { NONE, ASYNC, SYNC };

public: //! returns the singleton static ModelIf* instance(); virtual ˜ModelIf();

c Airbus Defence and Space 587 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

//! implement the MRA TimeManager interface double getSimTime() const; //! return the actual simulation time (now) double getWallTime() const; //! return the actual wallclock time (now) double getSysTime() const; //! return the actual system time (now) double getFacTime() const; //! return the actual facility time (now) double getObcTime() const; //! return the actual onboard time (now)

//get TimeSet attributes const TimeSet& getTimeSet() const {return _time;} double getSMT() const {return _time.smt;} double getWCT() const {return _time.wct;} double getSYT() const {return _time.syt;} double getTFT() const {return _time.tft;} double getETFT() const {return _time.etft;} double getOBT() const {return _time.obt;} double getEOBT() const {return _time.eobt;}

//updating of Test Facility Time and Onboard Time void setTftUpdateMode(TimeUpdateMode aMode); bool updateTFT(); void setObtUpdateMode(TimeUpdateMode aMode); bool updateOBT();

virtual bool esimPublish();

protected: //access to the TFT providing interfaces //is to be implemented in inheriting model virtual bool initTFT(double &tft)=0; //return true on success virtual bool readTFT(double &tft)=0; //return true on success virtual bool termTFT(double &tft)=0; //return true on success //access to the OBT providing interfaces //is to be implemented in inheriting model virtual bool initOBT(double &obt)=0; //return true on success virtual bool readOBT(double &obt)=0; //return true on success virtual bool termOBT(double &obt)=0; //return true on success //entrypoints for the model void init(); void step(); void term();

double _deltaSimTime; //!< delta smt, simTime - prevSimTime double _deltaWallTime; //!< deltawct, wallTime - prevWallTime double _simSpeed; //!< deltaSimTime/deltaWallTime double _wallSpeed; //!< deltaWallTime/deltaWallTime double _maxSysCycleTime; //!< if (_sysTime-prevSysTime)>max max=_sysTime-prevSysTime double _minSysCycleTime; //!< if (_sysTime-prevSysTime)

//! singleton must have a protected Timekeeper ModelIf();

588 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

//! singleton is not copyable ModelIf(const ModelIf&);

}; class Model : virtual public ModelIf, public FeModel::Mil1553::SyncIf {

public: //! returns the singleton static ModelIf* instance(); static ModelIf* instance(const char *aSaPath, unsigned aOffset); ˜Model(); bool setObtSa(const char *aSaPath, unsigned aOffset); public: bool esimPublish();

protected: //updating of Test Facility Time and Onboard Time bool initTFT(double &tft); bool readTFT(double &tft); bool termTFT(double &tft); bool initOBT(double &obt); bool readOBT(double &obt); bool termOBT(double &tft);

//implementation of the sync interface void updateSyncInfo(double pCswCycleStamp); void updateSyncInfo(double pCswCycleStamp,unsigned int pCswCycleNr);

protected: //The user can pass a path to the OBT in the mil1553 model on construction //If this is not done the user MUST link himself _scet to the correct place char _saPath[ESIM_MAX_PATH]; unsigned _dwOffset;

//set the pointer to the time distribution on the TEST terminal MilEmSaData *_scet;

//pointer to the mil1553 device for irig-b time access FeModel::Mil1553::DevIf *_timeDev;

//! singleton must have a protected Timekeeper Constructor Model(); Model(const char* aObtPath, unsigned offset);

//! singleton is not copyable Model(const Model&);

};

}

c Airbus Defence and Space 589 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The Timekeeper interface code shows the implementation of the MRA TimeManager interface, which may or may not be used. These calls provide the time at the moment of calling of the function utilizing extrapolation.

29.7.3 Configuration The configuration of the Timekeeper in the present version of EuroSim is limited and provided via the constructor and setter methods of the class:

static ModelIf* instance(const char *aSaPath, unsigned aOffset); static ModelIf* instance(); void setTftUpdateMode(TimeUpdateMode aMode); void setObtUpdateMode(TimeUpdateMode aMode);

The constructor allows passing the location from where the onboard time is to be read. This onboard time is read as a CUC time from the subaddress defined as a dictionary path to a mil1553 model subaddress, as well as an offset which points to the position in this subaddress. This information is only relevant if the obt is actually used in the timekeeper, which is when the mode is either set to SYNC or ASYNC using the setObtUpdateMode. If the instance call without arguments is used, the obt mode should remain NONE and no time will be read. The test facility time follows the same approach. If the mode is either SYNC or ASYNC it will read the tft via the Mil1553 Front-End model interface, if set to NONE no obt will be read at all. Setting the model to SYNC will force the Timekeeper to read the time synchronously using the readTFT() and readOBT() methods with the frequency equal to the scheduling of the step() entrypoint of the Time- keeper. When set to ASYNC it is expected that that simulation developer has some external trigger which leads to a call to the methods updateTFT / updateOBT. If the provided implementation of readTft and readObt are not what is needed, the simulation developer should make a class derived from TimekeeperIf.

29.7.4 Dictionary interface In the dictionary, the TimekeeperIf class publishes the variables that are always of interest to the operator in a generic Timekeeper. The Timekeeper class then adds the variables that are specific to the configura- tion of the subaddress and dataword offset via the constructor and the link to the sub address from where the onboard time is read. The appearance of the Timekeeper class (which thus inludes the publication by the Interface as well as the Timekeeper classes is then shown in Figure 29.12. Note the two configuration variables tftUpdateMode and obtUpdateMode. These represent the users mode selections for tft and obt access. These variables can be set before model initialization to NONE to avoid any hardware access in specific test cases.

29.7.5 Front-end interface Currently no special interfaces are provided, this may increase in future releases.

29.7.6 Device interface In future releases the EuroSim software is expected to be expanded to include a definition and inter- face for time devices. Together with an XML file for configuration of the Timekeeper there should be sufficient interfaces.

590 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 29.12: Timekeeper dictionary interface

29.8 Front-End Model Stub

29.8.1 Introduction The Front-End Model Stub is a configurable test model that can be used to verify the implementation of the real-time simulator using batch test scripting. This allows the simulator developer to provide a verified simulator before the actual onboard computer or emulator thereof comes available. It is important to have such verified simulator prior to the integration with the real onboard computer as when both the simulator and the onboard computer/software can have issues the source of the problem is hard to find, particularly in closed loop control. Additionally onboard computer or emulators thereof may come available late in the project, requiring a minimal delay for integration with the simulator. With the Front-End Stub it becomes possible to verify the simulator independently of the onboard com- puter by running IO scenarios on the interface of the simulator. The development and verification of the realtime simulator then can already start before the product under test is available. The concept is shown in Figure 29.13. The Front-End Stub model can be used from the Simulation Controller but in most cases will be used from batch test scripts, currently EuroSim is supporting perl, python, tcl and java. Using specific el- ements of the Front-End stub requires additional functions to send commands and retreive data, which are installed as part of EuroSim for perl and python and which is used in the example unit test scripts included with the ThermoMRA examples (tcl and java extensions will be added on user request, perl is currently the most used approach). For a specific project the user will configure the Stub with commands that stimulate the Front-End model as well as sequences of these commands configured via an XML file. In combination with the test scripts this provides an easy method of sending mesages and playing protocol streams on the interface of the simulator, and verifying the incoming telemetry. The stub model can be configured to use the Front-End model API (as in a software verification facility) or to use loopback solutions for more precise timing. The latter is currently only supported for the Mil1553 cards, which usually have the ability of an internal loopback. For discrete interfaces it depends highly on the supplier of the discrete Front-End interface whether loopback mode can be supported. The Stub must be scheduled as all models. An init entrypoint is to be scheduled to initialize the stub,

c Airbus Defence and Space 591 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 29.13: Concept of the Front-End Model Stub usage

a step method to provide its execution tick in the Standby and Execution state of the simulation, and a term method to clean up resources. The frequency of the step entrypoint is usually the highest frequency in the system to provide maximum resolution on timing.

29.8.2 Architecture The Stub consists of three components which are visible as three objects underneath the Stub object in the dictionary. Figure 29.14 shows the class architecture of the front-end model stub and Figure 29.15 the resulting object hierarchy in the dictionary.

Figure 29.14: Front-End Model Stub class architecture

The Commander is generally used for unit testing of models in a non realtime stepwise approach. Typ- ically a test script in perl (python, tcl, java upcoming) communicates with the commander running in

592 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 29.15: Front-End Model Stub object hierarchy in dictionary

standby state where simulation is paused to set up conditions. Then a simulation step is made for a specific time to let the configured situation take effect and subsequently back in standby state the Com- mander is used again to check if the state of variables and interfaces matches expectation. Alhough generally interaction with the commander in this kind of testing is during standby state, it is possible to use the Commander as well during Execution state but timing the injection of commands is not very precise from batch scripting. The commander has a variety of mil1553 and discrete generic commands that can be used to stimulate the front-end models. Often a single on the fly constructed command is sufficient, but it is possible to configure multiple and trigger these as a burst of commands. The Sequencer allows the user to define named command lists in an XML configuration file. This component is mostly used in integration testing of models or to broadcast mode codes on the bus. Most of the time it is combined with MDL scripting to enable and disable the sequences or to change the data the sequence is emitting. It runs only in Execution state as its activities rely on simulation time. The sequences consist of a sequence of steps, where each step defines the delta time from the starttime of the sequence and the command that it should execute. The activation of sequences is triggered by the increase of the reqCount attribute of a sequence as visible in the Dictionary. When this is increased, the Sequencer will start checking its scheduling attributes. A sequence can be scheduled to start on a Major or Minor sync or immediate and there is the possibility of making the sequence repeatable and having a countdown to delay its start. It is assumed that the major frame lasts one second, the minor frame or communication frame is then often related to the emission of sycnhronization mode codes and the subframe is related to the frequency at which the step entrypoint of the test stub is scheduled. In the ThermoMra example it is shown that these frequencies are defined in the configuration file of the stub using the line The sequence itself contains a list of commands that can be a Mil1553 transmit or receive command, a Discrete line stimulation that is defined in the same XML file for that equipment, or NOP (no operation). The latter is relevant cause it will keep the sequence active which affects the next iteration. When the command is a MIL or Discrete command, the command is passed to the Executer component, similar as the Commander component does for on the fly created commands. The Executer mimics the embedded computer scheduler. It checks for any commands in its command queues that are to be transmitted and will route them to the Front-End models, either via loopback through the front-end software library and hardware, or direct via the Front-End model API.

29.8.3 Commander Usage The Commander component can be used to configure commands and send these once or repeatedly. The user must fill the configuration and data sections of the mil1553- or discrete command structure in the EuroSim Dictionary and then activate the command by setting the activate variable to 1. Figure 29.16 shows the structure in the dictionary for a mil1553 and a discrete command displayed in a EuroSim MMI tab. (Note that this is the manual approach, but more common is to perform this from test scripts using support functions provided by EuroSim) To activate a command the variable active should be set to 1 to activate the stimulation. Note that as shown in Figure 29.16, the MilCommand has one additional configuration parameter, config.overwriteDataWords.

c Airbus Defence and Space 593 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 29.16: Stub MMI tab

This should be set to 1 to use the data defined in the datawords. If not, the data that is last used is applied again. Special FeStub perl and python extensions provide functions in batch scripting in terms of sending data and receiving data in a synchronous execution, as well as setting variables and checking variables that make the usage of the commander component of the stub considerably easier. For a discrete commands the user must set the type of the line (Section 29.5.1) and the variables that belong to that type. Not all the variables are thus used that are displayed, but only the ones that relate to the stimulation. Thus for an Analog this is value, for a bilevel it is level etc. When a sim type command is issued there is no need to specify data, rather the command is executed and the data retreived from the simulator is stored in the lastDiscrReply structure variable in the dictionary. Convenience functions are available in the Festub batch script extension that operate synchronously and return the output stored in the lastDiscrReply. This is reliable for the nominal usage (in Standby state), but must be used carefully when issueing commands in the Executing state, particularly when sequences are active. For a mil1553 command the approach is similar to the discrete command approach, but different variables are used. The Mil1553 specific variables allow the user to define the bus the mil1553 command is to be send on, the mil1553 command word of the message and up to 32 datawords. The fields are decimal notation, but with the aid of the calculator in programming view and linux or similar calculator usage on windows the computation from bits to mil1553 commandword is easily made. The batch script Festub extension provides also for Mil1553 convenience functions that allow the sending and receiving of data over mil subaddresses in a synchronous manner in Standby state. This is a convenient way to setup a condition on the milbus, execute the simulator for some time and then retreive data in standby state again to check the transmit subaddresses. When the command word is a transmit command, the remote terminal sends mil1553 data messages back to the bus controller. These messages are queued in the Executer component and elaborated in section 29.8.5. Please beware that for the wordcount, the mil standard encodes 32 as 0, and if the overwritedatawords field is not 1 the data in the dw fields are not used. For both discrete and mil1553 commands the user has the option to set general configuration parameters that allow to define a number of cycles delay before activation (config.countdown) and the number of repetitions that the stimulation should be repeated (config.everyNthCycle). The cycle time depends on the taskrate with which the Stub step method is scheduled. Note that when these control attributes are used, the execution becomes simulation time dependent and hence such command will not execute

594 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

in Standby State. For this reason these control attributes are not often used as they defeat the easy usage of a step wise simulation script for testing. Another common configuration parameter is config.activateNext, which, if set to 1, will instruct the Commander to automatically enable the next command and execute that too. Althought the tab shows only the first command, it is actually an array of commands, thus this allows the user to setup a sequence of commands through the commander and activate all in one go. This is another advanced control at- tribute, which is not often used because when executing in standby the siulation time does not progress and hence there is no need to active commands in a burst.

The usage from the MMI tab may be usefull for a developer to get his first model version working. The normal approach however is to use the commander from test scripts. See Section 29.8.6.

29.8.4 Sequencer usage The sequencer component is more useful for iterative stimulation of the mil1553 and discrete front-end interface. A good example is sending mil1553 synchronization mode codes. The sequencer executes only in Executing state as it is dependent on simulation time. It is often used in integration and system testing in conjunction with MDL scripting. For the sequencer the user must first configure the StubConfig file. This file contains a section per equipment that defines which instances exist of the equipment, which commands can be sent to the equipment with specific data, and the sequences which define the activation of commands over time. Following is a snippet from a configuration file:

The instances allow the user to define the commands and sequences once, but in the EuroSim dictionary the expansion is visible for all three instances, where the parameters in the instance line are applied to the empty attributes in the commands and the sequences. Figure 29.17 shows a fragment in the dictionary: For each equipment the commands and sequences are displayed that are defined in the stub configuration file. The single variable of interest is the requestCount, This variable has to be given a different value (normally increased by 1). Most other variables are filled from the XML file and should not be changed. An exception could be the datawords in a Mil command, here the user could set a different set of values

c Airbus Defence and Space 595 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 29.17: FeModel Stub Sequencer in the dictionary

that would be applied in the next time the sequence is activated. Figure 29.18 shows the dictionary variables in the commands (mil command unfolded only).

Figure 29.18: FeModel Stub Sequencer steps in the dictionary

The sequence activation can be delayed using a Countdown parameter in a sequence and subsequently additionally be delayed to the upcoming Minor or the Major frame boundary using the Sync parameter of the sequencer. When the sequence becomes active it will mark its activation time and then the Time- FromStart in a step definition is the time distance from that activation time. Setting the repeat argument to On will ensure that the sequence starts again after the finish of a running sequence has completed. For the Major and Minor frame the next start will then be at the next minor or major frame boundary. The Countdown is only applied once. To send multiple messages to the same remote terminal for deep ad- dressing, the user can have multiple steps with the same TimeForStart, which then will all be performed in one minor cycle, in line with the array order. The commmand types in the definition can be:

where the Mil- Cmd can be either a transmit (Tx=”T”) or receive (Tx=”R”) command. The Data is only relevant for a receive command, but the argument must be present as well for the transmit command, al- though that data will be overwritten by the data from the remote terminal. The Data attribute can

596 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

be either a single number, or a sequence of numbers in the format ”1,2,3,4” with maximum length 32. An empty Bus or Rt will be replaced by the Bus and Rt from the Instance definition. • is a variation on the MilCmd to distribute a time over the mil1553 bus according to a specific pro- tocol. Currently only the ECSS 50 13C is supported as protocol which writes 46 in the first word of the identified subaddress followed by a CCSDS CUC time in the next 3 words. Additional protocols can be added by the EuroSim team if required by customers. The Source of the time distribution can be simtime, walltime or systime. The Offset is added to the actual time value prior to transmission. • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the specific line in that group. The value is the analog value to be set in the Fe side for that line in the Discrete Front-End model. • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the specific line in that group. The lvl is the bilevel value to be set in the Fe side for that line in the Discrete Front-End model. • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the specific line in that group. The Duration, Amplitude and cumulative count are the values to be set into the Discrete Fe model for the specified line. • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the spe- cific line in that group. The Duration, Amplitude, cumulative count and cumulative ontime are the values to be set into the Discrete Fe model for the specified line. • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the specific line in that group. The Cnt is the number of pulses in the last frame that are detected and past to the specific line in the Discrete FeModel • The Grp is either empty or a group known to the Discrete Front-End Model. The line is the specific line in that group. The Size is the number of bytes to be transmitted and the byte array is the array of bytes provided to the serial line.

The specific meaning and unit of the arguments is defined with the front-end model section in this model. The values in the FE side of the Discrete and Mil1553 Front-End model are the same as set by the Stub. In the XML configuration file snippet the commands and sequences where prefixed with CMD and SEQ, this is up to the user, but in practice makes it easier to discern the commands from sequences in the Simulation Controller.

29.8.5 Executer usage The executer is the component of the FeModel test stub that handles the commands injected by the Commander and the Sequencer. It is not of direct interest to the user to initiate commands, but it does provide relevant variables. The following configuration variables can be used to adjust the mode that the executer uses to interface with the discrete and mil1553 front-end model:

discreteConnect This variable determines the connection to the discrete front-end model milConnect This variable determines the connection to the mil1553 front-end model xferDelay The Xfer gap between mil messages for usage with a simulated mil1553 bus. In the case of a smiulated Mil1553 bus the time of the messages sent in one step call would all be the same. It therefore adds the xferDelay to the timestamp of the message to simulate the effect that the messages are sent sequential and thus have a minor time delay between each transmissionn. c Airbus Defence and Space 597 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

The discreteConnect and milConnect variables can have the following values:

• Unconfigured (0), in this case the variable will be set during initialization based on the model mode of the stub. If set to Simulated, the connection will be direct. If set to HIL it will be set to Scoe. See value description below.

• Direct (1), selects communication via the front-end model API,

• Loopback (2), selects communication via the loopback mode. This is currently only sup- ported by the mil1553 front-end model.

• Scoe (3), selects communication via the scoe. This is currently only supported by the mil1553 front-end model.

Additionally the Executer stores data that it receives from the Mil1553 Front-End interface in response on transmit commands. This can be accessed as normal dictionary variables from a test script to verify that the command is properly executed.

lastDiscrReply The data of the last reply by a remote terminal lastMilReply The data of the last reply by a remote terminal lastMilTcReply[0..31] The data of the last mil1553 message in reply on the last transmit command to a remote terminal lastMilTmReply[0..31] The data of the last mil1553 message in reply on the last receive command to a remote terminal milRepliesByIndex[0..99] This can keep up to 100 replies in a subframe. The sub- frame is determined by the schedule frequency of the stub step entrypoint, which subdivides the mil1553 minor frame in a number of slots (see MRA). The index is set to zero at the beginning of the step entrypoint of the Stub and for each reply on a milcmd is incremented. If multiple com- mands with the same TimeFromStart are sent, up to 100 replies are stored in this array. If there is a difference that is equal or larger then the subframe the replies are over- written milRepliesByIndexSwMask This variable can be used in combination with the mil- RepliesByIndexSwFilter to limit the replies that are stored in the milRepliesByIndexQueue. When given a value, that value is used in a bitwise AND with the statusword of each Mil1553 Transmit message on the Mil1553 bus. If the result of that bitwsie AND matches the milRepliesByIn- dexSwFilter value the message is stores in the milReplies- ByIndexQueue. The most usefull function is to filter out data replies to a specific remote terminal. milRepliesByIndexSwFilter See description with milRepliesByIndex

598 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

mMilRepliesByIndexNrofOfCommands This variable shows the number of commands that are in the queue that match the filter criteria defined by mil- RepliesByIndexSwMask and milRepliesByIndexSwFilter. The queue is filled from zero every cycle, where cycle de- pends on the frequency that the test stub is executed on. Thus every cycle the data in the queue can be rewritten and the milRepliesByIndex queue thus can only contain multi- ple commands when they arrived in one cycle. However, this NrofOfCommands variable is only reset when indeed a new command has arrived in a next cycle. This NrofOf- Commands thus indicates how many commands are still in the queue.

29.8.6 Test Scripting The commander and sequencer can be operated manually as described in Section 29.8.3, but are normally used from test scripts in unit and integration testing on the simulator. The approach is to bring the simulator in a specific condition, then run the simulator for a certain amount of time (after which it freezes), and inspect the results. The test scripts can be written in any of the batch scripting languages perl, python, tcl or java. (see Scripting volume). In the ThermoMra example a setup is provided using perl, which can be found in the ThermoMra/Simulator/Rts subdirectory the folder src of the EuroSim installation directory. Two test scripts and a package that is generic for these scripts are provided in the ThermoMra exaple that illustrate the usage for the unit tests of the heater and sensor of the ThermoMra example. The setup assumes a naming convention for test filenames, where test scripts start with the unit name in small characters followed by a freely chosen part that describes the test scope and ending on the extension .pl. These example script can be used as the basis for developing more elaborate unit test scripts and even integration test scripts within the scope of a simulator development. The resulting set of test scripts can be added to a nightly build process as a regression test setup using for instance the free available tool jenkins. The Lib directory of the EuroSim installation provides a perl package that make the perl unit and inte- gration test script development easier called FeStub which provides convenience functions related to:

• Stub Commands - functions to create and activate commands and sequences in the EuroSim FeStub model

• Simulation Utilities - Simulation Control related functions

• Mil1553 Support utilities - MIL word value check functions, type conversion, and endian conversion functions

The FeStub perl module provides a number of functions that can be used in the development of perl unit and integration test scripts. The most important ones are described here: FeStub::init FeStub::dict(STUB_PATH, MIL_1553_PATH, DISCRETE_PATH); Initialise the paths in the dictionary to be used by the FeStub package. The Stub model is introduced in Section 29.8, The Front-End Models for Discrete Lines and for MIL-1553 Bus(ses) are introduced in Section 29.5.5, and Section 29.6.5 respectively. FeStub::setOutputDir FeStub::setOutputDir(RESULTS_DIR); Initializes defaults to be used by the FeStub package. The RESULTS_DIR determines where the output of the test script execution is logged.

c Airbus Defence and Space 599 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

FeStub::sendMilMcCommand FeStub::sendMilMcCommand(bus,channel,remoteTerminal,modeCode,wordValue); Convenience function to send a mode code command, potentially with dataword. This is the most easy interface for sending mode codes built on top of the sendMilCommand. It executes synchronous, thus it will not complete until the mode code is sent. It is intended for use in Standby state, but wil work in execution state to. The modeCode command is automatically decoded to apply the correct TX/RX bit and the dataword parameter. Note that in this interface always the first milcommand (arrayIndex 0) is used to keep the API simple, similarly there are no control attributes. If control of these parameters is relevant the sendMilCommand or setMilCommand must be used. Parameter description can be found in the explanation of the setMilCommand function below. FeStub::sendMilTxCommand FeStub::sendMilTxCommand(bus,channel,remoteTerminal,subAddress,size); Convenience function to synchronously send a transmit type mil command, wait for its execution and then return the results as an array of word values. This works for normal and plusbuffer subaddress. The size argument can thus be up to 32 for a normal subAddress or much higher to catch the result of the deep addressing. This is the most easy interface to send Mil1553 transmit commands. This functions requires that this is the only command executed because it is assumed that this function can wait and poll for the MilReply in the executer and store the data in the wordValues. This is normally the case in standby state where the commander’s cyclic commands and the sequencer are not active. Note that this command also lacks the countdown, cycle repetition and triggering of next command which are available with the Set commands as these are all powerful yet rarely needed options. Arguments are described with setMilCommand. FeStub::sendMilRxCommand FeStub::sendMilRxCommand(bus,channel,remoteTerminal,subAddress, wordValues) ; Convenience function to send a receive type mil command to transfer data to a remote terminal sub address. The function works for both normal and plus buffers. the wordvalues array can thus be longer than 32 words in case of the latter. This is the most easy interface as it executes synchronous, the function waits until the stub has executed the command and returns if the command was succesfully transmitted. It requires that this is the only command executed because it is assumed that this function can wait and poll for the MilReply in the executer and store the data in the wordValues. This is normally the case in standby state where the commander’s cyclic commands and the sequencer are not active. Note that this command also lacks the countdown, cycle repetition and triggering of next command which are available with the Set commands as these are all powerful yet rarely needed options. Arguments are described with setMilCommand. FeStub::sendMilCommand FeStub::sendMilCommand(arrayIndex, countdown, everyNthCycle, activateNext, bus, channel, remoteTerminal, transmitValue, subAddress, wordCount, wordValues); Convenience function to set and activate a MIL command in one call. Parameter description can be found in the explanation of the setMilCommand function below. The execution is synchronous, the function returns a list which contains the statusword, size and datawords retreived from the lastMilReply in the executer. Note that this function can use any of the milcommand fiels of the commander component of the stub, but does not have the control attributes. If the latter are relevant the setMilCommand and activateMilCommand functions should be used. FeStub::setMilCommand FeStub::setMilCommand(arrayIndex, countdown, everyNthCycle, activateNext, bus, channel, remoteTerminal, transmitValue, subAddress, wordCount, wordValues);

600 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Prepares a MIL command for activation. This is the most elaborare interface which can adjust every attribute of the mil command. It forms the backbonce for the other commands which provide a much more tailored and conveient interface. Arguments:

• arrayIndex - Index in the set of MIL commands.

• countdown - Number of cycles before activation (count of stub activations taking stub scheduling frequency into account).

• everyNthCycle - Number of repetitions.

• activateNext - After executing the arrayIndex command, also execute the arrayIndex+1 com- mand: to activate the next command, set to 1; to stop set to 0. This is repeated until a command is found where activateNext equals 0.

• bus - The MIL bus.

• channel - Main (0) or Redundant (1) MIL Channel.

• remoteTerminal - The Remote terminal.

• transmitValue - Transmit (TC=0) or Receive (TM=1) command.

• subAddress - The Sub Address in the Remote Terminal.

• wordCount - Number of words in wordValues. If 0 is specified, this is interpretered to represent 32.

• wordValues - Array of word values. FeStub::activateMilCommandNoWait FeStub::activateMilCommand(arrayIndex); Activates a prepared MIL command as fire and forget, it does not wait and therefore always returns 1. Argument:

• arrayIndex - Index in the set of MIL commands. FeStub::activateMilCommand FeStub::activateMilCommand(arrayIndex); Activates a prepared MIL command, waits until it has been send and then returns the if execution was succesful. Argument:

• arrayIndex - Index in the set of MIL commands. FeStub::activateMilSequence FeStub::activateMilSequence(sequenceName); Activates a sequence of MIL command(s) defined for the stub. Argument:

• sequenceName - Name of the sequence as definded in the StubConfig XML file as described in Section 29.8.4. FeStub::sendAnalog FeStub::sendAnalogCommand( group, line, value); Convenience function to send a value to an Analog acquisition line. The command waits for execution by the stub executer before returning the success of the activation. The function is build on top of the sendDiscreteCommand function. The function returns one if the activation is succesful, zero otherwise.

c Airbus Defence and Space 601 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• group, line - see setDiscreteCommand

• value - Floating point value to be sent into the discrete line FeStub::recvAnalog FeStub::recvAnalogCommand( group, line); Convenience function to retreive data from an Analog line in the discrete front end model. It is build on top of the sendDiscreteCommand function. The function waits for command completion and returns the data (the floating point analog value) as array. In case of a failure an ampty array is returned.

• group, line - see setDiscreteCommand FeStub::sendBilevel FeStub::sendBilevel(group, line, level); Convenience function to send a value to a Bilevel acquisition line. The command waits for execution by the stub executer before returning the success of the activation. The function is build on top of the sendDiscreteCommand function. This stimulates the experiation of a detected pulse of specific amplitude and duration. The function returns one if the activation is succesful, zero otherwise.

• group, line - see setDiscreteCommand

• level - boolean value to be sent into the discrete line FeStub::recvBilevel FeStub::recvBilevel(group, line); Convenience function to retreive data from a Bilevel line in the discrete front end model. It is build on top of the sendDiscreteCommand function. The function waits for command completion and returns the data (the boolean bilevel) as array. In case of a failure an ampty array is returned.

• group, line - see setDiscreteCommand FeStub::sendCmdPulse FeStub::sendCmdPulse(group, line, duration, accCount); Convenience function to send data to a Command Pulse acquisition line. The command waits for execu- tion by the stub executer before returning the success of the activation. The function is build on top of the sendDiscreteCommand function. This stimulates the expiration of a detected pulse of specific amplitude and duration detected by the hardware as a result of crossing the amplitude that is preprogrammed in the pulse detection front-end configuration files. The function returns one if the activation is succesful, zero otherwise.

• group, line - see setDiscreteCommand

• duration - Length of the pulse after completion

• accCount - Cummulative count to identify that this is a new pulse FeStub::recvCmdPulse FeStub::recvCmdPulse(group, line); Convenience function to retreive data from a Command Pulse output line in the discrete front end model. It is build on top of the sendDiscreteCommand function. The function waits for command completion and returns the data (the duration and accumulated count) as array. In case of a failure an ampty array is returned.

• group, line - see setDiscreteCommand

602 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

FeStub::sendPowerPulse FeStub::sendPowerPulse( group, line, duration, amplitude, accCount); Convenience function to send data to a Power Pulse acquisition line. The function is build on top of the sendDiscreteCommand function. The command waits for execution by the stub executer before returning the success of the activation. The functions stimulates the expiration of a detected pulse of specific amplitude and duration. The function returns one if the activation is succesful, zero otherwise.

• group, line - see setDiscreteCommand

• duration - Length of the pulse after completion

• amplitude - Hight of the pulse

• accCount - Cummulative count to identify that this is a new pulse FeStub::recvPowerPulse FeStub::recvPowerPulse(group, line); Convenience function to retreive data from a Power Pulse output line in the discrete front end model. The function waits for command completion and returns the data (the duration, amplitude and accumulated count) as array. It is build on top of the sendDiscreteCommand function.

• group, line - see setDiscreteCommand FeStub::sendOntimePulse FeStub::sendOntimePulse(group, line, accOntime); Convenience function to synchronously send an ontime to a pulse line to the simulator. The function is build on top of the sendDiscreteCommand function. The ontime pulse information contains an accu- mulated ontime which contains the ontime of all completed pulses and a currently in progress but not completed pulse.

• group, line - see setDiscreteCommand

• accOntime - Length of the pulse after completion FeStub::sendFreqPulse FeStub::sendFreqPulse( group, line, accCount); Convenience function to send data to tacho sensing input. The command executes synchronously, waiting for the stub to complete the sending of the data to the FreqPulseAcq input. The function is build on top of the sendDiscreteCommand function. The frequency pulse line is usefull when you need to pass the count of something to the simulator. The arguments are limited to the commonly used ones.

• group, line - see setDiscreteCommand

• accCount - Length of the pulse after completion FeStub::recvFreqPulse FeStub::sendFreqPulse(group, line); Convenience function to retreive data from a Tacho output line in the discrete front end model. The function waits for command completion and returns the data (the period) as array. It is build on top of the sendDiscreteCommand function.

• group, line - see setDiscreteCommand FeStub::sendSerial FeStub::sendSerial(group, line, byteValues);

c Airbus Defence and Space 603 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Convenience function to send a list of bytes to the discrete front end model and wait for the executer to complete transmitting the data. It is build on top of the sendDiscreteCommand function. Returns 1 on successful activation of the command.

• group, line - see setDiscreteCommand

• byteValues - bytes to be send FeStub::recvSerial FeStub::recvSerial(group, line); Convenience function to retreive data from a SerialSim line in the discrete front end model. The function waits for command completion and returns the data as array. It is build on top of the sendDiscreteCom- mand function.

• group, line - see setDiscreteCommand FeStub::sendDiscreteCommand FeStub::sendDiscreteCommand(arrayIndex, level, duration, amplitude, accCount, wordCount, wordValues); Sets and activates a Discrete command in one command and waits for the command to be sent by the executer to the front-end mode. The function operates synchronously, but only returns 1 on successful activation, 0 otherwise. The data retreived by sim commands is stored in the lastDiscrReply variable in the dictionary (published by the Executer). It is recommended to use the more specific functions for receiving and sending listed above which query the lastDiscrReply after it has been sent and retrieve the data as a function result. The Arguments are described with setDiscreteCommand below. Note that the control attributes are not present in the API of this function because it is intended for usage during the standby state, though the function will work in executing state. Use setDiscreteCommand and activateDiscreteCommand if such control is needed. FeStub::setDiscreteCommand FeStub::setDiscreteCommand(arrayIndex, countdown, everyNthCycle, activateNext, group, line, type, value, level, duration, amplitude, accCount, wordCount, wordValues); Prepares a Discrete Line command without executing it. Arguments:

• arrayIndex - Identifier to select which handle in the Commander is used

• countdown - Number of cycles before activation (count of stub activations taking stub scheduling frequency into account).

• everyNthCycle - Number of repetitions.

• activateNext - After executing the arrayIndex command, also execute the arrayIndex+1 com- mand: to activate the next command, set to 1; to stop set to 0. This is repeated until a command is found where activateNext equals 0.

• transmitValue - Transmit (TC=0) or Receive (TM=1) command.

• group - Name of the group as definded in the Discrete Lines XML file as described in Sec- tion 29.5.3.

• line - Name of the line as definded in the Discrete Lines XML file as described in Section 29.5.3.

• type - Numerical value of the line type as definded in the Discrete Lines XML file as described in Section 29.5.3. Note that the following values represent the line types described:

– 0 - AnalogAcq

604 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

– 2 - BilevelAcq – 4 - PulseCmdAcq – 5 - PulsePowerAcq – 6 - PulseFreqAcq – 10 - SerialAcq – 1 - AnalogSim – 3 - BilevelSim – 7 - PulseCmdSim – 8 - PulsePowerSim – 9 - PulseFreqSim – 11 - SerialSim

Additional details on the line types can be found in Section 29.5.7. That section also describes which of the following parameters are relevant for each of these lines: value, level, duration, amplitude, accCount, wordCount (size), wordValues (data). FeStub::activateDiscreteCommand FeStub::activateDiscreteCommand(arrayIndex); Activates a Discrete command. Argument:

• arrayIndex - Index in the set of Discrete commands. FeStub::begin FeStub::begin(testName, logLevel); Begins a test run ad creates a default test results file. FeStub::end FeStub::end(); Ends a test replaces the default test results file with the actual test results summary. FeStub::waitHandleEvent FeStub::waitHandleEvent(eventName, timeout); Waits for the event to occur unless the timeout passes first. FeStub::simInit FeStub::simInit(simulatorFile, realTimeMode); Create a simulator session for the provided simulator file and ininitializes the simulator in the provided real time mode (1=real time). If the real time setting is 0 (non real time), the simulation speed is set to 5. FeStub::simModelInit FeStub::simInit(realTimeMode);

Initializes the simulator by raising the EGSE_SIM_INIT-event, followed by the raising the MODEL_INIT and waits for the simulator to enter Standby-state. If the real time setting is 0 (non real time), the simulation speed is set to as fast as possible. FeStub::simCreateSession FeStub::simCreateSession(simulatorFile, realTimeMode); Create a simulator session for the provided simulator file and ininitializes the simulator in the provided real time mode (1=real time).

c Airbus Defence and Space 605 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

FeStub::simAddInitCond FeStub::simAddInitCond(initialConditionFile); Adds an initial condition file to the simulator session. FeStub::simInitExistingSession FeStub::simInitExistingSession);

Initializes the simulator by and waits for the simulator to enter Initializing-state. FeStub::simSpeed FeStub::simSpeed(speed); Change the simulation speed. FeStub::simWait FeStub::simWait(seconds); Wait for a number of seconds to pass. FeStub::getLogBuf FeStub::getLogBuf(); Returns the current value of the log buffer. FeStub::setLogLevel FeStub::setLogLevel(level); Changes the log level. With increasing value, more output is logged. FeStub::simTime FeStub::simTime(); Returns the simulation time. FeStub::simStepSec FeStub::simStepSec(seconds);

Actiates (Executing-state) the simulator for the provided number of seconds and returns the simulator to Standby-state. FeStub::simStop FeStub::simStop(); Stops the simulator. FeStub::simExit FeStub::simExit(); Aborts the simulator. FeStub::simGetVar FeStub::simSetVar(name);

Returns the value of name from the dictinary. FeStub::simSetVar FeStub::simSetVar(name, value);

Updates the value of name in the dictinary.

606 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

FeStub::simSetVars FeStub::simSetVars(data);

Process the data in pairs of (name, value) and updates the value of name in the dictinary. FeStub::simCheckVars FeStub::simCheckVars(title, decimals, data);

Process the data in pairs of (name, value) and checks whether name in the dictinary equals value within an accuracy defined in the number of decimals. A message is printed showing pass or failure (with details). FeStub::simCheckVarsNotEqual FeStub::simCheckVarsNotEqual(title, decimals, data);

Process the data in pairs of (name, value) and checks whether name in the dictinary does NOT equals value within an accuracy defined in the number of decimals. A message is printed showing pass or failure (with details). FeStub::simCheckVarsGreaterThen FeStub::simCheckVarsGreaterThen(title, data);

Process the data in pairs of (name, value) and checks whether name in the dictinary is greater then value. A message is printed showing pass or failure (with details). FeStub::simCheckVarsSmallerThen FeStub::simCheckVarsSmallerThen(title, data);

Process the data in pairs of (name, value) and checks whether name in the dictinary is less then value. A message is printed showing pass or failure (with details). FeStub::simCheckString FeStub::simCheckString(title, name, value);

Checks whether name in the dictinary is equals value. A message is printed showing pass or failure (with details). FeStubMilUtils::checkMilWords FeStubMilUtils::checkMilWords(title, expected, data);

Processes the data in pairs of (offset, value) and checks whether a BYTE value at the offset in the MIL data equals value in the array of expected values. A message is printed showing pass or failure (with details). FeStubMilUtils::checkMilDWords FeStubMilUtils::checkMilWords(title, expected, data);

Processes the data in pairs of (offset, value) and checks whether two byte (MIL WORD) value at the offset in the MIL data equals value in the array of expected values. A message is printed showing pass or failure (with details).

c Airbus Defence and Space 607 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

608 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 30

C++ Client Interface reference

30.1 Introduction

This chapter provides details on the batch interface for the C++ programming language. Various C++ classes have been created that provide an interface to existing EuroSim libraries. This means that a batch application is no more than a normal C++ client application using EuroSim classes. The provided C++ classes form an object oriented interface to monitor and control EuroSim. The C++ interface is the foundation for the Batch scripting languages where SWIG is used to generate wrapper code for the bindings to the selected scripting languages. The behavior will thus be identical, but being a C++ library it will be more usefull for external programs written in a compiled languaged. The batch interface for C++ consists of various classes. Each class (or group of classes) is described in a separate chapter. The most important classes are the Session and EventHandler classes. To compile and link a client application that uses the C++ Batch interface, just include the esimClient.h header file in your code and link your application to the esimClient++ library. The following line will then build your application under the assumption that you have EuroSim or at least the EuroSim client package installed $(CXX) client.cpp -o client -I$(EFOROOT)/include -L$(EFOROOT)/$(ARCH) - lesClient++

In the above line $(ARCH) should be lib for 32-bit and lib64 for 64-bit operating systems (Windows currently is always 32-bit). $(CXX) should be replaced with the appropriate compiler command, e.g g++ for Linux users applying gcc. The dependencies in the esimClient.h are minimalised, assuring that it only depends on the C++ stan- dard header files and not any other EuroSim header files. This allows a relatively easy compilation without an installed EuroSim using just copies of the relevant EuroSim files: $(CXX) client.cpp -o client -I. -L. \ libesClient++.$(EXT) libesClient.$(EXT) libes.$(EXT)

Where In the above line $(EXT) should be replaced by .so.7.1for Linux users and .dll for Windows users. Note that if your client and target are on different platforms, potentially even different operating systems, you may need to compensate for the difference in the path to the simulator on both systems, please see the Session class method set_remote_path for more information on this specific issue.

30.2 Session class

This is the central class used to run simulations. It supports the complete network protocol required to control the running simulator executable. There is a function for each command you can send to the simulator. In order to handle messages sent from the simulator to the application you can install an

c Airbus Defence and Space 609 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

instance of an EventHandler class (see Section 30.3). You can also wait synchronously for any message. The messages and responses are documented in detail in Chapter 31. The idea behind this class for batch control is that it is a replacement for the simulation controller. It can fully automate anything you can do with the simulation controller. At the same time this provides an easy to use interface for any program that wants to interface with the running simulator. To start a simulator all you need to do is: using namespace eurosim; Session *s = new Session("some.sim"); // load simulation definition s->init(); // start simulator

The constructor of the Session class uses the information in the simulation definition file to start the simulator. As you can see you pass similar information to these calls as needed by the simulation controller. In the simulation controller you open a simulation definition file and then you can click on the Init button which launches the simulator. The simulation controller automatically connects to the simulator, just like the init method does. This function also sets up a number of standard event handlers for incoming events (messages) from the simulator. The information is stored in the session class. The user can at any moment print the contents of this structure by calling the print_session_parameters method. To install a new event handler you have to create a derived class from the EventHandler class. The con- structor of the class also installs the event handler such that the event handler methods are automatically called on each incoming event. To remove the event handlers call the remove method of the event handler class. See Section 30.3 for detailed information on each event handler class method. It is also possible to synchronously wait for an event you expect. In this case you call the wait_event method with the name of the event (same name as the method in the event handler class) and a time-out (in milliseconds). To synchronously wait for some time to pass, you can call wait_event with an empty string as the event name.

30.2.1 Monitoring variables

In order to monitor variables you must call the method monitor_add with the variable you want to monitor. The variable parameter is in the form of a valid EuroSim data dictionary path. This method will add the variable to the list of variables monitored in EuroSim. The value of each variable will be updated with the asynchronous action manager frequency, which defaults to 5 Hz if they change. If there is no change, no update is sent. The values of the variables are stored in the Session class. To get the value of a variable use the following expression: s->monitor_value(var_path). The value is always returned as a string. To stop monitoring a variable you must call the function monitor_remove with the variable you want to stop monitoring. If you only want to get the value of a variable once, it is better to call the function get_value. This function retrieves the value of the variable immediately from the simulator, but only once. The value of the variable is returned as a string.

30.2.2 Modifying variables

If you want to change the value of a variable in the simulator you can simply call set_value with the name and value (as a string) of the variable. The value will be set as soon as possible in the simulator. Calling set_value also works on an array variables or struct in its entirety and will set these values atomically.

610 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

To set different variables atomically in one API call, use set_values. The argument is an instance of class VariableSet in the eurosim namespace. Variable value pairs can be added to this VariableSet instance using its add function, which takes the variable path and value string as arguments. The benefit of this approach is a much quicker execution time as the client will send the value pairs in one message to the simulator and wait for confirmation. Using set_value the client will send one message and wait for confirmation, which then must be repeated for each variable.

30.2.3 Method reference 30.2.3.1 Constructors

Session() Session(std::string sim) Session(std::string sim, std::string hostname)

Description Creates a EuroSim simulation session by loading the given simulation definition file sim. The simulation run will be started on the host with the given hostname or on the current host if not specified. Parameters sim the simulation definition file name hostname the name of the host on which to run the simulator

30.2.3.2 Methods std::string cwd() Description Returns the path name of the current working directory of the simulator. The value is set by the event handler for event maCurrentWorkingDir. Return value Path name of the current working directory std::string dict() Description Returns the path name of the EuroSim data dictionary of the simulator. The value is set by the event handler for event maCurrentDict. Return value Path name of the EuroSim data dictionary std::string outputdir() Description Returns the path name of the directory where the output files of the simulator are stored (journal file, recorder files, etc.) The value is set by the event handler for event maCurrentResultDir. Return value Path name of the output directory std::string state()

c Airbus Defence and Space 611 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Returns the simulator state. Can be: unconfigured, initialising, stand-by, executing, exiting. The value is set by the event handler for the following events: rtUnconfigured, rtInitialising, rtStandby, rtExecuting and rtExiting. Return value Simulator state

void set remote path() Description On a single system the path to the .sim file is the same for the client that launches the simulator an for the EuroSim daemon that starts the simulator on request from the client. If the client is on a different computer, this can still be accomplished, for instance by using the NFS solution on unix based systems. This assures that there is only one directory which is accessible via the same path on both computers. If this however is not feasible, for instance because the target operating system differs from the client, the set_remote_path method can be used to patch the target path in the Session object. This solution needs on the client a copy of the .sim file as well as beside it the copy of the path .$(ARCH)/.dict from the target system. The client will read these two files when the Session object is created with the .sim file and the target hostname as argument. The set_remote_path method then will patch the absolute directory path to the local .sim file in the Session object, with the one provided as argument. When the init method of the Session object is thereafter called the corrected path is provided to the EuroSim daemon on the target system. Note that when the client is on a windows system and the target has a Linux operating system, the client system must have the file path .Linux/.dict because the Session object derives the operating system specifier from the operating system of the target. Return value None

std::string journal() Description Returns the path name of the journal file. Return value Path name of the journal file

std::string schedule() Description Returns the path name of the schedule file. Return value Path name of the schedule file

std::string exports() Description Returns the path name of the exports file. Return value Path name of the exports file

std::string alias(std::string alias) std::string alias()

612 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Set or get the alias file name. Parameters alias Override the alias file specified in the SIM file. If alias was not specified, then the alias file remains unchanged. Return value Path name of the alias file. If the simulation is running, then the value is set by the event handler for event maCurrentAliasFile. std::string model() Description Returns the path name of the model file. Return value Path name of the model file double recording bandwidth() Description Returns the recorder bandwidth in bytes/second. The value is set by the event handler for event maRecordingBandwidth. Return value Recorder bandwidth in bytes/second double stimulator bandwidth() Description Returns the stimulator bandwidth in bytes/second. The value is set by the event handler for event maStimulatorBandwidth. Return value Stimulator bandwidth in bytes/second double speed() Description Returns the clock acceleration factor achieved by the simulator. Values larger than 1 indicate faster than real-time. Values smaller than 1 indicate slower than real-time. The value is set by the event handler for event scSpeed. Return value Acceleration factor double sim time() Description Returns the simulation time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Simulation time in seconds double wallclock time()

c Airbus Defence and Space 613 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Returns the wallclock time (as seen by the running simulator). The value is set by the event handler on reception of events from the simulator, thus is updated with at least the frequency of the event dtHeartBeat. Return value Wallclock time in seconds

double wallclock boundary() Description Returns the wallclock boundary time to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Wallclock time boundary in seconds

double simtime boundary() Description Returns the simulation time boundary to be used for timed state transitions. If you add an integer number of times the main cycle time to this value it will produce a valid state transition boundary time. Return value Simulation time boundary in seconds

double main cycle() Description Returns the main cycle time of the current schedule. It can be used to calculate valid boundary times for timed state transitions. Return value Main cycle in seconds.

bool recording() Description Returns the flag indicating that recording is enabled or not. True means enabled, false means disabled. The value is set by the event handler for event maRecording. Return value Recording is enabled

bool write access() Description Returns the flag to indicate whether this client is allowed to change variable values in the sim- ulator. The value is set by the event handler for event maDenyWriteAccess. Return value Client is allowed to change variables

int time mode()

614 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Returns the time mode. It can be relative or absolute (UTC). Relative is 0 and absolute is 1. The value is set by the event handler for event maCurrentTimeMode. Return value Time mode bool realtime(bool realtime) bool realtime() Description Set or get the realtime mode. Parameters realtime If the realtime mode is not specified, then the realtime mode is not set. If realtime is 0, then realtime mode is disabled, otherwise it is enabled. The new setting will not effect an already running simulation. Return value The realtime mode, true for realtime, false for non-realtime. If a simulation is running, then the value as was set by the event handler for event scGoRT is reported. Non-realtime is the default. bool auto init(bool auto init) bool auto init() Description Set or get the auto initialization flag. Parameters auto init If the auto initialization flag is not specified, then the auto initialization flag is not set. If auto init is 0, then the simulator will not go automatically to initializing state on startup, otherwise it will go automatically to initializing (this is the default). The new setting will not effect an already running simulation. Return value The auto init flag, true if the state transition to initializing state is performed automatically, false if it isn’t. Automatic state transition to initializing is the default. int prefcon(int prefcon) int prefcon() Description Set or get the preferred connection. Parameters prefcon The preferred connection. This can be used in a situation where you need to reconnect to an already running simulator. To start new simulation runs, this number is not used. If prefcon was not specified, then the preferred connection is not set. Return value Return the connection number of the current simulation session. int startup timeout(int timeout) int startup timeout()

c Airbus Defence and Space 615 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Set or get the startup timeout. The startup timeout default is 5 seconds. If starting up a simulator takes longer than this you must change that default to a higher value. If timeout was not specified, then the startup timeout is not set. Parameters timeout The startup timeout. Return value Return the startup timeout in seconds of the current simulation session.

std::string clientname(std::string clientname) std::string clientname() Description Set or get the name under which this session is known to the simulator. Parameters clientname The client name of the current simulation session. The default is “esimbatch”. If clientname was not specified, then the client name is not changed. Return value Return the client name of the current simulation session.

vector string initconds(vector string initconds) std::string initconds() Description Set or get the initial condition files. Parameters initconds Override the initial condition files specified in the SIM file. If initconds was not specified, then the initial condition files remain unchanged. Return value Initial condition files. If the simulation is running, then the value is set by the event handler for event maCurrentInitconds.

vector string calibrations(vector string calibrations) std::string calibrations() Description Set or get the calibration files. Parameters calibrations Override the calibration files specified in the SIM file. If calibrations was not specified, then the calibration files remain unchanged. Return value Calibration files. If the simulation is running, then the value is set by the event handler for event maCurrentCalibrations.

std::string workdir(std::string workdir) std::string workdir()

616 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Set or get the work directory. Parameters workdir Use this directory as the work or project directory instead of the current directory. Return value The work directory. std::string user defined outputdir(std::string outputdir) std::string user defined outputdir() Description Set or get the user defined output directory. Parameters outputdir Use this output directory instead of the default date/time directory. If not set, then the user defined output directory is not changed. Return value The user defined output directory. std::string hostname(std::string hostname) std::string hostname() Description Set or get the EuroSim server hostname. Parameters hostname Use this EuroSim server. If not set, then the hostname is not changed. Return value The EuroSim server hostname. std::string sim(std::string sim, std::string hostname) std::string sim(std::string sim) std::string sim() Description Set or get the simulation definition file. This simulation definition file is used to start the simulator. Information derived from the sim- ulation definition file is used to provide sensible defaults for all parameters. Parameters sim The simulation definition file. If not set, then the simulation definition is not changed. hostname The EuroSim server hostname. If not set, then the local host is used instead. Return value The filename of the simulation definition file. int init() Description Start a new simulation run. Return value 1 on success, 0 on failure.

c Airbus Defence and Space 617 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

int join channel(std::string channel) Description Join a channel of a simulation session. By default each session connects to all channels. The following channels are available: mdlAndActions, data-monitor, rt-control, sched-control. To join all channels use channel “all”. Parameters channel The channel to join. Return value 1 on success, 0 on failure.

int leave channel(std::string channel) Description Leave a channel of a simulation channel. Parameters channel The channel that you want to leave. Return value 1 on success, 0 on failure.

bool wait event(std::string event, int timeout ms) Description Wait for an incoming event This function is used to wait synchronously for the given event. The timeout is used to limit the amount of time to wait for this event. Parameters event The name of the event to wait for. If the event name is empty this function can be used to read all pending events while waiting for the given amount of time. timeout ms The timeout in milliseconds. A value of -1 means that this this function will wait until the event arrives for an unlimited amount of time. A value of 0 means that the function will return immediately even if the event has not arrived yet. Return value true if the event had arrived, false if it has not.

int monitor add(std::string var) Description Monitor a variable. The value of the variable is updated with the asynchronous action manager, which defaults to 5 Hz. Parameters var The variable from the data dictionary that you want to monitor. Return value 1 on success, 0 on failure.

std::string monitor value(std::string var)

618 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Retrieve the value of a monitored variable Parameters var The name of the monitored variable. Return value the value of the variable int monitor remove(std::string var) Description Remove the monitor of a variable. Parameters var The variable from the data dictionary that should be removed from the monitor list. Return value 1 on success, 0 on failure. long create session list(std::string hostname) long create session list() Description Create a list of all sessions and return the size of that list. Parameters hostname If set, then report the sessions running on that host. Otherwise report all sessions running on the subnet. Return value the number of sessions.

SessionInfo session list(long idx) Description Return the session info for the session with the given index. Parameters idx The index in the session list. Return value The session info. int esim connect() Description Connect to a running simulation; a new journal file is opened. Return value 1 on success, 0 on failure. void esim disconnect() Description Disconnect from the simulation session. The simulator will continue to run in the background. void print monitored vars()

c Airbus Defence and Space 619 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Print a list of currently monitored variables and their current values. All variables in active monitors send values to the batch tool. A table with all variables is kept with their current values.

void print session parameters() Description Print a complete overview of all available parameters.

void print event list() Description Print a list of all events (messages) and parameters used in the communication between the test controller and the simulator.

std::string script action(std::string name, std::string script, std::string condition) std::string script action(std::string name, std::string script) Description Create an MDL script text. Parameters name The action name. script The action script. condition The optional condition. Return value The fully composed action script.

std::string recorder action(std::string name, double freq, vector string vars) Description Create a recorder script. Parameters name The action name. freq The recorder frequency. vars A list of all variables to be recorded. Return value The fully composed recorder script.

std::string stimulus action(std::string name, std::string option, std::string filename, double freq, vector string vars) Description Create a stimulus script. Parameters name The action name. freq The stimulus frequency. option An option string (“soft”, “hard” or “cyclic”).

620 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

filename The stimulus filename. vars A list of all variables to serve as stimulus. Return value The fully composed stimulus script. long event list size() Description Return the size of the list of events present in the schedule. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Return value The size of the list of events.

EventInfo event list(long idx) Description Return the event info of the event with the given index. The value is set by the event handler for the following events: scEventListStart, scEventInfo, scEventListEnd. Parameters idx The index in the event list (the first element has index 0). Return value Event info. long where list size() Description Return the size of the current breakpoint list. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Return value The size of the list.

WhereInfo where list(long idx) Description Return the current breakpoint with the given index. The value is set by the event handlers for the following events: scWhereListStart, scWhereEntry, scWhereListEnd. It is cleared by the following events: scStepTsk and scContinue. Parameters idx The index in the current breakpoint list. Return value The breakpoint location. long task list size() Description Return the size of the task list. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable.

c Airbus Defence and Space 621 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value The size of the task list.

TaskInfo task list(long idx) Description Return the task info for the task with the given index. The value is set by the event handler for events scTaskListStart, scTaskStart, scTaskEntry, scTaskEnd and scTaskListend. Each task consists of a number of entry points and a flag called disable. The disable flag is set by the event handler of scTaskDisable. Parameters idx The index in the task list. Return value The task info

long find task index(std::string taskname) Description Convert task name to index number. Parameters taskname The name of the task. Return value The index in the task list.

vector string mdl list() Description Return a list of all loaded MDL files. MDL files are loaded at start-up when a .sim file is loaded or during run-time when extra MDL files are loaded. Extra files can be loaded by the event handler for event maNewMission or by manually adding MDL files with new scenario. Return value The list of MDL files.

vector string action list(std::string mdl) Description Return a list with the names of all the actions. Parameters mdl The name of the MDL file. Return value The list of action names.

vector string monitored vars() Description Return a list of all monitored variables. Return value The list of variables.

long event type list size()

622 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Return the size of the event messages table. Return value The number of event messages.

EventTypeInfo event type list(long idx) Description Return the event type info of event message idx. Parameters idx The index in the event messages table. Return value The event type info. std::string sev to string(int sev) Description Return a string respresentation of a message severity Parameters sev Message severity Return value std::string representation of severity int go(int sec, int nsec) int go(int sec) int go() Description Change the simulator state from stand-by to executing. Equivalent to the Go button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is specified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure. int stop(int sec, int nsec) int stop(int sec) int stop() Description Stop the simulation run. Equivalent to the Stop button of the test controller. The variant speci- fying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds)

c Airbus Defence and Space 623 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

int pause(int sec, int nsec) int pause(int sec) int pause() Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

int freeze(int sec, int nsec) int freeze(int sec) int freeze() Description Change the simulator state from executing to stand-by. Equivalent to the Pause button of the test controller. The variant specifying the time is used for timed state transitions. The wallclock time is secified as sec seconds and nsec nanoseconds. Parameters sec Wallclock time (seconds) nsec Wallclock time (nanoseconds) Return value 1 on success, 0 on failure.

int freeze at simtime(int sec, int nsec) int freeze at simtime(int sec) Description Change the simulator state from executing to stand-by on the specified simulation time. The simulation time is secified as sec seconds and nsec nanoseconds. Parameters sec Simulation time (seconds) nsec Simulation time (nanoseconds) Return value 1 on success, 0 on failure.

int step() Description Perform one main scheduler cycle. Equivalent to the Step button of the test controller.

624 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure. int abort() Description Abort the current simulation run. Equivalent to the Abort button of the test controller. Return value 1 on success, 0 on failure. int health() Description Request a health check of the running simulator. Prints health information to the test controller. Return value 1 on success, 0 on failure. int reset sim() Description Restart the current simulation with the current settings. Equivalent to the Reset button of the test controller. Return value 1 on success, 0 on failure. int new scenario(std::string scen) Description Create a new scenario in the simulator. This new scenario is only a container for new actions. It is not a file on disk. It is a pure in core representation. Parameters scen The scenario name. Return value 1 on success, 0 on failure. int open scenario(std::string scen) Description Open a new scenario file in the simulator with file name scen. The file must be on disk and readable. Parameters scen Scenario file name. Return value 1 on success, 0 on failure. int close scenario(std::string scen) Description Close a currently opened scenario with name scen in the simulator. Parameters scen Scenario file name.

c Airbus Defence and Space 625 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

int new action(std::string scen, std::string action text) Description Add a new action in the scenario file with name scen. action text is the complete action text. There are a few utility functions to generate those actions. Parameters scen The scenario file name. action text The action text. Return value 1 on success, 0 on failure.

int delete action(std::string scen, std::string action) Description Delete an action from scenario scen with name action. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

int action execute(std::string scen, std::string action) Description Trigger the execution of the action with name action in scenario with name scen. This is equivalent to triggering an action manually on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

int action activate(std::string scen, std::string action) Description Make action with name action in scenario with name scen active in the running simulator. The action must already be defined in the scenario. This is equivalent to activating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure.

int action deactivate(std::string scen, std::string action)

626 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Deactivate action with name action in scenario with name scen in the running simulator. This is equivalent to deactivating an action on the scenario canvas of the Simulation Controller. Parameters scen The scenario file name. action The action name. Return value 1 on success, 0 on failure. int snapshot(std::string filename, std::string comment) int snapshot(std::string filename) int snapshot() Description Make a snapshot of the current state of the variables in the data dictionary. The comment string is optional. If you omit the filename, a filename is chosen of the form snapshot simtime.snap. The snapshot is saved in the output directory, unless the filename is absolute. This is equivalent to the “Take Snaphot...” menu option in the “Control” menu of the test controller. Parameters filename Path name of the snapshot file. comment Comment string Return value 1 on success, 0 on failure. int mark(std::string comment) int mark() Description Make a mark in the journal file. The comment string is optional. This is equivalent to the “Mark Journal” and “Comment Journal Mark” menu options in the “Insert” menu of the Simulation Controller. Parameters comment Comment string Return value 1 on success, 0 on failure. int sim message(std::string msg) Description Send a message to the simulator for distribution to all clients. This is useful if your client application is not the only client of the simulator. The message is broadcasted to all clients. Parameters msg Message string Return value 1 on success, 0 on failure. int suspend recording()

c Airbus Defence and Space 627 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Suspend recording in the simulator. This is equivalent to unchecking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure.

int resume recording() Description Resume recording in the simulator. This is equivalent to checking the “Enable Recordings” menu item of the “Control” menu of the Simulation Controller. Return value 1 on success, 0 on failure.

int recording switch() Description Switch all recording files of a simulation run. All currently open recorder files are closed and new recorder files are created. Recording will continue in the new recorder files. Return value 1 on success, 0 on failure.

int reload(std::string snapfile, std::string hard) int reload(std::string snapfile) Description Load initial condition file or snapshot file with file name snapfile into the running simulator. Parameter hard is by default “off”. This means that the simulation time stored in the snapshot file is ignored. If hard is set to “on”, the simulation time is set to the value specified in the snapshot file. Parameters snapfile Path name of snapshot file. hard “on” or “off”. Return value 1 on success, 0 on failure.

int set value(std::string var, std::string value) Description Set the value of a variable. Parameters var The data dictionary path name of variable you want to change. value The new value as string. To set an array variable write the value as a comma seperated list between curly brackets. For example: ::s set_value("/Thrusters/force", "{1,2, 2, 3, 4, 5, 6, -2, 2}") The same applies for a struct with respect to fields. Nesting is possible too, a field of a struct that is an array would be a comma seperated list in curly brackets embedded in a comma seperated list in curly brackets as in: ::s set_value "/Thrusters/example" "{1,2, {1,5}, 3, 4,}"

628 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value 1 on success, 0 on failure. int set values(eurosim::VariableSet varset) Description Set the value for a list of variables in one command. The class VariableSet can hold a list of variable-value pairs. The advantage is a much faster handling for larger sets of variables. Parameters varset The instance that holds the list of variable-value pairs. eurosim::VariableSet varset; varset.add("/Thrusters/force", "2"); varset.add("/Thrusters/torque", "3’); s set_values(varset); Return value 1 on success, 0 on failure. std::string get value(std::string var) Description Get the value of a variable. Parameters var The data dictionary path name of the variable Return value The value, empty on failure int cpuload set peak(int cpu, int peak time) Description Configure the CPU load monitor peak time in msecs. Parameters cpu CPU number peak time Peak time in seconds. Return value 1 on success, 0 on failure. int set breakpoint(std::string taskname, int entrynr, bool enable) Description Set a breakpoint on entry nr entrynr in task taskname in the scheduler. If parameter enable is set to true the breakpoint is enabled. To disable it again set the parameter to false. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure. int set trace(std::string taskname, int entrynr, bool enable)

c Airbus Defence and Space 629 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Enable/disable tracing of entry points. Entry points are defined by specifying the number of the entry point entrynr (numbering starts at 0) and the name of the task taskname. To enable a trace set enable to true, to disable it set it to false. Tracing an entry point means that messages are printed to the journal window. Parameters taskname Name of the task. entrynr Entry point number enable true to enable, false to disable Return value 1 on success, 0 on failure.

int where() Description Request the current position when the scheduler has stopped on a break point. The reply to the message is automatically stored and can be retrieved by using where list. Normally the position is sent to the client whenever the scheduler hits a breakpoint. So there is rarely any need to request the position manually if you store the position on the client side (as is done in this tool.) Return value 1 on success, 0 on failure.

int step task() Description Perform one step (=one entry point) in the scheduler debugger. Return value 1 on success, 0 on failure.

int cont() Description Continue executing upto the next breakpoint in the scheduler debugger. Return value 1 on success, 0 on failure.

int task disable(std::string taskname) Description Disable task with name taskname in the current schedule of the simulator. Parameters taskname Name of the task. Return value 1 on success, 0 on failure.

int task enable(std::string taskname) Description Enable task with name taskname in the current schedule of the simulator.

630 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters taskname Name of the task. Return value 1 on success, 0 on failure. int clear breaks() Description Remove all breakpoints in the current schedule of the simulator. Return value 1 on success, 0 on failure. int clear traces() Description Remove all traces in the current schedule of the simulator. Return value 1 on success, 0 on failure. int set simtime(int sec, int nsec) int set simtime(int sec) Description Set the simulation time to sec seconds and nsec nanoseconds. This can only be done in stand-by state. Parameters sec Simulation time in seconds. nsec Simulation time in nanoseconds. Return value 1 on success, 0 on failure. int enable realtime() Description Switch to real-time mode. This can only be done when the simulator has started off in real-time mode, and has switched to non-real-time mode. Return value 1 on success, 0 on failure. int disable realtime() Description Switch to non-real-time mode. Return value 1 on success, 0 on failure. int list tasks() Description Request a list of all tasks in the current schedule of the simulator. The list is also sent automat- ically upon joining the “sched-control” channel.

c Airbus Defence and Space 631 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure.

int list events() Description Request a list of all events in the schedule of the simulator in all states. The list is automatically sent to the client when subscribing to the “sched-control” channel at start-up. Return value 1 on success, 0 on failure.

int raise event(std::string eventname, SWIGTYPE p void data, int size) int raise event(std::string eventname) Description Raise event with name eventname in the scheduler. An event is defined by the input connector on the scheduler canvas. The event is handled as fast as possible. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

int raise event at(std::string eventname, int sec, int nsec, SWIGTYPE p void data, int size) int raise event at(std::string eventname, int sec, int nsec) int raise event at(std::string eventname, int sec) Description Raise event with name eventname in the schedler at a specified wallclock time. The wallclock time is specified as sec seconds and nsec nanoseconds. Event data with a given size can option- ally be passed together with the event. Parameters eventname Name of the event sec Wallclock time in seconds. nsec Wallclock time in nanoseconds. data Data size Size of data in bytes. Return value 1 on success, 0 on failure.

int raise event at simtime(std::string eventname, int sec, int nsec, SWIGTYPE p void data, int size) int raise event at simtime(std::string eventname, int sec, int nsec) int raise event at simtime(std::string eventname, int sec)

632 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Raise event with name eventname in the schedler at a specified simulation time. The simula- tion time is specified as sec seconds and nsec nanoseconds. Event data with a given size can optionally be passed together with the event. Parameters eventname Name of the event sec Simulation time (seconds) nsec Simulation time (nanoseconds) data Data size Size of data in bytes. Return value 1 on success, 0 on failure. int set speed(double speed) Description Set the acceleration/deceleration of the scheduler of the simulator. Values smaller than 1 will cause a proportional deceleration of the scheduler clock. Values larger than 1 will cause a proportional acceleration of the scheduler clock. Magical value -1 means that the scheduler will run in an optimized as-fast-as-possible mode. Parameters speed acceleration factor Return value 1 on success, 0 on failure. int add MDL(std::string mdlname) Description Load (another) new MDL file in the session. Parameters mdlname Path name of the MDL file. Return value 1 on success, 0 on failure. int sync send(int token) Description Send sync token to simulator Parameters token synchronization token id Return value 1 on success, 0 on failure int sync recv(int token) Description Wait for sync token from simulator Parameters token synchronization token id

c Airbus Defence and Space 633 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Return value 1 on success, 0 on failure

int kill(int signal) int kill() Description Kill the simulator with signal signal. By default the simulator is killed with SIGTERM. Parameters signal Signal to send to the simulator Return value 1 on success, 0 on failure

30.3 EventHandler class

The EventHandler class is used to handle events coming from the simulator. The user must derive from this class and implement the methods for the events that must be handled. When a messsage from the simulator is received, first the built-in message handling is performed fol- lowed by the user defined message handlers. The message handlers are installed by instantiating the handler. The message handlers are removed upon instance destruction. To define a user defined message handler all you need to do is (using inline for ease of reading in this document): class ExampleEventHandler:: public EventHandler {

public: // constructor ExampleEventHandler(Session s) : EventHandler(s) {};

// handler for maMessage events void maMessage(int simtime_sec, int simtime_nsec, int runtime_sec, int runtime_nsec, int sev, std::string procname, std::string msg) { std::cout << procname << " + " << msg); };

}

30.3.1 Method reference 30.3.1.1 Constructors

public EventHandler(Session s) Description Construct a new EventHandler and install the handler. Parameters s The simulator session

634 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

30.3.1.2 Methods

Session session() Description Return the session for this event handler. Return value The simulator session.

30.3.1.3 Event Handler Methods In order to create a user defined event handler, one or more methods must be implemented. void maNewMission(std::string mission) Description A new mission (MDL) is created. Parameters mission The name of the mission. void maOpenMission(std::string mission) Description A mission (MDL) file is opened. Parameters mission The filename of the mission file. void maCloseMission(std::string mission) Description A mission (MDL) file is closed. Parameters mission The filename of the mission file. void maSimDef(std::string simdef) Description Inform that client which simulation definition file is currently loaded. Parameters simdef The filename of the simulation definition file. Return value

void maCurrentDict(std::string dict) Description Inform the client which data dictionary file is currently loaded. Parameters dict The filename of the data dictionary file. Return value

c Airbus Defence and Space 635 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

void maCurrentWorkingDir(std::string cwd) Description Inform the client what the current working directory of the simulator is. Parameters cwd The path name of the current working directory.

void maCurrentResultDir(std::string result dir) Description Inform the client what the result directory is. The result directory contains all the journal files, recorder files, snapshots and timings file. Parameters result dir The path name of the result directory.

void maCurrentAliasFile(std::string filename) Description Inform the client what the alias file is. The alias file contains the data dictionary aliases. Parameters filename The path name of the alias file.

void maNewAction(std::string mission, std::string actiontext) Description Inform the client that a new action has been created. Parameters mission The name of the mission. actiontext The new action.

void maDeleteAction(std::string mission, std::string actionname) Description Inform the client that an action has been deleted. Parameters mission The name of the mission. actionname The name of the action.

void maActionExecute(std::string mission, std::string actionname) Description Inform the client that an action is being executed. Parameters mission The name of the mission. actionname The name of the action.

void maActionExecuteStop(std::string mission, std::string actionname) Description Inform the client that an action is no longer being executed.

636 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Parameters mission The name of the mission. actionname The name of the action. void maActionExecuting(std::string mission, std::string actionname) Description Inform a newly connected client that the action is currently executing. Parameters mission The name of the mission. actionname The name of the action. void maActionActivate(std::string mission, std::string actionname) Description Inform the client that an action has been activated. I.e. is allowed to execute. Parameters mission The name of the mission. actionname The name of the action. void maActionDeActivate(std::string mission, std::string actionname) Description Inform the client that an action has been deactivated. I.e. is no longer allowed to execute. Parameters mission The name of the mission. actionname The name of the action. void maExecuteCommand(std::string name, std::string command, int action mgr nr) Description Inform the client that a one shot action has been executed. Parameters name The name of the action. command The commands of the action. action mgr nr The number of the action manager that has executed the action. void maSnapshot(std::string snapshot, std::string comment) Description Handle maSnapshot event. This event is sent after a snapshot of the current simulator state has been made. Parameters snapshot Path name of the snapshot file. comment Comment describing the snapshot. void maMark(std::string message, int marknumber) Description Inform the client that a mark has been made in the journal file.

c Airbus Defence and Space 637 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters message The descriptive message of the mark. marknumber The number of the mark.

void maMessage(int simtime sec, int simtime nsec, int runtime sec, int runtime nsec, int sev, std::string process, std::string msg) Description Inform the client that a message has been generated in the simulator. This message is also automatically logged in the journal file by the simulator. Parameters simtime sec Simulation time stamp (seconds part) simtime nsec Simulation time stamp (nanoseconds part) runtime sec Wallclock time stamp (seconds part) runtime nsec Wallclock time stamp (nanoseconds part) sev Severity of the message. The name of the severity can be retrieved by using the sev_to_string() method of the Session class. process Name of the simulator thread from where the message was generated. msg The message text.

void maRecording(std::string on off) Description Inform the client that recording has been globally enabled/disabled. Parameters on off If the string is equal to “on”, recording is enabled. If it is “off” it is disabled.

void maRecordingBandwidth(double bandwidth) Description Report the bandwidth used to record data to disk. Parameters bandwidth Number of bytes per seconds written to disk.

void maStimulatorBandwidth(double bandwidth) Description Report the bandwidth used to read data from disk for stimulation. Parameters bandwidth Number of bytes per second read from disk.

void maRecorderFileClosed(std::string filename) Description Inform the client that a recorder file has been closed and can be used for further processing. Parameters filename The file name of the recorder file.

void maDenyWriteAccess(bool denied)

638 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Description Inform the client that the write access to variables is denied. This is the case if the client has the role of observer. Parameters denied Flag to indicate denial of write access to the simulator variables. void maCurrentInitconds(std::string simdef, std::string initconds) Description Inform the client of the current list of initial conditions as used for the initialization of the simulator. Parameters simdef The name of the simulation definition file. initconds The list of initial condition files (space separated). void maCurrentCalibrations(std::string simdef, std::string calibrations) Description Inform the client of the current list of calibration definition files as used by the simulator. Parameters simdef The name of the simulation definition file. calibrations The list of calibration files (space separated). void maCurrentTimeMode(int time mode) Description Inform the client of the current time mode. The time mode can be relative time or absolute time (UTC mode). Parameters time mode The time mode, 0 is relative time mode, 1 is absolute time mode (UTC mode). void maNewSeverity(int sev, std::string sev name) Description Inform the client about a new user-defined message severity. This message is automatically han- dled. The severity identifier can be mapped to its symbolic name using the sev_to_string() method of the Session class. Parameters sev The severity numerical identifier. sev name The symbolic name of the severity. void rtUnconfigured() Description Inform the client that the state of the simulator is unconfigured. This state means that the simulator is either still starting up, or is in its final clean up phase. This is a transient state. When starting up, the next state will be Initialising. When cleaning up the last event will be evShutdown. void rtInitialising()

c Airbus Defence and Space 639 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Inform the client that the state of the simulator is initialising. Depending on the schedule definition, this state will automatically be followed by the standby state. Otherwise you have to manually change the state to standby using the eventStandby() method of the Session() class.

void rtStandby() Description Inform the client that the state of the simulator is standby.

void rtExecuting() Description Inform the client that the state of the simulator is executing.

void rtExiting() Description Inform the client that the state of the simulator is exiting. This is a transient state. The next state will be the unconfigured state.

void rtTimeToNextState(int sec, int nsec) Description Report the time to the next state transition. This is useful when the major cycle is quite long (more than a couple of seconds). This can be the case if the schedule definition contains a clock with a very low frequency or when the lowest common denominator of the clocks results in a long major cycle. Parameters sec Time to next state (seconds part) nsec Time to next state (nanoseconds part)

void rtMainCycle(int sec, int nsec) Description Report the length of the main cycle of the schedule. Parameters sec Main cycle (seconds part) nsec Main cycle (nanoseconds part)

void scSetBrk(std::string taskname, int entrynr, int enable) Description Inform the client about the enabling/disabling of a break point on a specific entry point in a task in the schedule. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). enable Whether the break point is enabled (1) or disabled (0).

640 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

void scStepTsk() Description Inform the client that a step to the next task has been performed in debugging mode. void scContinue() Description Inform the client that the execution is now continued after being stopped on a break point in debugging mode. void scGoRT(bool enable) Description Inform the client that the real-time mode has changed. Parameters enable Real-time mode is enabled (true) or disabled (false). void scTaskDisable(std::string taskname, bool disable) Description Inform the client that a task has been disabled. This means that the task is no longer executed. Parameters taskname The name of the task. disable The task is disabled (true), or enabled again (false). void scSetTrc(std::string taskname, int entrynr, bool enable) Description Inform the client that a trace has been set on an entry point in a task. Parameters taskname The name of the task. entrynr The number of the entry point in the task (counting starts at 0). enable The trace is enabled (true), or disabled (false). void scSpeed(double speed) Description Report the speed of the scheduler clock. This is only relevant in non-real-time mode when going slower or faster than real time. Parameters speed Speed factor. 1 means real-time, less than 1 means slower than real-time, more than 1 means faster than real-time. E.g. 2 means two times faster than real-time. void scTaskListStart() Description Start the description of the list of tasks. void scTaskStart(std::string taskname, bool enabled)

c Airbus Defence and Space 641 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Start the description of a task. This is followed by a number of scTaskEntry events, one for each entry in the order of execution in the task. Parameters taskname The name of the task enabled The task is enabled (true), or disabled (false).

void scTaskEntry(std::string entryname, bool breakpoint, bool trace) Description Report information of an entry point in a task. Parameters entryname The name of the entry point. breakpoint The entry point has a break point set (true) or not set (false). trace The entry point is traced (true) or not (false).

void scTaskEnd() Description Report the end of the task information.

void scTaskListEnd() Description Report the end of the list of tasks.

void scEventListStart() Description Report the start of the list of schedule events.

void scEventInfo(std::string eventname, int state, bool is standard) Description Report all information about a specific schedule event. Parameters eventname The name of the event. state The state in which it is present. is standard Whether or not it is a built-in (standard) event (true), or a user defined event (false).

void scEventListEnd() Description Report the end of the list of events.

void scWhereListStart() Description Report the start of the list of places where the scheduler has stopped execution when reaching a break point. As there are possibly more than 1 executers executing tasks, there can be multiple places where the execution has stopped.

642 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

void scWhereEntry(std::string taskname, int entrynr) Description Report a location where the execution has stopped. Parameters taskname The name of the task. entrynr The number of the entry point (counting starts at 0). void scWhereListEnd() Description End of the list of locations where the execution has stopped. void scEntrypointSetEnabled(std::string entrypointname, bool enabled) Description Report the enabling or disabling of the execution of an entry point. The execution of the entry point is disabled for all tasks and also when executing the entry point from MDL scripts. Parameters entrypointname The name of the entry point. enabled Whether the entry point is enabled for execution (true), or disabled (false). void dtLogValueUpdate(std::string var, std::string value) Description Report an updated value for a logged variable. Parameters var The name of the variable. value The value of the variable. void dtHeartBeat() Description This event is sent at the speed of the non realtime action manager component, which is 5 Hz by default and indicates that the simulator is still alive. It is also the last event sent after a series of dtLogValueUpdate events. void dtCpuLoad(int cpu, double average, double peak) Description Report the load of a CPU. Parameters cpu CPU number average Average load over a main cycle. peak Peak load over a minor cycle. void evLinkData(std::string link id)

c Airbus Defence and Space 643 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Event that is used internally to transmit (TM/TC) packets. The actual data of the packet is not passed to this callback function. It is stored internally and can be retrieved using the read() method of the TmTcLink class. Parameters link id The symbolic name of the link.

void evExtNewView(std::string view id, std::string export id) Description Event that is used to confirm the creation of an external view by the simulator. Parameters view id The symbolic name of the view. export id The symbolic name of the exported view as defined in the exports file.

void evExtSetData(std::string view id) Description Event that is used internally to update External Simulator Access views. The actual data of the event is not passed to this callback function. It is decoded and stored in the view variables and can be retrieved with the get() method of the ExtSimVar* classes. Parameters view id The symbolic name of the view.

void evShutdown(int error code, std::string error string) Description Event that is received when the connection with the simulator is lost. Parameters error code The value of errno at the time the connection was terminated. This value is zero when the connection was terminated in a normal way. error string The description of the error code.

void evEventDisconnect() Description Event that is received when the connection with the simulator is closed. This is normally done using the method esim_disconnect().

30.4 eurosim class

This class contains a couple of utility methods that are not linked to a session.

30.4.1 Method reference

static vector string host list() Description Return the list of EuroSim hosts. Return value The list of hosts.

644 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

static int session kill by name(std::string simname, int signal, std::string hostname) static int session kill by name(std::string simname, int signal) static int session kill by name(std::string simname) Description Kill a simulation session by name. Parameters simname The name of the session. This is normally the basename of the executable. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, other- wise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified name could not be found. static int session kill by pid(int pid, int signal, std::string hostname) static int session kill by pid(int pid, int signal) static int session kill by pid(int pid) Description Kill a simulation session by pid. Parameters pid The process id of the session. signal The signal to send to the session (default = SIGTERM) hostname The name of the host where the session runs (default = localhost) Return value -1 if creating the connection with the EuroSim daemon on the host failed, 0 on success, oth- erwise the result is the value of errno of the failed kill system call or EPERM if you do not have the right permissions to kill the simulator or ESRCH if the simulator with the specified pid could not be found. int open log() Description Allows the client to log to a file. After opening the log file everything that is sent to stdout and to stderr is also logged to the spedified file. Return value 0 if succeeded. int close log() Description Closes the log file created by open_log. Return value 0 if succeeded.

c Airbus Defence and Space 645 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

30.5 EventInfo class

The EventInfo data is return by the event_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler event.

30.5.1 Method reference

std::string name() Description Get the name of the event. Return value The name of the event

int state() Description Get the number of the state where this event is defined. Return value The number of the state.

std::string state name() Description Get the name of the state where this event is defined. Return value The name of the state.

bool is standard() Description Whether the event is a standard event or a user defined event. Return value true if it is a standard event, false if it is a user defined event.

30.6 WhereInfo class

The WhereInfo data is return by the where_list method of the Session class. The methods allow you to retrieve the individual attributes of a scheduler break point location.

30.6.1 Method reference

std::string name() Description Get the name of the task where the scheduler is currently stopped. Return value The task name.

int entrynr() Description Get the entry point number of the current break point within the task. Return value The entry point number. Counting starts at 0.

646 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

30.7 EntryInfo class

The EntryInfo data is return by the entry_list method of the TaskInfo class. The methods allow you to retrieve the individual attributes of an entry point in a task.

30.7.1 Method reference std::string name() Description Get the name of the entry point. Return value The name of the entry point. bool breakpoint() Description Get the break point status of the entry point. Return value True if a break point is set, false if not. bool trace() Description Get the trace status of the entry point. Return value True if a trace is set, false if not.

30.8 TaskInfo class

The TaskInfo data is return by the task_list method of the Session class. The methods allow you to retrieve the individual attributes of a task.

30.8.1 Method reference std::string name() Description Get the name of the task. Return value The name of the task. bool disabled() Description Get the disabled state of the task. Return value True if the task is disabled, false if it is enabled. long entry list size()

c Airbus Defence and Space 647 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Get the number of entry points of the task. Return value The number of entry points.

EntryInfo entry list(long idx) Description Get the entry point information of the entry point with the given index. Parameters idx The entry point index (counting starts at 0). Return value The entry point information.

30.9 EventTypeInfo class

The EventTypeInfo data is return by the event_type_list method of the Session class. The methods allow you to retrieve the individual attributes of a client/server message (called event internally).

30.9.1 Method reference

std::string name() Description Get the name of the message. Return value The name of the message.

std::string args() Description Get the argument types of the message. This is a character coded string with one character for each argument type. Return value The argument types.

std::string argdescr() Description Get a description of the arguments of the message. Return value The description of the arguments.

int id() Description Get the numerical identifier of the message. Return value The numerical identifier.

648 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

30.10 SessionInfo class

The SessionInfo data is return by the session_list method of the Session class. The methods allow you to retrieve the individual attributes of a simulation session.

30.10.1 Method reference std::string sim hostname() Description Get the host name running the simulation session. Return value The host name. std::string sim() Description Get the simulation definition file. Return value The file name of the simulation definition file. std::string workdir() Description Get the working directory. Return value The path name of the working directory. std::string simulator() Description Get the simulator executable. Return value The path name of the executable. std::string schedule() Description Get the simulator schedule. Return value The path name of the schedule file. vector string scenarios() Description Get the list of scenario (MDL) files. Return value The list with path names of the MDL files. std::string dict()

c Airbus Defence and Space 649 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Description Get the data dictionary file. Return value The path name of the data dictionary file.

std::string model() Description Get the model file. Return value The path name of the model file.

std::string recorderdir() Description Get the recorder directory. Return value The path name of the recorder directory.

vector string initconds() Description Get the list of initial condition files. Return value The list of path names of the initial condition files.

vector string calibrations() Description Get the list of calibration files. Return value The list of path names of the calibration files.

std::string exports() Description Get the exports file. Return value The path name of the exports file.

std::string alias() Description Get the alias file. Return value The path name of the alias file.

std::string timestamp() Description Get the time stamp.

650 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The time stamp. int prefcon() Description Get the connection number. Each session has a connection number that can be used to connect a client to that session. Return value The connection number. int uid() Description Get the UNIX user id of the user who started the simulator. Return value The user id. int gid() Description Get the UNIX group id of the user who started the simulator. Return value The group id. int pid() Description Get the UNIX process id of the simulation session. Return value The process id. bool realtime() Description Get the real-time state of the simulation session. Return value True if the simulator was started in real-time mode, false if it was started in non-real-time mode.

30.11 TmTcLink class

The TmTcLink class is used to create a packet link with a model in the simulator. The packet link can be used to send arbitrary packets (binary or not) to a simulator model and receive packets from a simulator model. Multiple packet links can be created. See Chapter 33 for detailed information on how to use the link.

30.11.1 Constructors public TmTcLink(std::string id, std::string mode) Description Open one end of a TmTc link. Parameters id The symbolic name of the TmTc link. mode Mode is “r”, “w” or “rw”, similar to the modes of the fopen() function in the standard C library.

c Airbus Defence and Space 651 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

30.11.2 Method reference

int connect(Session s) Description Connect the link to the other end in a running simulator. Parameters s The session of the running simulator. Return value -1 on failure, 0 on success.

int write(std::string data) Description Write a packet to the link. Parameters data The data (binary string). Return value The number of bytes sent or -1 on failure.

std::string read() Description Read data from the link. Return value The data read as a binary string.

30.12 InitCond class

This class is used for the manipulation of initial condition files. This allows the user to create a new initial condition file or modify an existing file. Individual values can be set or modified. It is also possible to merge two initial condition files.

30.12.1 Constructors

public InitCond(std::string filename, std::string dictfile) Description Create a new set of initial conditions from an existing file. Parameters filename The initial condition file. dictfile The path of the data dictionary file.

30.12.2 Method reference

bool add(std::string filename) Description Merge an existing initial condition file with the current initial condition data. Parameters filename The path of the to-be-merged initial condition file.

652 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value true on success, false on failure. bool write(std::string filename, bool binary) Description Write the initial condition data to a file. Parameters filename The path of the new initial condition file. binary If true, write a binary file, otherwise write the data in human readable (ASCII) format. Return value true on success, false on failure. double simtime() Description Return the simulation time of the initial condition file. Return value The simulation time. std::string comment() Description Get the comment of in the initial condition file. Return value The comment string. std::vector string get varlist failed() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables. vector string get varlist set() Description Get the list of variables in the initial condition file which were successfully loaded into the data dictionary. Return value The list of variables. double var value get(std::string path) Description Get the numerical value of a variable. Parameters path The data dictionary path. Return value The numerical value of the variable.

c Airbus Defence and Space 653 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

std::string var string get(std::string path) Description Get the string value of a variable. Parameters path The data dictionary path. Return value The string value of the variable.

bool var value set(std::string path, double value) Description Set the numerical value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure.

bool var string set(std::string path, std::string value) Description Set the string value of a variable. Parameters path The data dictionary path name. value The new value. Return value true on success, false on failure.

vector string list(std::string path) vector string list() Description Get a list of child node names beneath a parent node. Parameters path The path of the parent node (default the root “/”). Return value The list of child node names.

30.13 ExtSimView class

This class wraps the External Simulator Access interface. Detailed information on the use of this inter- face can be found in Chapter 32.

654 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

30.13.1 Constructors public ExtSimView(Session session, std::string id) Description Create a new External Simulator Access view. Parameters session The simulation session. id The symbolic identifier of the view.

30.13.2 Method reference int add(ExtSimVar var) Description Add a variable to this view. Parameters var The variable to add to the view. Return value 0 on success, -1 on failure. string get export id() Description get the export_id of this view Return value the export_id string get view id() Description get the view_id of this view Return value the view_id int connect(int rw flags, double frequency, int compression) Description Create a new view with the variables previously added to the view. Note that an excessive ammount of variables on the view might cause memory issues when calling connect. In such cases, increase the stack size of the host thread accordingly or spread the variables over multiple views. Parameters rw flags Read/write flags, 1 is read, 2 is write. frequency Update frequency in Hz. compression Compression type to be used for the data transmission. 0 is no compression, 1 means that unchanched values in the view are not transmitted. Please note that in case the whole view is not changed, no update is sent in any case. Return value 0 is success, -1 is failure. This only is a local return value. The simulator emits a message evExtNewView with view id and export id as arguments on succesful creation of the requested view.

c Airbus Defence and Space 655 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

int change freq(double frequency) Description

Parameters Change the update frequency of the view.

frequency The update frequency in Hz. Return value 0 is success, -1 is failure.

int send() Description Send the view with the updated values to the simulator. Return value 0 is success, -1 is failure.

30.14 ExtSimVar class

This is the base class of the ExtSimVar* classes. It is not to be used directly.

30.14.1 Method reference

ExtSimVar.extvar t type() Description Get the variable type. Return value The variable type.

bool is array() Description Find out if the variable is an array variable. Return value true if it is an array.

bool is fortran() Description Find out if the variable is a Fortran variable. Only relevant for arrays, as the Fortran column/row order is different from C/Ada. Return value true if it is a Fortran variable.

int nof dims() Description Get the number of dimensions of the array variable.

656 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Return value The number of array dimensions.

SWIGTYPE p int dims() Description Get the dimensions of the array variable. Return value The array dimensions. std::string path() Description Get the data dictionary path of the variable. Return value The data dictionary path. long size() Description Get the size in bytes of the variable. Return value The size in bytes.

30.15 ExtSimVar* classes

Below are the derived classes of ExtSimVar described. All similar methods are grouped to reduce the amount of documentation that only repeats the same information again and again. Therefore only two different cases are documented. One for the single element case and one for the array case. For both cases the following variants are possible: Char, Double, Float, Int, Long, Short, UnsChar, UnsInt, UnsLong and UnsShort. The java types corresponding to the above types are: char, double, float, int, int, short, short, long, long and int. For arrays there are two variants: ExtSimVar*Array and ExtSimVar*FortranArray. To summarize for one type you can have the following classes: ExtSimVarChar, ExtSimVarCharArray and ExtSimVarCharFortranArray.

30.15.1 Constructors public ExtSimVar*(std::string path) public ExtSimVar*Array(std::string path, int dim0) public ExtSimVar*Array(std::string path, int dim0, int dim1) public ExtSimVar*Array(std::string path, int dim0, int dim1, int dim2) public ExtSimVar*FortranArray(std::string path, int dim0) public ExtSimVar*FortranArray(std::string path, int dim0, int dim1) public ExtSimVar*FortranArray(std::string path, int dim0, int dim1, int dim2) Description Create a new variable to be used in an ExtSimView.

c Airbus Defence and Space 657 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Parameters path The data dictionary path dim0 The size of the first dimension. dim1 The size of the second dimension. dim2 The size of the third dimension.

30.15.2 Method reference

* get() * get(int idx0) * get(int idx0, int idx1) * get(int idx0, int idx1, int idx2) Description Get the value of a single variable or single array element. The variant without the idx* param- eters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension. Return value The value of the variable. The type of the return value depends on the type of the function. The type mapping is listed above in the introduction.

void set(* val) void set(* val, int idx0) void set(* val, int idx0, int idx1) void set(* val, int idx0, int idx1, int idx2) Description Set the value of a single variable or single array element. The variant without the idx* parame- ters is for a single variable, the others are for 1, 2 and 3 dimensional arrays. Parameters val The new value. The type of the value depends on the type of the function. The type mapping is listed above in the introduction. idx0 Index in first dimension. idx1 Index in second dimension. idx2 Index in third dimension.

658 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 31

C Cient Interface reference

31.1 Introduction

The run-time interface of EuroSim is the C-Language interface which is used to communicate with the running simulator. The Simulation Controller tool and the batch utility use this interface to start a new simulation run and to control it. This interface description provides a step by step description of how to start the simulator and what commands to send to control the simulator once it is running. The order of the chapters is the order of each step. In Section 31.2 is explained how to start a simulator using the EuroSim daemon and how to connect to the new simulator. In order to receive autonomous messages from the simulator the client must subscribe to certain channels. This is explained in Section 31.3. The following 4 chapters describe each one channel. Shutdown and cleanup is described in Section 31.8. Finally, Section 31.9, gives an overview of the available manual pages on the subject.

31.2 Simulator start-up

On each host where a EuroSim simulation can run, a daemon must be started. This daemon is responsible for the starting of simulators (among other things). The interface to this RPC daemon is defined in esimd.x in $EFOROOT/include/rpcsvc. The header file can be found in $EFOROOT/include/esim. The details of the interface are described in manual page esimd(3).

To start a simulator the RPC call start_session_7() must be done. The EuroSim daemon running on a EuroSim simulator host will launch the actual simulator executable. This call takes the following structure as argument:

Listing 31.1: session7 def structure struct session7_def { file_def sim; char *work_dir; char *simulator; file_def schedule; struct { u_int scenarios_len; file_def *scenarios_val; } scenarios; char *dict; file_def model; char *recorderdir; struct { u_int initconds_len; file_def *initconds_val;

c Airbus Defence and Space 659 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

} initconds; struct { u_int calibrations_len; file_def *calibrations_val; } calibrations; char *exports; char *alias; char *reserved; struct { u_int environment_len; env_item *environment_val; } environment; int prefcon; int umask; int flags; int uid; }; struct file_def { char *path; char *vers; };

The file_def structure is used to store the name of the file and an optional version string. Table 31.1 describes each member of the session7_def structure.

field description sim The path and version name of the simulation definition file (.sim). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. work_dir The path name of the current working directory of the simulator. The directory should exist and be accessible by the EuroSim daemon. Normally this is done by making the directory available through NFS in case the RPC call is performed from a different host. simulator The file name of the simulator executable (.exe). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. schedule The file name of the simulator schedule file (.sched). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. scenarios An array of scenario files (.mdl). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. dict The file name of the data dictionary file (.dict). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. model The file name of the model file (.model). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. This file is not actually used by the simulator for reading. It used for tracing purposes as a reference. recorderdir the path name of the directory where all recordings are stored. It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. initconds An array of initial condition files (.init). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. Table 31.1: session def structure

660 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

field description calibrations An array of calibration files (.cal). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. exports the file name of the exports file (.exports). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. alias the file name of the alias file (.alias). It can be an absolute or relative path name. If it is a relative path name, it is relative to the path in work_dir. environment an array of environment variables in the usual format VAR=value. Normally it is sufficient to copy the entire current environment into this array. If you want to start the simulator with a custom environment setting you have to set at least the following environment variables used by EuroSim in addition to the ones used by the simulator model software. EFOROOT should be set to the EuroSim installation directory. EFO_SHAREDMEMSIZE is the amount of memory reserved for dynamic memory allocation. Default is 4194304 (4 MB). This value can be set in the ModelEditor since Mk3rev2. EFO_STACKSIZE is the stack size reserved for each thread of the simulator. Default is 16k. This value can be set in the ModelEditor since Mk3rev2. PWD is the current working directory and is set to work_dir by the daemon if it is not present. LD_LIBRARY_PATH should be set to the path of the shared libraries of EuroSim. The value is normally $EFOROOT/lib. prefcon set to -1 under normal circumstances, a connection number is selected by the daemon and returned on successful start-up of the simulator. Put a positive value here if you want to force the new simulator to have a specific connection number. umask the umask used for creation of new files. See umask(2). flags there are currently two flags defined: SESSION REALTIME and SESSION NO AUTO INIT. Flags shall be or-ed together. Add the SESSION REALTIME flag for real-time runs, or do not set the flag for non-real-time runs. The SESSION NO AUTO INIT flag can be set to prevent the EuroSim scheduler from automatically going into initializing state. This is used by the EuroSim Simulation Controller to set break points and traces and to disable tasks before the simulation goes into initializing state. uid Reserved. No action or data needed by the user in relation to this field. Table 31.1: session def structure

The following small example in C will show how to start a simulator using representative values for the parameters. We however recommend an easire method which is explained thereafter to fill the session structure.

Listing 31.2: tc example.c #include #define _RPCGEN_CLNT #include int main(void) { struct session7_def session; struct start7_result *result; env_item env[6]; file_def scenario; file_def initcond; CLIENT *clnt;

c Airbus Defence and Space 661 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

session.sim.path="Demo.sim"; session.sim.vers=""; session.work_dir="/home/user/projects/STD"; session.simulator="Demo.exe"; session.schedule.path="Demo.sched"; session.schedule.vers=""; scenario.path="Demo.mdl"; scenario.vers=""; session.scenarios.scenarios_len=1; session.scenarios.scenarios_val=&scenario; session.dict="Demo.dict"; session.model.path="Demo.model"; session.model.vers=""; session.recorderdir="2000-04-01/00:00:01"; initcond.path="Demo.init"; initcond.vers=""; session.initconds.initconds_len=1; session.initconds.initconds_val=&initcond; session.exports="Demo.exports"; session.alias="Demo.alias"; session.prefcon=-1; session.umask=022; session.flags=SESSION_REALTIME; env[0] = "LD_LIBRARY_PATH=/usr/EuroSim/lib"; env[1] = "HOME=/home/user"; env[2] = "EFO_HOME=/home/user/project/EfoHome"; env[3] = "LD_LIBRARYN32_PATH=/usr/EuroSim/lib32"; env[4] = "PWD=/home/user/project/STD"; env[5] = "EFOROOT=/usr/EuroSim"; session.environment.environment_len = 6; session.environment.environment_val = env;

clnt = clnt_create("spiff", ESIM_PROG, ESIM_VERS7, "tcp"); clnt->cl_auth = authunix_create_default(); result = start_session_7(&session, clnt); if (result->status == ST_SUCCESS) { printf("simulator started at connection %d\n", result->start7_result_u.success.con); return 0; } else { error_array *errors; unsigned int i;

printf("simulator failed to start:\n"); errors = &result->start7_result_u.errors; for (i = 0; i < errors->error_array_len; i++) { printf("%s\n", errors->error_array_val[i]); } xdr_free((xdrproc_t)xdr_start_result, (char*)result); return 1; } }

The above example can be compiled as follows:

gcc -Wall -I$(EFOROOT)/include -I$EFOROOT/include/esim \ -o tc_example tc_example.c -L$EFOROOT/lib -lesClient -les

It is however easier if you use the esimd_complete_session function to fill in the missing pieces.

662 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

You only have to provide the simulation definition and the other entries will be completed by the esimd_complete_session:

Listing 31.3: Example of the use of esimd complete session()

#include #include #include #include #include int main(void) { struct session7_def session; extern char **environ; char *err; int prefcon; pid_t pid,

memset(&session, 0, sizeof(session)); session.work_dir = ds("/home/user/projects/STD"); session.sim.path = ds("Demo.sim"); if (esimd_complete_session(&session, "localhost", environ) == 0) { /* start session */ session.flags = SESSION_NO_AUTO_INIT; session.flags &= ˜SESSION_REALTIME; if ((err=esimd_client_launch_7("localhost",&session,&prefcon, &pid))){ printf("Client launch error: %s\n",err); }

esimd_free_session(&session); } }

Note that the example is using localhost as computer name. You can also fill in the name of the lo- cal machine or even the name of a remote machine. The example also uses a utility function to du- plicate the string in heap memory char *ds("const char*). This memory will be freed using the esimd_free_session function. The ds function is declared in the auxMemory.h file in the include/esim directoy of your EuroSim installation. On a succesfull esimd_complete_session the session structure is filled with the correct data to launch a simulator with. The session flags are first set to set the simulation to non-real-time and avoid that the simulator automatically starts entering the initialising state after launch. Thereafter the esimd_client_launch_7 call can be used to request the daemon to start the simulator. After successfully launching the simulator a connection can be created to the running simulator exe- cutable. There is some time between launching the simulator and when a connection can be created. This time is normally less than a second, but depends on the size of the simulator and the model inter- faces used (the CPP interface is slower to start then the C interface for instance). The eventProbe function can be used to check if the simulator is already running:

Listing 31.4: check simulator activity int fd=0; while(fd<=0) { fd=eventProbe("localhost",prefcon,0); }

The eventProbe function returs the file descriptor on which the simulator with the passed prefcon number

c Airbus Defence and Space 663 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

was found on host localhost. The third argument is for debugging and normally zero. If set to one, the eventProbe function prints status information. To make a connection with the simulator the function eventConnect() must be called, or eventConnectFd() must be called. The latter accepts the file descriptor from eventProbe.

Listing 31.5: Connect to a simulator #include

Connection *conn; void *userdata;

conn = eventConnectFd("localhost", "test-controller", fd, connClient, eventHandler, userdata, true, prefcon);;

The second parameter is the client name. In this example it has the value “test-controller”. If the string contains the sub-string “-observer”, the client is treated as a read-only client of the simulator. The client can monitor variables but not change them. The client cannot do anything which influences the simulator. The parameter eventHandler is the callback function which is called when an event from the simulator has been received. Each event results in one call to the callback. The callback must determine the type of the message and decode its contents. The callback has one parameter called userdata which contains the value given when calling eventConnect(). The following example in C code shows an implementation of the eventHandler callback.

Listing 31.6: Example of an eventHandler callback function #include

int eventHandler(Connection *conn, const evEvent *event, void *userdata) { size_t offset = evEventArgOffset(); int sev; char *mesg, *thread; double speed; AuxTime simtime, wallclocktime;

simtime = evEventSimTime(event); wallclocktime = evEventRunTime(event);

switch (evEventType(event)) { case maMessage: evEventArgInt(event, &offset,&sev); evEventArgString(event, &offset,&thread); evEventArgString(event, &offset,&mesg); printf("%u: %s %s\n", sev, thread, mesg); break;

case scSpeed: evEventArgDouble(event, &offset,&speed);); printf("speed = %f\n", speed); break; } return 0; }

The programmer can choose to use synchronous or asynchronous handling of events. The example above has chosen for asynchronous event handling. This means that each time an event arrives a signal (SIGIO) is sent to the application. The library installs a signal handler which ultimately calls the eventHandler

664 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

callback. If you select synchronous handling, the application has full control over when events are read. Using select(2) the programmer can determine if data is ready to be read and would then call eventPoll() to process all the available events. The function eventPoll() will call the eventHandler callback for each event.

31.3 Subscribing to channels

After connecting to the server, the simulator client can subscribe to several channels. When a client is subscribed to a channel it will receive events that are sent automatically without a previous client request. These messages are either generated by the models or by the simulator infrastructure. Each channel addresses a specific area of interest. At the moment of subscribing (or joining) a channel, the client will receive a number of messages describing the current state relating to that channel. The messages after joining a channel are described in the chapter dedicated to that channel. Table 31.2 describes each channel.

Channel Channel Identifier Define Chapter Real time control rt-control CONTROLCHANNEL Section 31.4 Mission mdlAndActions MISSIONCHANNEL Section 31.5 Monitor data-monitor MONITORCHANNEL Section 31.6 Scheduler control sched-control SCHEDCONTROLCHANNEL Section 31.7 Table 31.2: Channel Descriptions

To subscribe to a channel the function eventJoinChannel() must be called. Fruther extending the previous example, following lines must be added following the eventConnect call. Listing 31.7: Join a channel Connection *conn; /* must be set with eventConnect() */

eventJoinChannel(conn,"sched-control"); eventJoinChannel(conn,"mdlAndActions");

For a simulator client it is mandatory to join the mdlAndActions channel. After launching the simulator, the simulator waits with the further initialization until the first client joins this particular channel. The simulator can then send its messages to a client. This is particular useful when something goes wrong. It enables the user to read the messages and take corrective actions. The following four chapters will describe each channel in detail. Each chapter will contain tables de- scribing events coming from the simulator and commands which can be sent to the simulator. Each command is sent using an event* function. This function takes 2 or more arguments. The first two arguments are always the same. The first argument is the handle to the connection, the second argument is a pointer to an AuxStamp structure which can be a NULL pointer for clients.

31.4 Real time control channel

The real time control channel is used to request and report state changes of the simulator. The simulator client can request state changes and the simulator will report the new state as soon as it has been reached. Figure 31.1 shows the state transition diagram applicable to an external application controlling the simu- lator. Next to the arrows are the functions to be called for each state transition. In the boxes the name of the event is shown that is sent to the client when entering the state. The only exception is the eventReset command. This command performs a small scenario consisting of a state transition from standby state to exiting state. from exiting to unconfigured, from unconfigured to initializing. In initializing state the automatic state transition to standby is performed as specified in the schedule.

c Airbus Defence and Space 665 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

start session 7

eventJoinChannel(MISSIONCHANNEL) rtUnconfigured rtInitializing

(automatic) eventAbort rtStandby eventStop (automatic)

rtExiting eventGo eventFreeze

eventAbort rtExecuting

Figure 31.1: Simulator states

Table 31.3 lists the messages sent to the client after joining the real-time control channel.

Event Description Arguments rtUnconfigured, rtInitializing, Current state - rtStandby, rtExecuting, rtExiting rtMainCycle Main cycle time of schedule cycle time in timespec format (tv sec and tv nsec) Table 31.3: Real time control channel join events

Table 31.4 shows the functions which can be used to request the change and the events sent back as a result.

Command Description Response eventFreeze Request state transition to rtStandby standby state from initializing or executing state eventFreezeAt Same as previous but rtStandby wait until a certain wallclock time. eventFreezeAtSimtime Same as previous but rtStandby wait until a certain simulation time eventGo Request state transition to rtExecuting executing state from standby state eventGoAt Same as previous but rtExecuting wait until a certain wallclock time. eventStep Request the execution of rtExecuting one main cycle. rtStandby Table 31.4: Real time control channel commands

666 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Command Description Response eventReset Request reinitialization rtExiting from standby state rtUnconfigured rtInitialising rtStandby (if performed automatically by the schedule configuration) eventStop Request the controlled rtExiting termination from standby rtUnconfigured state. eventAbort Request immediate abort rtUnconfigured from any state. eventHealth Request health check. maMessage maMessage maMessage rtHealth Table 31.4: Real time control channel commands

As state transitions may take some time, a rtTimeToNextState message is sent to the simulator client which contains the amount of time to the transition. After joining the rt-control channel the current simulator state is sent. All state transitions from then on are sent to the client, including automatic state transitions, or transitions requested by another client. The standard time stamps of the state transition message can be used to calculate valid future state transition times which can be used to issue timed state transition commands. To calculate a valid future transition time take the wallclock or simulation time from the last state transition message and add an integer number of main cycle times. The following example in C requests a state transition at midnight on April 1, 2001 (wallclock time): Listing 31.8: Time state transition Connection *conn; /* must be set with eventConnect() */ struct timespec tv; struct tm tm; tm.tm_sec = 0; tm.tm_min = 0; tm.tm_hour = 0; tm.tm_mday = 1; tm.tm_mon = 4; tm.tm_year = 100; /* years since 1900 */ tm.tm_isdst = 0; tv.tv_sec = mktime(&tm); tv.tv_nsec = 0; eventGoAt(conn, NULL, &tv);

At the indicated time an event rtExecuting is sent to the simulator client.

31.5 Mission channel

The mission channel is used for all activities relating to the manipulation of scenarios and actions. Sce- narios are either loaded at start-up from disk or are created on the fly using the commands listed in this chapter. Scenarios loaded from disk can be modified in the simulator. The changes are only in the running simulator, not in the file on disk.

c Airbus Defence and Space 667 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Table 31.5 lists the messages sent to the client after joining the mission channel.

Event Description Arguments maDenyWriteAccess Write access notification. on/off maCurrentWorkingDir Working directory notification. working directory maCurrentDict Current data dictionary notification. dictionary file name maSimDef Current simulation definition file simulation definition filename maCurrentResultDir Current result directory notification. result directory maCurrentAliasFile Current alias file notification. alias file maCurrentTimeMode Current time mode notification. 0 = relative 1 = UTC maCurrentInitconds Current list of initial condition files notification. initial condition file(s) maCurrentCalibrations Current list of calibration files notification. calibration file(s) maRecording Recording status notification. on/off Table 31.5: Mission channel join events

Table 31.6 shows the events which can be sent to the simulator and the responses they send back. Argu- ments are enclosed in angled brackets. Literal messages are in courier where variant parts are in italic. Wherever you see the word file (as in scenario file) a file on disk is meant. All other references to scenario are to the run-time data structure inside the simulator.

Command Description Response eventNewMission Create a new (virtual) maNewMission scenario maMessage eventOpenMission Open an existing scenario maOpenMission file maMessage eventCloseMission Close a scenario maMessage by "group" closed> maCloseMission eventNewAction Create a new action in a maNewAction scenario maMessage "actionname" in "scenario"> eventDeleteAction Delete an action in a maDeleteAction scenario maMessage from "scenario"> eventActionExecute Execute (trigger) an maActionExecute action in a scenario maActionExecuteStop maMessage 1 Table 31.6: Mission channel commands

1In case a monitor action (obsolescent) is executed various messages from the monitor channel are generated. These can be found in Table 31.9

668 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Command Description Response eventActionActivate Make an action active in maActionActivate a scenario maMessage eventActionDeActivate Make an action inactive maActionDeActivate in a scenario maMessage deactivated> eventExecuteCommand Execute a single shot maExecuteCommand MDL command. This shall be used for MDL maMessage commands that need to be executed only once. eventCurrentAliasFile Set a new alias definition maCurrentAliasFile file. eventCurrentInitconds Sets a new list of initial maCurrentInitconds files(s)> eventCurrentCalibrations Sets a new list of maCurrentCalibrations calibration files. eventSnapshot Make a snapshot. maMessage filename> maSnapshot eventReload Reload a snapshot file. maReload The second argument set simtime> simtime can be set to on If snapshot is loaded with simtime: or off. When it set to on, scSimtime the simulation time is set maMessage snapshot file. In all cases: maMessage eventMark Create a mark. maMark eventMessage Send a message to the maMessage simulator client eventRecording Suspend/resume When switching off: recording. maRecording maMessage When switching on: maRecording maMessage eventRecordingSwitch Switch recorder files. For each recorder file: maRecorderFileClosed maMessage Table 31.6: Mission channel commands

Table 31.7 shows the events relating to messages which can be sent from the model code or the simulator

c Airbus Defence and Space 669 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

infrastructure.

Event Description Arguments maMessage Message severity, message Table 31.7: Message events

Table 31.8 shows the messages sent autonomously every 2 seconds.

Event Description Arguments maRecordingBandwidth Current recording bandwidth bandwidth (bytes/sec) consumption notification. maStimulatorBandwidth Current stimulator bandwidth bandwidth (bytes/sec) consumption notification. Table 31.8: Mission channel autonomous messages

The following example in C requests the loading of a scenario file into the simulator.

Listing 31.9: Load an MDL file into the simulator Connection *conn; /* must be set with eventConnect() */

eventOpenMission(conn, NULL, "/home/eurosim/project/proj.mdl");

The result will be a maMessage event informing about the successful opening of the scenario file.

31.6 Monitor channel

The monitor channel is used to manipulate monitors. Table 31.9 shows the messages which are sent when triggering a monitor action (obsolescent). The event dtMonitor is sent at the start to mark the beginning of a new monitor. If one monitor action monitors multiple variables, the dtMonitorVar event is sent once for each variable. The event dtMonitorDone ends the list. The client application can then set up the display for the new monitor. The client must send a eventAdd2LogList command for each variable. After that every 0.5 seconds (2 Hz) an update (dtLogValueUpdate) is sent from the simulator to the client. The frequency can be changed to a higher or a lower frequency by passing an option -f to the EuroSim daemon esimd with the required frequency. Using this command line option for the daemon sets the frequency for all simulators. The frequency may be a floating point number. The frequency can be changed to a lower frequency by passing an option -d to the EuroSim daemon with a divisor. This option reduces the frequency of the monitor updates etc. with the specified integer factor. This option affects all simulators started with the daemon. The order of messages periodically sent by the simulator to the client is as follows:

• monitor values

• heartbeat

• cpu load (optionally)

Alternatively it is possible to retrieve the value of a variable only once by using the dtGetValueRequest command.

670 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Event Description Arguments dtMonitor Start new monitor scenario, action name dtMonitorVar Monitor variable variable name dtMonitorDone Finish new monitor attributes Table 31.9: Monitor events on monitor action (obsolescent) execution

Table 31.10 shows the event sent periodically at 2 Hz for each variable in an active monitor.

Event Description Arguments dtLogValueUpdate Monitor value update variable name, value Table 31.10: Monitor update event

Table 31.11 shows the commands which can be sent.

Command Description Response eventAdd2LogList name> monitored variables dtLogValueUpdate eventRemoveFromLogList Remove variable from list dtRemoveFromLogList of monitored variables name> eventSetValueRequest Set variable to value dtSetValueRequest name> maMessage If variable is monitored at that moment: dtLogValueUpdate eventSetMultipleValueRequest Atomically set multiple For each variable: variables to a new value. dtSetValueRequest multiple times maMessage that it is guaranteed that If variable is monitored at that all variables are updated moment: in the same simulation dtLogValueUpdate cycle.

eventCpuLoadSetPeak Monitor the CPU load of a dtCpuLoadSetPeak (ms)> At a frequency of 2 Hz: dtCpuLoad dtGetValueRequest variable once name> Table 31.11: Monitor channel commands

c Airbus Defence and Space 671 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Table 31.12 shows the messages sent on the mission channel autonomously with a frequency of 2 Hz.

Event Description Arguments dtHeartBeat Heartbeat count Table 31.12: Monitor channel autonomous events

The following example in C requests the monitoring of a specific variable in the data dictionary of the running simulator.

Listing 31.10: Start monitoring a variable Connection *conn; /* must be set with eventConnect() */

eventAdd2LogList(conn, NULL, "/model/file/var");

From this moment on dtLogValueUpdate messages will be sent to the simulator client with 2 Hz. To stop these messages call:

Listing 31.11: Stop monitoring a variable eventRemoveFromLogList(conn, NULL, "/model/file/var");

31.7 Scheduler control channel

The scheduler control channel is used to manipulate and monitor the EuroSim scheduler. Table 31.13 lists the messages sent to the client after joining the mission channel.

Event Description Arguments scTaskListStart Beginning of task list - scTaskStart Beginning of entry point list of a task taskname, enabled scTaskEntry Entry point description entryname, breakpoint, trace scTaskEnd End of entry point list of a task - scTaskListEnd End of task list - scEventListStart Beginning of event list - scEventInfo Event description eventname, state, is standard scEventListEnd End of event list - scGoRT Real-time mode notification enable Table 31.13: Scheduler control join events

Table 31.14 lists the available commands.

672 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Command Description Response eventSetBrk Set breakpoint scSetBrk The where-list is only sent if the simulator state maMessage scWhereListStart scWhereEntry scWhereListEnd eventStepTsk Step to next entry point scWhereListStart scWhereListEnd scStepTsk scWhereListStart scWhereEntry scWhereListEnd maMessage eventContinue Continue execution up to scWhereListStart next breakpoint scWhereListEnd scContinue scWhereListStart scWhereEntry scWhereListEnd eventGoRT Switch between real-time scGoRT and non-real-time. eventListTasks Request task list scTaskListStartscTaskStart scTaskEntry scTaskEndscTaskListEnd eventEntrypointSetEnabled Enabled or disable an scEntrypointSetEnabled entry point. eventTaskDisable Disable a task scTaskDisable maMessage eventSetTrc Enable/disable tracing of scSetTrc an entry point eventClearBrks Clear all breakpoints scClearBrks eventClearTrcs Clear all traces scClearTrcs eventWhere Request current position scWhereListStart in schedule scWhereEntry scWhereListEnd eventListEvents Request event list scEventListStartscEventInfo scEventListEnd eventRaiseEvent Raise event scRaiseEvent Table 31.14: Scheduler control commands

c Airbus Defence and Space 673 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Command Description Response eventSimtime Set simulation time scSimtime maMessage eventRaiseEventAt Raise event at wallclock scRaiseEventAt time eventRaiseEventAtSimtime Raise event at simulation scRaiseEventAtSimtime time eventSpeed Set relative clock speed scSpeed Only when running non-realtime. When speed is set to -1, the simulator will run as fast as possible. Table 31.14: Scheduler control commands

There are three groups of events which need additional attention. These groups of events are used to transmit complicated data structures to the client:

• task list

• event list

• debugger position list

The task list uses 5 events which are sent in a nested fashion. The task list starts with scTaskListStart and ends with scTaskListEnd. After scTaskListStart one or more tasks are sent. Each task starts with scTaskStart and ends with scTaskEnd. After scTaskStart one or more entry points are sent. Each entry point is sent using scTaskEntry. The event list starts with scEventListStart and ends with scEventListEnd. After scEventListStart one or more event descriptions are sent. Each event is sent using scEventInfo. The debugger position list, also called where list, starts with scWhereListStart and ends with the re- sponse scWhereListEnd. After scWhereListStart zero or more positions are sent. Each position is sent using scWhereEntry. Table 31.15 shows the messages sent autonomously every 2 seconds.

Event Description Arguments scSpeed Relative clock speed. speed Only when running non-real-time. Table 31.15: Scheduler control autonomous messages

The following example in C sets the speed of a non-realtime simulator to run as fast as possible. Listing 31.12: Let the simulator run as fast as possible Connection *conn; /* must be set with eventConnect() */

eventSpeed(conn, NULL, -1);

From now the scheduler from EuroSim will execute all models as fast as possible. The event scSpeed is sent at 2 Hz. The value of the speed parameter will reflect the actual acceleration achieved.

674 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

31.8 Simulator shutdown

At the moment a simulator executable exits, all clients are automatically disconnected. In that case event evShutdown is received. This is a pseudo event which is not sent by the simulator but is generated as soon as a socket shutdown is detected. The socket has been destroyed by then and it is not possible to send messages to the simulator anymore. It is also possible to actively terminate the simulator connection by calling eventDisconnect():

Listing 31.13: Disconnect from the simulator Connection *conn; /* must be set with eventConnect() */ eventDisconnect(conn);

After disconnecting from the simulator it is not possible to send messages to the simulator. However it is possible to reconnect to the simulator using the functions described in Section 31.2.

31.9 Manual pages

Table 31.16 shows an overview of the on-line available manual pages of EuroSim. These pages are the ultimate reference for all events.

Man Page Description events(3) Retrieval system for information about all available EuroSim events evEvent(3) Event construction, access and I/O functions rt-control(3) Real-time control events data-monitor(3) Monitor events sched-control(3) Scheduler control events mdlAndActions(3) Scenario events

esimd(3) EuroSim daemon RPC client interface functions and types evc(3) Functions for clients to setup multi bi-directional event driven connections evHandler(3) Functions for server and client to create handlers for incoming events extClient(3) Functions for an external client to establish and control access to a EuroSim simulator extView(3) Functions to create, control and destroy data views. extMdl(3) Functions for an external client to manage scenarios and actions running on a EuroSim simulator extMessage(3) Functions for an external client to send messages to a EuroSim simulator. esimLink(3) Functions for creating and manipulating simulated satellite communication links Table 31.16: Overview of relevant manual pages.

c Airbus Defence and Space 675 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

676 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 32

External Simulator Access reference

32.1 Introduction

With EuroSim the possibility exists to share simulation data at run time between EuroSim and another (external) simulator. This is achieved by linking external (local in the client) variables to (a subset of) the EuroSim data dictionary variables. During the simulation, EuroSim tools ensure that the values in the two data dictionaries are “mirrored” (the update frequency being a user definable parameter). In Figure 32.1a schematic of the connection and associated functions for handling the data dictionary values is provided.

External Client EuroSim Application Model datadict values Update Transmit Receive values dict view dict view Simulation model

Simulate Something DataDict DataDict

datadict values Process Receive Transmit value(s) dict view dict view

ethernet

Figure 32.1: External Simulator Access Schematic

The two simulators need to be connected via a TCP/IP link. The EuroSim extSimAccess routines are intended to be usable within a heterogeneous environment, and should be suitable for any UNIX based simulators. In addition to the specified data dictionary values, the external simulator also receives the simulation time, (elapsed) wall clock time and simulation state from EuroSim. Note that the C++ Batch interface (see Chapter 30) provides an object oriented interface on top of the External Simulator Access library. This provides the same capabilities as part of an object oriented interface in C++ usable by client programs to estabish simulator client connections. It is up tot he user select either the C++ interface or the lower level C library interface documented in this chapter on the client program.

32.2 Selection of shared data items

It is possible to make all EuroSim data dictionary items accessible between the two simulators, but for performance, security or other reasons, it is often a requirement to limit the number of data items which are shared between the two. There are two levels of filter which can be applied:

c Airbus Defence and Space 677 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• The EuroSim application decides which data dictionary items are to be visible to an external sim- ulator, and whether with read and/or write access (defined in an exports file).

• The external simulator application decides which data dictionary items are to be used from those made available from EuroSim, and the type of access (defined in a data view).

An example is shown in Figure 32.2. The first box shows all the API items in the EuroSim data dictionary, i.e. all possible data items which can be shared between the two simulators. The middle box shows that by listing a subset of these items in a exports file, the EuroSim application can limit the number of data items which it wants the external simulator to share. In addition, read/write access can be limited. And finally, the third box for the external client shows how only some of the “public” data variables are actually referenced by the external simulator for his own internal use.

EuroSim External Application Model Exports Simulator (Client) Data Dictionary Interface Data View /nodeA/varX /nodeA/varX R /nodeA/varX R /nodeA/varY /nodeA/varY R /nodeA/varZ /nodeA/varZ R /nodeB/varM /nodeB/varM R /nodeB/varM R /nodeB/varN /nodeC/varR /nodeC/varS /nodeC/varS W /nodeC/varS W /nodeC/varT /nodeC/varT W /nodeC/varU /nodeC/varU W

Figure 32.2: Filtering of Data Dictionary Items

32.3 Exports file

To share data between a EuroSim application and an external simulator, an additional file is needed. This file shall have the extension .exports, e.g thermo.exports and shall be included in the simulation definition file for this simulator. The exports file specifies the EuroSim data dictionary items which will be made accessible at runtime to the external simulator (see Section 32.2). It is a text file and the contents can contain any number of lines of either of the following formats:

# this is an optional comment line; # the next line can be tab or space separated dict_node_ref viewName accessType

The dict_node_ref is a reference to a node or individual data item within the data dictionary hierarchy. Hence /myNode/file.c/stateVariableA is a legal reference which allows a particular variable to be accessed explicitly, as is /myNode which implicitly allows access to all of the data items under the named node in the data dictionary hierarchy. The “viewName” provides a symbolic name for this set of data items, which needs to be referenced later on when creating a local data view for the external simulator. Each “viewName” has to be unique. It is generally recommended to make at least two views, one allowing read and one allowing write access. By choosing the views so that they contain different sets of data, this approach helps to reduce potential data inconsistencies which could be caused by simultaneous read/writes. Additional views may also be created for the purposes of data hiding, e.g. defining two views which give read access for nodes /A and /C, leaving node /B inaccessible to an external simulator. The accessType indicates the type of access (“R” or “W”) which the external simulator is given to the specified variables.

678 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

32.4 Creating multiple local data views

Instead of providing the external simulator with a single view of the shared EuroSim data (which is the situation implied in Figure 32.2 above), it can sometimes be advantageous to create and use several local data views. This is often useful when the external simulator is complex, and there are a significant number of shared data items. Two particular circumstances where multiple data views are recommended are:

• Data items need to be read/written at a wide range of frequencies, and therefore it is more efficient to split data items into views which can be given high and low update frequencies as required.

• The simulator model uses an object-oriented approach, and creating a data view per “object” con- tinues to support this methodology.

Each local data view is created from (i.e. maps to) a single EuroSim data view (i.e. a single line as defined in the exports file). However, there can be several local data views mapping to a single EuroSim data view, for example to provide the possibility to read new values at different frequencies as mentioned above.

External Simulator Exports file views (defining available EuroSim views) 10Hz read data view

# This gives read access to /nodeA/varX everything /nodeF/varG /nodeD/varP / r view R 20Hz read data view # And here some nodes/vars are /nodeB/varX # selected for write access /nodeB/varY

/nodeB bw view W 100Hz read data view /nodeC/varS cs view W /nodeC/varU cu view W /nodeB/varZ

Figure 32.3: Mapping of EuroSim and Local Data Views

32.5 Synchronization

The external simulator access link can also be used to synchronize the client and the simulator with each other. If either the client or the simulator is slower than the other, the other side waits until the slowest side is finished. Also if one side stops for some reason, hitting a breakpoint or going to standby state for instance, the other side is halted as well. The synchronization mechanism is coupled with the data being exchanged over the link so that data integrity is also ensured. At the simulator side this is done implicitly, but at the client side the user has to make sure to call extViewSend() before sending the synchronization token. The synchronization token should be a unique token for each synchronization point in a simulator. It is possible to have multiple synchronization points in a simulator, possibly with multiple clients. It is the responsibility to make sure that the numbers are unique. If the same token number is used by multiple clients the simulator and/or one of the clients will very likely become blocked. At startup the client shall connect to the simulator before the first synchronization token is sent from the simulator to the client. Sending synchronization tokens by the simulator is done by broadcasting as it is not possible to know in the simulator which client is performing synchronization (external simulator access clients are anonymous at the simulator side). So if the simulator sends the synchronization token before the client is connected, the token gets lost and the synchronization mechanism at the client side will have missed one token, resulting in a blocked client.

c Airbus Defence and Space 679 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

At the client side there are two functions for synchronization purposes. The function extSyncSend() sends the synchronization token to the simulator. The function extSyncRecv() waits for the synchro- nization token from the simulator. The following example shows how to use the functions in a typical application where the client is two- way synchronized to the server. #define SYNC_TOKEN 1234

extViewSend(write_view); /* send data to the simulator */ extSyncSend(sim, SYNC_TOKEN); /* send the synchronization token */ extSyncRecv(sim, SYNC_TOKEN); /* wait for the synchronization token */

At the simulator side there are two functions for synchronization purposes which are the counterparts of the functions on the client side. They differ from the client side functions by the fact that they do not have an argument to specify the connection. The function esimExtSyncSend() broadcasts the synchronization token to all clients. The function esimExtSyncRecv() waits for the synchronization token from the client. The following example shows how to use the functions in a typical application where the simulator is two-way synchronized to a client. #define SYNC_TOKEN 1234

esimExtSyncSend(SYNC_TOKEN); /* send the synchronization token */ esimExtSyncRecv(SYNC_TOKEN); /* wait for the synchronization token */

Please note that this method of synchronization cannot be used in a situation where hard-real-time perfor- mance is needed. The calls which wait for the synchronization token (extSyncRecv() and esimExtSyncRecv()) may block for a long time if the other side is stopped. In Figure 32.4 a sequence diagram of the exchange of tokens is shown. Please note that the client as well as the simulator are always blocked from the point where they wait for the token until the next token is received. This is the essence of the synchronization mechanism.

client simulator send sync & send sync & wait for sync wait for sync receive sync receive sync send sync & send sync & wait for sync

time wait for sync

receive sync receive sync

Figure 32.4: Synchronization sequence of a client and a simulator

32.6 Summary of procedure

The following steps summarize how to set up and use the connection between a EuroSim simulator and another (external) simulator:

1. Create an .exports file to specify which EuroSim data dictionary (API) items are visible to the external simulator.

680 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

2. Add calls to the external simulator code to link to EuroSim as a client at runtime.

3. Add calls to the external simulator code to make local data view(s) linking EuroSim data items to local variables.

4. Add calls to receive and send shared data at runtime.

5. Close the connection.

32.7 Case study: setting up shared data to another simulator

This section provides examples of how the procedure is implemented. The examples are taken from complete demonstration models (installed in $EFOROOT/src/TmTc+ExtSimModel).

32.7.1 Create an exports file No changes need to be made to the EuroSim application model itself, but an additional file (thermo.exports) must be created and added to the simulation definition file using the simulation con- troller. The given example has the following lines in the thermo.exports file:

/ r_view R /SPARC w_view W

The first line in the export file specifies that all data items (i.e. from the root of the data dictionary downwards) are to be available to an external simulator with read only access and under the id of r_view. A specific node or data item can be referenced individually if required; however the “/” symbol is a useful shorthand to allow all data items to be referenced in one go. The second line specifies that all data items under the SPARC node in the data dictionary are to be available under the id of w_view with write only access for the external simulator. As the SPARC node has also been included in the “/” specification for r_view, all data items under this note have effectively been given RW access and care should be taken when accessing their values. In this example, two separate views are created for the external simulator: one containing data for read- ing, one containing data for writing. This is recommended to limit potential data inconsistency problems when allowing simultaneous read/write access.

32.7.2 Link the external simulator as a EuroSim client The external simulator access library is initialized with the following call in the external simulator source code: #include extInit();

Note that this only needs to be called once in your main() function.

Next, the link is set up with the following call in the external simulator source code: #include sim = extConnect(hostname, clientname, eventHandler, userdata, async, prefcon); and takes the arguments: hostname Simulator host running target EuroSim simulator.

c Airbus Defence and Space 681 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

clientname Name by which this client is to be known to the EuroSim server, e.g. “TRPClientTester”. eventHandler Name of procedure in external simulator code which will process events coming from EuroSim simulator (flags indicating data updates and state changes are received as “events”). userdata Pointer to user defined data. This pointer is passed as a parameter to the eventHandler proce- dure.

async Flag to indicate signal driven event handling versus polled event handling (see also extPoll).

prefcon Preferred connection on the EuroSim server; should be used to select between simulators when more than one is currently active on the EuroSim simulation server (default of 0 is sufficient if only one simulator is active). A pointer is returned which identifies the simulator, and which you need to reference later on (e.g. when setting up the local view of the data dictionary). The extClient manual pages or [PMA18] provide more information on connection and disconnecting a client.

32.7.3 Determine host byte order When accessing a simulator running on a host with a different byte order than the client the bytes need to be swapped. In order to facilitate the detection of this difference in byte order, a message is sent to the client which allows you to determine the simulator byte order. Comparing the byte order to your own byte order will detect any differences. Below you find an example of such a detection routine: int needs_swap = 0; /* set to 0 if the byte order is the same */

int eventHandler(Connection *conn, const evEvent *event, void *userdata) { switch (evEventType(event)) { case evExtByteOrder: { int size; int *magic; evEventArg(event, &offset, EV_ARG_RAW(&size, &magic)); needs_swap = (*magic != EXT_BYTE_ORDER_MAGIC); } } }

32.7.4 Set up local data view with links to EuroSim data Overview Once the client link is set up, local data view(s) can be created which link external and EuroSim data items. The views can contain all or a subset of the data items which were “exported” from EuroSim as described in Section 32.7.1. There are three steps necessary, as shown in the following extract:

• Use of extViewCreate to create a local view.

• Use of extViewAdd to add a data item (local name + EuroSim name) to the view.

• Use of extViewConnect to connect the local view to the EuroSim simulator.

The extView manual pages or [PMA18] provide more information on data views.

682 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

#include "extSim.h"

#define VAR_VERBOSE_FLAG "Verbose" /* Wonly */ void main(int argc, char *argv[]) { int ext_verbose = 0; .... w_view_ext = extViewCreate(sim, "w_view"); .... extViewAdd(w_view_ext, VAR_VERBOSE_FLAG, &ext_verbose, extVarInt); ..... extViewConnect(w_view_ext, EXT_DICT_WRITE, frequency, COMPRESS_NONE); .... }

Creating a Local Data View

In this example, only one local view (w_view_ext) is being created from the EuroSim w_view de- fined in the model.exports file. It is possible to make several views: for example w_view_sensors, w_view_actuators, each local view then having added to it a subset of the dict items available in the referenced w_view (see Section 32.4 for more information).

Linking EuroSim Variables, Local Variables in the Local Data View In this case, the local view is to contain just one item: the EuroSim dictionary variable “Verbose”. A define is used to make a symbolic name from the data dictionary variable name1. The link between the data dictionary (symbolic) name VAR_VERBOSE_FLAG and the local variable ext_verbose is made with the extViewAdd call. The type of the variable also needs to be made known when adding it to the view (e.g. extVarInt); the different types possible are listed in the extView manual pages, which also provides more detailed information on setting up data views.

Connecting the View to EuroSim The final step is to define the connection characteristics for the local data view. The given frequency in extViewConnect is only useful for views which are requested with EXT_DICT_READ permission. It indicates how many times per second a view must be sent over. The maximum frequency is the maximum frequency of the EuroSim scheduler (as defined in the Schedule file). This frequency can be changed with a call to extViewChangeFrequency. The last argument in extViewConnect indicates if compression should be used. For now only one com- pression method is available which simply discards values that are not changed since the last update and has minimal effect on process time. The simulator confirms the creation of the view with a message evExtNewView which has the view_id string and the export_id string as arguments.

Alternative Method to Create/Use a Local Data View An alternative way of setting up a local data view requires access to EuroSim dict access routines, and the example code (as provided in $EFOROOT/src/TmTc+ExtSimModel) uses this technique to set up the write view. The method described above is generally preferred, as it can be used by any external simulator independently of EuroSim, the only knowledge of EuroSim then being required is a list of data dictionary items. 1At the moment the only way to find the correct data dictionary variable names is to get the information on-line from the info menu option in the Model Editor or DictBrowser, or to look in the model *.dict file.

c Airbus Defence and Space 683 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

32.7.5 Receiving and sending shared data at runtime Receiving Data Updates from the EuroSim Simulator When the view is connected, events from the EuroSim server arrive automatically and are passed through the eventHandler which was specified when extConnect was called (see Section 32.7.2). Incoming events can either indicate that the data view has just been updated (event->type of evExtSetData) or that a state change command has been issued by EuroSim (evEventType(event) of rtExecuting, rtStandby, etc.). Each event is timestamped with simtime and runtime (evEventSimTime(event) and evEventRunTime(event) respectively). In the given example external simulator code, an incoming evExtSetData event is used to trigger a display of the data (the data being read from local memory by the curses_print procedure). Similarly, any state events trigger the procedure curses_state which prints the state to screen together with the time- stamps. With this mechanism, if the update frequency is set to 10Hz, then the curses_print procedure is effectively being scheduled at 10Hz: static int eventHandler(Connection *conn, const evEvent *command, void *userdata) { char buf[50]; evArgRec *pt;

switch (evEventType(command)) { case evExtSetData: curses_print(command); break;

case rtExecuting: case rtStandby: ..... curses_state(command); ..... } ... }

However the events can be ignored: it is also possible to schedule (local) tasks which access the local data as and when required, rather than waiting for a data update to trigger processing.

Sending Updated Data Views When the view is opened with write permission, the external simulator can send an update to the EuroSim simulator with a call to extViewSend. This will result in an event being sent to the EuroSim server (unless the data has not changed since the last call to extViewSend). The following example shows the verbose data item being toggled and the updated view being sent: ext_verbose = !ext_verbose; extViewSend(w_view_ext);

32.7.6 Close the connection To close the connection between the client and the server, call the disconnect on exiting, for example: installSignalHandler(SIGQUIT, cleanup);

static void cleanup(int signal) { ... extDisconnect(sim);

684 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

if (signal) exit(1); exit(0); }

32.8 Performance

The External Simulator Access protocol is based on TCP/IP. This means that each data packet has some protocol overhead. When an isolated (peer to peer) Ethernet “network” is used (i.e. two computers connected by means of an Ethernet cross-over cable), then a theoretical throughput of 10 MByte/s can be achieved when using quality 100 Mbit/s network adapters and cable. The above figure can be affected in a negative way by a number of causes:

• Cheap network cards that saturate the CPU at an interrupt rate that allows only a few MByte/s on a 100 Mbit/s network,

• Overhead and latency introduced by routers,

• Operating system,

• Driver implementation,

• Collisions in a non-isolated network,

• Configuration (tuning of TCP/IP parameters).

The latter point needs some explanation. On most systems, the default transmit and receive buffer size for TCP/IP sockets is only 16384 bytes. On Linux, you can use the sysctl(8) command to increase buffer sizes.

32.8.1 Maximum throughput When using an non-isolated network, you must be aware of network “collisions” that affect the average throughput. Collisions are caused by multiple network nodes trying to access the medium (i.e. send a packet) at the same time. Each node will retry after a random interval. For that reason, a safe rule of thumb is to take one third (1/3) of the theoretical maximum as a basis for your calculations. In practice this means that you can transfer 3 MBytes/s on a 100 Mbit/s network or, in EuroSim terms, have a view of 7500 long integers (4 bytes each) updated at 100 Hz. Be aware though that any network “hiccup” will cause buffer overflows at such high data rates.

32.9 Building the client

32.9.1 Unix and Linux The external simulator access libraries are provided as dynamic shared objects (DSO’s) and are part of the standard EuroSim distribution. The include files are located in the include subdirectory of the directory where EuroSim is installed.

32.9.2 Windows When using the Cygwin environment, you can use the mingw gcc compiler and the external simulator access libraries as provided in the lib subdirectory of the directory where EuroSim is installed. If you prefer to use the Microsoft development tools, then you can use the DLL’s. To link your client application with the DLL’s, you must first create import libraries from the .def files in the lib subdirectory, for example:

c Airbus Defence and Space 685 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

lib /DEF:c:/eurosim/lib/libes.def lib /DEF:c:/eurosim/lib/libesClient.def

The above commands create libes.lib and libesClient.lib, which you can use to link your client application with. Make sure that the DLL’s can be found on the PATH before you execute your client application.

686 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 33

TM/TC Link reference

33.1 Introduction

With EuroSim the possibility exists to model a telemetry/telecommand link at run time either between two sub-models within a EuroSim simulator, or between EuroSim and another (external) computer. The main feature of this library is to simulate the bandwidth and time-delay that characterize a long- range communication link, such as the TM/TC link between a ground station and a satellite. By default this delay is disabled and packets are forwarded without any delay. Note that the TM/TC link interface is included in the C++ Batch interface (see Chapter 30) which for external clients may be a preferable interface for setting up and establishing the TM/TC connection. The TM/TC mechanism uses a central server process running within EuroSim, via which the two termi- nators (or clients) can communicate. The server can maintain one or more client-to-client links; links are bidirectional and can be established between any two internal clients or between an internal and an external client. For the latter, use is made of TCP/IP. No link can be established between two external clients. EuroSim has the flexibility to handle any data structure as a packet: “packets” do not have to be compliant with ECSS PUS [Sec03] standards in order to be sent and received over the TM/TC link. An ECSS PUS support library to pack and unpack PUS packets however is included with EuroSim. In Figure 33.1a schematic of a TM/TC link between an external simulator and a EuroSim simulator is provided.

Ground Station OnBoard Thermal Model (EuroSim) ethernet Input Process Process cmd(s) TC TC TC packets Ground station commands

Thermal Operator Control Model

Temperature readings Display Process Process data TM TM TM packets

Figure 33.1: External TM/TC Link Schematic

In the case of an internal TM/TC link, i.e. between two or more sub-models within an EuroSim application, the link needs to be set up, customized and then used.

In the case of an external TM/TC client, the only difference is first to connect the external client over TCP/IP to the EuroSim server. Then the setting up and use of the link uses exactly the same routines. The

c Airbus Defence and Space 687 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

EuroSim routines are intended to be usable within a heterogeneous environment, and should be suitable for any UNIX based simulators.

33.2 Characteristics of the TM/TC Link

Various characteristics of the link can be changed by calling esimLinkIoctl to customize the transmis- sion of packets: some of the possible arguments for esimLinkIoctl are:

• LINKDELAY integer: sets the delay of the packages to the given number of milliseconds;

• LINKDELAYPROC procname: the given function will be called for each time a new package is put on the link with the call link_write(). Its return value is used as the delay for the given package. The arguments it gets are the Link identifier for which the delay is requested, and the last delay returned by this function for this Link;

• LINKBANDWIDTH integer: indicates the number of bytes which can be sent over the link per second. A negative number indicates ‘Unlimited’ (default) and will pose NO extra delay. When this value is set to 100, and 200 bytes are sent over, the package will take 2 seconds + the LINKDE- LAY to arrive at the other side. Note that the package will arrive as a single entity and therefore will not be visible (and cannot be read) as long as the complete package has not arrived;

• LINKMAXTIME PENDING integer: indicates how many milliseconds data may be overdue in the queue before it is discarded. When a value less than zero is given, the packages will never be discarded (default).

The esimLinkIoctl procedure can be called at runtime, so can be used to introduce a variable delay time, for example in order to mimic an elliptical orbit or to simulate communications with a set of ground stations where the delay time is a function of the current location of the satellite.

Both TM/TC clients can set their own characteristics so that the upward and downward links can differ accordingly.

The esimLink manual page or [MAN18] provides more information on creating and customizing TM/TC links.

33.3 Summary of procedure

The following steps summarize how to set up and use a TM/TC link between two simulated stations:

1. If one of the simulators is external to EuroSim, set up a connection to the EuroSim server;

2. Create and customize the link between the two clients;

3. Send packets;

4. Receive packets;

5. Close the link.

33.4 Case study: setting up a TM/TC link

This section provides examples of how the procedure is implemented. The examples are taken from complete demonstration models (installed in $EFOROOT/src/TmTc+ExtSimModel).

688 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

33.4.1 Set up the external simulator as a EuroSim client

This only needs to be done if one of the clients for the TM/TC link is not a EuroSim application. The external simulator is firstly linked to the EuroSim simulator as a client. #include tmtcClient = extConnect(hostname, clientname, eventHandler, userdata, async_flag, prefcon); and takes the arguments:

• hostname: simulator host running target EuroSim simulator;

• clientname: name by which this client is to be known to the EuroSim server, e.g. “TMTC Client”;

• eventHandler: name of procedure in external simulator code which will process events coming from EuroSim simulator (flags indicating data updates and state changes are received as “events”)

• userdata: pointer to user defined data. This pointer is passed to the eventHandler callback function.

• async flag: flag to indicate that on incoming data the eventHandler callback function is to be called via a signal handler. If the flag is set to false, the user must call extPoll() whenever data arrives or periodically.

• prefcon: preferred connection on the EuroSim server; should be used to select between simulators when more than one is currently active on the server (default of 0 is sufficient if only one simulator is active)

33.4.2 Create and customize a link between the two TM/TC clients

The next step is to establish a (simulated) TM/TC link between the two “systems”, i.e. either between the external client and EuroSim, or between two sub-models within a EuroSim application. In both cases, the link is set up and used in almost the same way. The link needs to be created on both sides with esimLinkOpen. The function esimLinkOpen will initialize a link with the supplied name. A point-to-point link is not established until the other side has also called esimLinkOpen with the same link name. The pointer returned by esimLinkOpen(e.g. tmtcLink in the following example) is used as an identifier for the link in all future calls, e.g. read, write, close. An external client needs to call esimLinkConnect() to connect the link to the simulator. Various options can be set using esimLinkIoctl(see Section 33.2). In the first example here, the link for the ground station is set up and customized to “lose” packets if they arrive after a certain time delay: #include

#define TMTC_CONNECTION_NAME "tmtc_connection" #define REQ_FREQUENCY 10 static int gFrequency = REQ_FREQUENCY; static void do_client(int signal) { ..... tmtcLink = esimLinkOpen(TMTC_CONNECTION_NAME, "rw"); esimLinkIoctl(tmtcLink, LINKMAXTIME_PENDING, (1000/gFrequency)+100); ..... }

The following lines from the SpaceStation model give an example of setting up the link and using esimLinkIoctl to set the default delay for packets being transmitted:

c Airbus Defence and Space 689 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

#include "esimLink.h" #include "esim.h"

#define TMTC_CONNECTION_NAME "tmtc_connection"

int requiredDelay = 300; /* msec delay for link to ground */

void tmtcInit(void) { .... tmtcLink = esimLinkOpen(TMTC_CONNECTION_NAME, "rw"); if (tmtcLink == NULL){ esimMessage("Couldn’t establish TmTc Link"); return; /* Nothing possible */ } esimLinkIoctl(tmtcLink, LINKDELAY, requiredDelay); .... }

33.4.3 Sending packets

The packets are sent using esimLinkWrite, providing arguments for the link identifier, the data packet buffer, and the size of the buffer; e.g.: send_packet(packet);

static int send_packet(EGSE_uns8 *pus) { PUS_P_Header *header;

header = (PUS_P_Header *)pus; return (esimLinkWrite(tmtcLink, (char *)pus, header->Packet_Length + PUS_P_HEADER_SIZE)); }

The packet is then available for the “other” client to read after a certain time delay, the length of the delay being dependent on the characteristics defined by esimLinkIoctl.

33.4.4 Receiving packets Internal Client In the example code for the EuroSim SpaceStation application model, a task is created which is scheduled at 5 Hz, and which calls a procedure which reads the (incoming telecommand) packets. The actually reading of the packets is done using esimLinkRead, the information being put into tmtcPacket. The return code ret is used to check on the success of the read: #include "esim.h" #include "esimLink.h"

#define PUS_P_HEADER_SIZE (sizeof(PUS_P_Header)) #define PUS_DATA_SIZE 512

static EGSE_uns8 *tmtcPacket = NULL;

void decodeTelecommand (void) { int ret; ......

690 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

ret = esimLinkRead(tmtcLink, (char *)tmtcPacket, PUS_P_HEADER_SIZE + PUS_DATA_SIZE); if (ret <= 0) { if (ret < 0) { /* incoming package is bigger than allocated data area */ esimMessage("Fatal: TmTc command too big to read"); } /* value of zero means no data to read */ return; } PUS_P_Decompose_Packet_Header(tmtcPacket, &VersionNumber, &Type, &DataFieldHeaderFlag, &ApplicationProcessId, &SegmentationFlags, &SourceSequenceCount, &PacketLength); .... }

External Client - polling for packets An external client has two possibilities to get packets. The first is to use the polling method as described above, i.e. regularly calling esimLinkRead to check if there are any incoming packets available. In the Ground Station TM/TC example code, incoming telemetry packets are checked for at 10Hz: #include "esimLink.h"

#define REQ_FREQUENCY 10 static int gFrequency = REQ_FREQUENCY; startTimer(gFrequency, do_client); static void do_client(int signal) { char buf[BUFSIZ]; int n; ..... n = esimLinkRead(tmtcLink, buf, BUFSIZ); if (n != 0) { browse_pus(buf, n); } ..... }

External Client - event driven response Alternatively, use can be made of the events which are sent from the EuroSim server to the client to trigger a response directly as a result of an incoming packet. After extClientConnect or evcConnect has been called (see Section 33.4.1), the client automatically receives events signalling new link data (event-> type of evLinkData). These incoming events are passed to the procedure which was specified as part of the connect call. In this example, this facility is not used, but an action to do something with the incoming packet could easily be defined in the client’s eventhandler (e.g. replacing the DEBUGSTR statement in the following extract): static int eventHandler(Connection *conn, const evEvent *command, void *data) { switch (evEventType(command)) { case evShutdown:

c Airbus Defence and Space 691 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

fprintf(stderr, "\nServer sent abort()\n"); cleanup(0); case evLinkData: DEBUGSTR(("Incoming data")); break; default: DEBUGSTR(("Incoming unknown event ‘%d’", evEventType(command))); } return 0; }

33.4.5 Close down link If one of the clients is an external simulator, then the appropriate disconnect should be called (depends on which version of connect was used at the beginning (see Section 33.4.1): #include

extDisconnect(sim);

Then the TM/TC link can be closed: #include "esimLink.h"

esimLinkShutdown();

692 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 34

COM Interface reference

34.1 Introduction

The EuroSim COM interface allows Windows scripting clients, such as Visual Basic for Applications (VBA) supported by MS-Excel, to launch and/or connect to an EuroSim simulator and control this sim- ulator from your client application.

34.2 Installation

34.2.1 VBA When you plan to use this interface only with VBA, then you only need to install the esimcom.dll (the actual component) and esimcom.tlb (the type library). If you have an installation of EuroSim for Win- dows, then these files have already been copied for you. If you want to use your own client applications on a PC that does not have EuroSim installed, then you can manually install the COM interface: • Copy the esimcom.dll and esimcom.tlb files from the EuroSim bin subdirectory to an appropriate directory (this can be the system directory, usually C:\windows\system32). • Copy the files pthreadGC.dll and oncrpc.dll to the system directory, if they are not installed on the target system yet (you can find these files in the system directory of a system that has EuroSim for Windows installed. • Open a command shell and go to the directory where you just copied the two files. • Type the following command at the prompt: regsvr32 esimcom.dll

followed by the Enter key.

34.2.2 C++ When you plan to develop C++ clients, then you need the esimcom.h (the header file) and the esim- com if.c files in your development environment. Copy those files from the EuroSim include directory into an appropriate directory and make sure you add an include path to the esimcom.h file. The esim- cim if.c file should be compiled and linked in with the other files of your client program. If you get errors at compile time about MIDL versions, you may need to use the esimcom vc6.h header file instead of esimcom.h.

34.3 Programmers reference

The complete reference is installed as HTML pages in the doc subdirectory of the directory where Eu- roSim is installed. For background information on COM/DCOM programming, see [COM98].

c Airbus Defence and Space 693 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

34.4 Use case – Excel example

In this chapter we will guide you through the EuroSim COM interface by means of a use case. We have a simulation, which is kept very simple for demonstration purpose and a client application, based on Microsoft Excel and Visual Basic for Applications, which will launch the simulator, monitor the state of variables in the model code of the simulator, monitor wallclock time, simulation time and the state of the simulator. As a last example, the client will change the value of the variables in the model code.

34.4.1 The simulator First we build the simulator from the src/com/counter directory. Start up the EuroSim project manager (either double click the EuroSim icon on the desktop or run esim from the command line). You may want to refer to the approriate section of the SUM if you are not yet familiar with the following steps:

• Create a project called ‘Counter’ and give it a directory.

• Copy the files from the src/com/testsim directory into your project directory.

• Add the Counter.sim and Counter.model files to the project.

• Double click the Counter.model file in the project manager and build (F8 key) the simulator with the Model Editor.

• Double click the Counter.sim file in the project manager and run the simulator by clicking the ‘Init’ button of the Simulation Controller. If all went well, you should see some messages in the log window of the Simulation Controller indicating that the simulation is running.

• Stop the simulation by clicking the ‘Stop’ button of the Simulation Controller.

At this point we have a working simulator, which we can use to test the MS Excel based client application.

34.4.2 The MS Excel client application We create the MS Excel client application in a couple of steps. Open a new MS-Excel sheet and open the Visual Basic (VB) editor: Menu: Tools:Macro:Visual Basic Editor. Open the references dialog box in the VB editor: Menu: Tools:References. . . and check the box in front of the ‘EuroSim SimAccess Type Library’, see Figure 34.1. Press the ‘OK’ button of this dialog to accept the changes and close the dialog.

Figure 34.1: Adding a reference to the EuroSim type library

Now we will add a declaration that creates an instance of the EuroSim COM interface. Create a new module by right-clicking the VBAProject tree and selecting Insert:Module. Then type the following in the code section of the new module:

694 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Public Sim As New EuroSim.SimAccess

Your VB editor should now look similar to Figure 34.2.

Figure 34.2: Declare an instance of the interface

Go back to the Excel sheet and make sure you have a ‘Control Toolbox’ toolbar, see Figure 34.3 (if not, goto menu: View:Toolbars and check the ‘Control Toolbox’). Place a command button on the sheet and change its name to ‘Init’ (right click the command button and select: CommandButton Object:Edit). Hit the Esc key on the keyboard and double-click the command button. Enter the following code in the CommandButton1 Click subroutine:

Private Sub CommandButton1_Click() On Error Resume Next Sim.Launch "localhost", "C:\mysims\Counter", _ "Counter.sim", "TestClient", 0 If Err <> 0 Then MsgBox ("Error: " & Err.Description) Else [A5].Value = "Launch successful" End If End Sub

Instead of ”C:\mysims\Counter” for the working directory, you should fill in the path that you used when creating the simulator project, i.e. the directory where the Counter.sim and Counter.model files are located. In a similar way add the ‘Go’ button with the following code:

Private Sub CommandButton2_Click() On Error Resume Next Sim.Go If Err <> 0 Then MsgBox ("Error: " & Err.Description) Else [A5].Value = "Started" End If End Sub

And a ‘Stop’ button with the following code:

Private Sub CommandButton3_Click() On Error Resume Next Sim.Abort If Err <> 0 Then

c Airbus Defence and Space 695 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

MsgBox ("Error: " & Err.Description) Else [A5].Value = "Stopped" End If End Sub

Your client should now look similar to Figure 34.3.

Figure 34.3: The basic test client

The client is ready for a first test. Leave design mode (the left-most button on the Control Toolbox tool- bar), click the ‘Init’ button and wait for the text “Launch successful’ to appear. You can also verify that the simulator is running by executing the efoList utility from the command line, see Section 24.12.1. Click the ‘Stop’ button in the Excel sheet to stop the simulator. The Windows Application Event Log may give you a clue in case you encounter problems.

34.4.3 Adding a View The example simulator has been build with the ‘External Simulator Access’ build option set in the Model Editor. This means that at simulator startup a .exports file, with the same basename as the simulator, will be searched for. This file specifies which nodes of the data dictionary will be available for reading and writing using so called ‘views’. More information can be found in the extExport(3) man page. The Counter.exports file looks like this:

696 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

/Counter readview R /Counter writeview W

This means that all variables in the /Counter node — the Counter.c file — are available for reading when a view is created with the name “readview” and they can be written when using a view that was created with the name “writeview”. The following paragraphs describe how to create views in the MS Excel based client application. Go to the VB editor and double click ‘Module1’ in the VBAProject tree. Add the following lines to the declarations:

Public ReadView As EuroSim.IvarView Public dCounter As Double

Then add a ‘Create View’ button with the following code:

Private Sub CommandButton4_Click() On Error Resume Next Set ReadView = sim.CreateVarView ("readview") If Err <> 0 Then MsgBox ("Error: " & Err.Description) Else ReadView.AddDouble "dCounter", dCounter ReadView.Connect EuroSim.Read, 10 End If End Sub

That is all the code needed to have EuroSim copy the value of simulator variable ‘dCounter’ to the client variable ‘dCounter’. The updates will occur at a frequency of 10 Hz. Now we want to display the value of ‘dCounter’ in a cell of the sheet. We could add a button that invokes some code that copies the value of ‘dCounter’ into a cell, but there is a more sophisticated means to achieve this, which is described in the next paragraphs.

34.4.4 Receiving updates from the simulator So far, the client has been calling the methods on the simulator interface of the EuroSim component. This is depicted in Figure 34.4.

Figure 34.4: Client calling methods on the ISimulator interface

If the client application wants to keep track of changes in simulator variables, it could simply poll. However, if this is done from VBA code in, for example, an Excel spreadsheet, the complete Excel application would not be responsive to user input while polling. To solve this problem, the EuroSim COM interface provides an event callback mechanism. Note that the client application has to implement an interface that the EuroSim component makes calls on. However, the EuroSim component specifies this interface in the type library. Since the component is the source of the calls on this outgoing interface, this interface is called a source interface. The client is called the sink for calls on this interface. The next paragraphs describe how to set-up a sink, or event handler, in VBA.

c Airbus Defence and Space 697 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Figure 34.5: Component calling methods on the client interface

34.4.5 Creating an event handler in VBA Right click the VBAProject tree and Insert:Class module. Select the new class and press F4 to display the properties window. Rename the class to ‘EsimEventClass’. Enter the following declaration in the code window of the new class:

Public WithEvents Simulator As EuroSim.SimAccess

This will declare an object named Simulator as an instance of the EuroSim.SimAccess class. The WithEvents statement tells VB that it receives events. At the top of the code window, there are two drop down edit boxes. In the one on the left, select Simulator from the list. Since there is only one method, Changed, the VB editor automatically creates a subroutine called ‘Simulator Changed’. Add the following line to this new subroutine:

If Reason = VarChanged Then [A6].Value = dCounter End If

The above line of code writes the value of ‘dCounter’ to cell A6 on the sheet, each time the interface notifies our client that something has changed in the external simulator. Your VB editor should look similar to Figure 34.6.

Figure 34.6: Creating an event handler

We also need an instance of the event class: select ‘Module1’ and add the following line

Public EsimClass As New EsimEventClass

to the global declarations so that it looks like the code below:

Public sim As New EuroSim.SimAccess Public ReadView As EuroSim.IvarView Public dCounter As Double Public EsimClass As New EsimEventClass

The last step is to install the sink. Go to the CommandButton1 Click subroutine and add the following line

698 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Set EsimClass.Simulator = sim so that it looks like the code below:

Private Sub CommandButton1_Click() On Error Resume Next sim.Launch "localhost", "C:\mysims\Counter", _ "Counter.sim", "TestClient", 0 If Err <> 0 Then MsgBox ("Error: " & Err.Description) Else [A5].Value = "Launch successful" Set EsimClass.Simulator = sim End If End Sub

34.4.6 Sending updates to the simulator This chapter will help you to modify your Excel application so that when you modify cells on your worksheet, these modified values are sent to the EuroSim simulator. First, we need a view with write permissions. Add the following declarations to Module1:

Public WriteView As EuroSim.IvarView Public newCounter As Double

Then add the following code to the CommandButton4 Click (CreateView button) subroutine:

Set WriteView = sim.CreateVarView("writeview") If Err <> 0 Then MsgBox ("Error: " & Err.Description) Else WriteView.AddDouble "dCounter", newCounter WriteView.Connect EuroSim.Write, 0 End If

The above code creates a relation between the local variable ‘newCounter’ and the simulator variable ‘dCounter’, which we monitor using the readview. Excel Worksheet and Workbook level events are contained by the Worksheet and Workbook objects, respectively. However, there is no similar object to contain the Excel Application level events. Therefore you must use a Class Module to create an object that can accept and handle Application level events. Open the VB Editor, and choose Class Module from the Insert menu to create a new Class Module. Select the class module and insert the following statement as a global declaration:

Public WithEvents App As Application

This will declare a variable named App as an instance of the Application class. The WithEvents statement tells Excel to send Application events to this object. At the top of the code window, there are two drop down edit boxes. In the one on the left, select App, and in the one on the right, select the SheetChange. The VB editor will automatically insert the Private Sub and End Sub statements into the module. Add the following code to the app SheetChange event handler:

c Airbus Defence and Space 699 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

On Error Resume Next Application.EnableEvents = False If Target.Address = "$B$6" Then newCounter = Target.Value WriteView.Send If Err <> 0 Then MsgBox Err.Description End If End If Application.EnableEvents = True Each time cell B6 is changed, i.e. the user types a value, its value is copied to the variable called newCounter. This value is sent to the simulator variable ‘dCounter’ using the Send method on the WriteView object. Press F4 to display the Properties window, and change the name of the class module to EventClass, see Figure 34.7.

Figure 34.7: The application event handler

Next, add the following line Public AppClass As New EventClass to the global declarations in Module1 so that it looks like the code below: Public sim As New EuroSim.SimAccess Public ReadView As EuroSim.IvarView Public WriteView As EuroSim.IvarView Public dCounter As Double Public EsimClass As New EsimEventClass Public AppClass As New EventClass This will create an object called AppClass as a new instance of EventClass. In order to receive application events, the App variable of the AppClass object must be set to the actual Excel application. One place to do this is in the CommandButton1 Click subroutine, using the following statement: Set AppClass.App = Application Your VB editor should now look similar to Figure 34.8. The MS Excel based client application is ready for another test. Leave design mode, launch the simulator, create the views and type a numeric value in cell B6. After pressing the Enter key, the application event handler will be called, which will send the value of cell B6 to the simulator.

700 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Figure 34.8: Setting the AppClass.App

c Airbus Defence and Space 701 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

702 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part VI

Embedding Reference Guide

c Airbus Defence and Space 703

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 35

Loadable EuroSim

35.1 Introduction

Loadable EuroSim focusses on providing a shared library (or dynamic link library) rather then an exe- cutable. By providing a shared library rather than an executable it becomes possible to embed EuroSim into any application either by linking or by dynamic loading of the library. The complete EuroSim functionality is then available in the context of the application that loads EuroSim. Additionally an in- terface is provided to slave the EuroSim scheduler to a scheduler in the base application to allow forms of co-simulation. A use-case for loading EuroSim as library is the typical co-simulation in a Software Validation Facility (SVF). Such facility combines an emulation of an onboard computer running the ”flight” software against a simulated environment that contains the models of equipment, dynamics and environment. The onboard computer model is often a given input to the establishment of an SVF. Several forms have been seen in projects: an executable with a socket connection, a library that can be loaded in another simulator, or an environment where it is feasible to extend the simulation by a programmer. In the first case a connection via external simulator access was used with EuroSim. In the second the library was linked to a EuroSim simulator and interfaced directly with the models. The third case now can be solved by loading EuroSim in the context of the emulator as a shared library. A major benefit of being able to load EuroSim in another environment is that the same simulator can be used both as a model in another simulator environment for an SVF and as a standalone solution as EGSE. This re-use of the simulator in its entirety means that validation is only performed once and the SVF and EGSE results can be easily compared, which is a major benefit in test compaigns.

35.2 Interface

The architecture of a loadable solution is not that different of EuroSim in its standard executable form. Building of the shared library requires only the selection of the option in the ModelEditor. When selected both the executable (.exe) and shared library (.so / .dll) are produced. The programmer has the option to either link the produced shared library to his executable or to use runtime loading as available through the dlopen function on Linux. The main difference is that with the first option all the sybols of EuroSim are exposed, whereas in the second approach the programmer can define which symbols of the EuroSim API should be exposed in the context of his application. A loaded EuroSim provides the programmer with the API to start EuroSim as if it was started from the commandline, that is there is a function that requires the same input: int esimMain(int argc, char *argv[]); where

c Airbus Defence and Space 705 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

-argc is the number of commandline options -argv is the array of commanline options following the argopt functionality \end

This approach is fully compatible with the commandline interface for EuroSim documented in Appendix @. A complete parametrisation is possible for all files and options used by a EuroSim simulator. Addi- tionally, when started, the library registers itself with the daemon such that a Simulation Controller can be connected. All abilities with respect to controlling the EuroSim simulator are supported: variables can be monitored and set, scripts can be started and the mmi’s show a graphical representation. To slave the scheduler, an esimTick function is provided. In the schedule file the clock source should be set to esimTick, which will slave the EuroSim clock to the esimTick call. When esimTick is called the scheduler will execute one minor cycle and block wiating on the next esimTick call. The application developer that loads EuroSim as a library must thus implement the master clock that calls esimTick.

706 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Chapter 36

Embedded EuroSim

36.1 Introduction

Embedded EuroSim is designed for those situations where EuroSim is integrated in an embedded envi- ronment. Typically such environment has limited resources and does not have the same interactive usage by the end-user as offered through the EuroSim Simulation Controller. Rather an application is devel- oped once as a combination of the Embedded EuroSim core and models and subsequently integrated with the target environment in the embedded system. The end-user will often not even be aware of EuroSim running inside the system. The major benefit of Embedded EuroSim may not be visible to the end-user but applies to the developer. Development of an Embedded EuroSim application is performed in the normal Embedded EuroSim environment with all services of EuroSim available. This makes development of the application a lot easier, particularly to a team of developers and testers on a single EuroSim server. The developers have the Simulation Controller and services of EuroSim available which provide a good insight into the running application. The testers write the test scripts in the EuroSim batch script language of choice to verify the models. A cross build setup builds the target image and executes this on the target platform. Typically the target is a scarce resource, only one may be available. In the Embedded Training application by Airbus and NLR the cross build was performed every night and the setup allowed the same test scripts to be applied against the target as against the host (see paper ”Application of EuroSim in the F-35 Joint Strike Fighter Embedded Training solution” available in the Support section of the EuroSim website). An embedded environment requires a smaller footprint, typically has no need or no capability to load configuration files. Furthermore the operating system and compiler may have a large number of restric- tions and specific interfaces related to certification and safety critical applications. Embedded EuroSim therefore includes a number of specific versions the components of the normal EuroSim distribution which focus on the execution of the models in an embedded version. In addition the configuration files such as a schedule file are no longer read on startup, but compiled into the target application. The development of Embedded EuroSim started with support for the PharLap OS (discontinued). The development continued with support for GreenHills Integrity 178B and Linux. There has not been a demand for embedded windows solutions, but such supported can be added (in fact PharLap OS followed a Win32 API). Prior to starting with Embedded EuroSim we suggest to contact the EuroSim helpdesk to analyze the compatibility of the available solutions and ability to extend EuroSim to match your environment. Embedded EuroSim has the design to be easily embedded, but the variations in target environments are large. Embedded EuroSim is available and used actively on the following operating systems:

• GreenHills Integrity 178B for Freescale 8548e with board support package cds8548

• Red Hat Enterprise Linux (compatible) 6 for i686 and X86 64

• Suse SLERT 11.3 x86 64 (based on RHEL6 Compatible built environment)

c Airbus Defence and Space 707 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

36.2 Architecture

This section show the architectural difference between a normal EuroSim, and Embedded EuroSim. The default Eurosim architecture assumes a Linux or windows host with a full array of input/output support available (See Figure 36.2).

Figure 36.1: Default EuroSim Architecture

Embedded EuroSim makes no assumptions about availability for input/output devices (disk, network) like standard EuroSim (see Figure 36.2).

Figure 36.2: Generic Embedded EuroSim Architecture

Hardware in the Loop (see Figure 36.2) is not supported by Embedded EuroSim. This may seem strange as embedded software is often used to control hardware. However, the target platforms for a Embedded EuroSim will vary such that it is impossible to include the Hardware in the Loop in Embedded EuroSim. Instead an IO-adapter is created that isolates Embedded EuroSim from the hardware under control.

708 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

36.2.1 Embed Data Files As Embedded EuroSim makes no assumptions about availability for input/output devices all required input files needs to be embedded into the Embedded EuroSim application executable during the build process of a Embedded EuroSim application. For an Embedded EuroSim application the following input files needs to be embedded:

• data dictionary (.dict)

• schedule (.sched)

• configuration (.cfg)

$EFOROOT/embedded//bin includes a script (esim_embed_files) that em- beds these files in a way that is expected by Embedded EuroSim. It creates a C-source file that must be compiled and linked with the Embedded EuroSim application. The data dictionary file is the dict-file of the application, the schedule file is the sched-file of the application. An example configuration file is included in

$EFOROOT/embedded//src/EmbedFiles

36.2.2 IO Adaptor: Shared Memory For external communication with a Embedded EuroSim application the IO adaptor is typically imple- mented in the form of shared memory areas that is accessible to the Embedded EuroSim application and accessible to a platform specific application that is aware of the platform specific IO devices (network, fibre channel, ...). The functionality to the set-up and use of shared memory areas is NOT included in the Embedded EuroSim libraries. However, example source code is included in

$EFOROOT/embedded//src/SharedMemory

That folder provides example source code that implements:

• functions to create and use non blocking message queues (ring-buffers) in a shared memory seg- ment to allow communication between a single server and single client. These functions are avail- able in SharedMemory.c.

• functions that sets-up two shared memory segments: an admin area that can be used to contain information about the shared memory queues a data area that can be used to contain the queues. These functions are available in SharedMemoryRegion.c.

– On GreenHills Integrity 178B the shared memory segments are created from information that is retrieved from an Integrity 178B integrate file that defines Integrity 178B memory object numbers that can be translated into memory addresses. – On Linux the shared memory segments are created by means of shared memory segments provided ny Unix System V inter-process communication support (ipcs). Here the shared memory keys needs to be defined taking other applications running on the same computer that also use ipcs keys into account.

Note that the example source code mentioned above serves as example only: source code that can be used to develop a local implementation. The provided example source code has been derived from a compiled, tested, and used version. The provided version is not compiled, tested, or used.

c Airbus Defence and Space 709 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

36.3 Configuration File Settings

One of the files that needs to be provided as an embedded data object in a Embedded EuroSim application is the configuration of Embedded EuroSim. As mentioned earlier the two other files that needs to be provided as embedded data objects are the dictionary and schedule files. These files are the standard EuroSim dictionary and schedule files. The configuration file provides two Embedded EuroSim specific settings:

• heap_size

• partition_idle_time

Lines in the configuration file that start with a # are considered as comment line and are ignored.

36.3.1 Heap Size The heap_size is a configuration parameter that is used in the Integrity 178B and in the Linux versions of Embedded EuroSim. The heap_size defines the amount of heap memory that is available for the Embedded EuroSim application to be used in malloc / free and new / delete calls. Note that the heap_size should be set lower than the amount of memory available (based upon the amount of physical memory taking into account the amount of memory used by the operating system, shared memory, other applications and the executable size of the Embedded EuroSim application). Note that many embedded operating systems do not provide a clear error message (if any) if the amount of memory requested exceeds the amount available. The setting must be calculated carefully in advance. The heap_size parameter is used when Embedded EuroSim starts to allocate that amount of memory. Subsequent malloc, free, new, delete calls use memory from that allocated memory to provide heap memory to the application and to release it for subsequent use. The heap_size parameters is defined in bytes.

36.3.2 Partition Idle Time The partition_idle_time is a configuration parameter that is used in the Integrity 178B version of Embedded EuroSim only. Integrity 178B uses a partition scheduler that swaps the execution of partitions. Embedded EuroSim runs as a partition in the Integrity 178B scheduler. A partition receives a signal when it becomes activated, but is unaware of the fact that it becomes inactive. Therefore the partition is unable to determine the amount of time that passed while it was inactive. This information is provided as the partition_idle_time is a configuration parameter. The master clock of Embedded EuroSim runs at a frequency of 60 Hz which is synchronized with the partition scheduler frequency defined in the Integrity 178B integrate file. Based on this frequency the partitions have a total time of 16.666 ms to execute. The partition_idle_time defines the amount of time that passed between two subsequent Embedded EuroSim partition activations. In the example configuration file $EFOROOT/embedded//src/EmbedFiles/esimEmbedded.cfg

the partition_idle_time is defined as 0.0066666 which defines that of the amount of time be- tween two activations of the Embedded EuroSim partition, 6.6666 ms has been spent on other partitions. This means that while the wallclock has advanced 16.6666 ms, the measurements of Embedded EuroSim should be based on a corrected amount of time (16.6666 ms - 6.6666 ms = 10 ms) the partition has really been active. The partition_idle_time parameters is defined in seconds.

710 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

36.4 Initialization

Embedded EuroSim initialization ends with a call to esimCppSetup that needs to be implemented in the Embedded EuroSim application. Embedded EuroSim initialization includes reading the embedded data files, allocation of the heap memory with the configured size, data dictionary initialization and schedule initialization. Once esimCppSetup completes its processing (typically the publication of Embedded EuroSim appli- cation objects and functions to be called from the schedule) Embedded EuroSim starts the master clock and starts the execution of the init part if the schedule.

36.5 Error and Message handling

As Embedded EuroSim does not provide an IO interface textual output of the standard message, warning and error interface (esimMessage() the facility of an output handler is provided. This handler is respon- sible to channel the message through the IO adapter provided for the operating system (typically through a queue in a shared memory area). Messages that are generated by EuroSim before a handler is installed are buffered and flushed by means of the handler as soon as it is installed. The API for the output handler follows the definition of standard EuroSim messages: typedef int (*esimEmbeddedOutputCallback)(esimSeverity severity, struct timespec runtime, struct timespec simtime, char *message); void esimEmbeddedInstallOutputCallback(esimEmbeddedOutputCallback callback);

36.6 Embedded API

Embedded EuroSim has a slightly different API than the C- and CPP-API EuroSim provides. Prototypes of the functions that Embedded EuroSim provides can be found in

$EFOROOT/embedded//include/esim.h

This file contains the esim... functions provided by Embedded EuroSim. Note that esim.h includes esimEmbedded.h from the same folder. The latter provides prototypes of Embedded EuroSim specific functions (esimEmbedded...) that are not part of the regular EuroSim C- and CPP-API.

36.7 Compilation and Linking of Embedded Applications

When developing Embedded EuroSim application the embedded operating system specific include folder must be added to the compilation flags:

-I$EFOROOT/embedded//include

Besides libraries required for the Embedded EuroSim application, the link command shall also include the esimEmbedded library:

-L$EFOROOT/embedded//lib -lesimEmbedded

Examples of Embedded EuroSim application specific libraries are:

• The shared memory library that support the creation and use of shared memory segments and queues based on the example source code provided.

c Airbus Defence and Space 711 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• Libraries with algorithms

Notes with respect to Integrity 178B linking:

• A main.o needs to be included in the link command. From the main function in that main.o file a call must be made to esimEmbeddedStart. Opposed to regular EuroSim the Integrity 178B operating system requires a main function to be able to create a partition for the Embedded EuroSim application.

• The Integrity 178B operating system and the Embedded EuroSim application partition (and other partitions) are loaded onto the target computer as an integrated image. The integrate file defines the partitions, the memory configuration, process identifiers, etc.

• The partition_idle_time and heap_size settings must be consistent with contents of the integrate file.

712 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Part VII

Appendices

c Airbus Defence and Space 713

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix A

Files and formats

In this appendix an overview is given of the various files which are used and created by EuroSim. Also, for a number of files, their format is given.

A.1 EuroSim project files

In this section, each of the files which can be part of a EuroSim project is described briefly. Files used in a project can be identified by their extension:

Extension(s) Short description adb Ada body source file. ads Ada spec source file. alias Alias file. c C source file. cc, cpp, C C++ source file cal Calibration file.

cat SMP2 catalog(ue) file.

dict Data dictionary; this derived file contains all API information for the simulator. It is generated by the Model Editor. env Environment description file EsimJournal.txt Human readable journal file; this file contains the logging of a simulation run. EsimJournal.xml Machine readable journal file; this file contains the logging of a simulation run. esb EuroSim SMP2 assembly file. exe Simulator executable; this derived file is generated by the Model Editor. exports Exports file; contains variable nodes exported to simulation clients. f, F Fortran source file. h C header file. init Initial condition; this file contains initial conditions for a simulator. It is generated by the initial condition editor, which is integrated in the Simulation Controller. java Java source file make Model makefile; this derived file controls the model building and is generated by the Model Editor.

c Airbus Defence and Space 715 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Extension(s) Short description md Model Description file; Describes which variables of a model should be copied to the datapool. To edit a model description file, start the Model Description Editor (from the Model Editor).

mdl Scenario file; this file contains an MDL scenario containing monitor (obsolescent), recording and stimuli definitions. It is generated by the Simulation Controller.

mmi Man-Machine Interface definition; this file describes the contents of an MMI tab page in the Simulation Controller. The contents consists of one or more monitors. This file replaces the use of monitors in the scenario (mdl) file. model Model file; contains all components for a simulator. To edit a model file, start the Model Editor. plt TestAnalyzer file; contains plot descriptions. To edit a plot file, start the Test Anzlyzer. px Parameter Exchange file; Describes exchanges of data in the datapool. To edit a parameter exchange file, start the Parameter Exchange Editor. rec Recording file; this file contains data written by recording actions in the corresponding EuroSim scenario. sched Schedule file; contains all timing information for a simulator. The following files are referenced: the model and zero or more Parameter Exchange files. To edit a schedule, start the Schedule Editor. sim Simulation Definition file; contains references to all files needed to create and run a successful simulation. The following files are referenced: the model, the schedule, the optional exports, zero or more scenario files, initial condition files, MMI definitions or User Defined Program files. To edit Simulation Definition, start the Simulation Controller.

snap Snap shot file; this file contains an full image of all API variables of an EuroSim simulator. timings Timings file; contains timings made during a simulation run. Can be imported by the Schedule Editor. tr Test result file; this file contains a list of all recordings performed by the corresponding EuroSim scenario. usr User Defined Program; contains all data necessary to launch a user defined program as client of the simulator.

The tr, rec, timings, EsimJournal.txt and EsimJournal.xml files are stored in directories represent- ing the date and time of the simulation. The exe and dict files are created in a temporary directory that is made up of the basename of the model file and extension of the operating system (f.i. MyModel.Linux). All other files are in user-specified directories.

A.2 EuroSim Configuration file format

Most of the tunable settings of the EuroSim tools are controlled by settings in the system-wide configu- ration file which is stored in the file: $EFOROOT/etc/esim conf. If a user wants to have settings differently from these system-wide settings, he can copy the file $EFOROOT/etc/esim conf to his home directory. At startup, the system-wide configuration file is read first, followed by the user’s configuration file (if available). Please note that a personal configuration file overrides any system-wide settings, so it is best only to include those settings that are actually changed.

716 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The EuroSim configuration file is divided into two sections, the first section contains key-value pairs, the second section contains file type settings. Comment-lines are started with the # character.

A.2.1 Keys Keys are defined with the format:

=

The following keys are currently used by EuroSim: UndoHistory (the number of commands to remember for undo) MakeCommand (the command used to call GNU-make) EuroSimOnlineHelp (location of the help index) ProjectManagerOnlineHelp (location of Project Manager help) ModelEditorOnlineHelp (location of Model Editor help) ModelDescriptionEditorOnlineHelp (location of Model Description Editor help) ParameterExchangeEditorOnlineHelp (location of Parameter Exchange Editor help) CalibrationEditorOnlineHelp (location of Calibration Editor help) SMP2EditorOnlineHelp (location of SMP2 Editor help) ScheduleEditorOnlineHelp (location of Schedule Editor help) SimulationCtrlOnlineHelp (location of Simulation Controller help) TestAnalyzerOnlineHelp (location of Test Analyzer help) MDLOnlineHelp (location of MDL help)

A.2.2 File types

The definition of file types starts after the keyword “FileTypes:”. The format for file type entries:

: : : : \ : ID-string uniquely identifying string description short description of the file type

c Airbus Defence and Space 717 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

extensions the file extensions for the file type (comma separated) editor cmd the command used to edit the file viewer cmd the command used for read-only access to the file icon the icon for the file type

The is mandatory, the other settings are optional. As an example follows an entry for the Simulation Defintion file type: SIM_FILE : Simulation Definition : sim : SimulationCtrl : :

(Note: On the Windows platform, the EuroSim utility “open.exe” can be specified as an editor/viewer command to call the default editor defined under Windows.)

A.3 Recorder file format

The files written by the MDL record command and the files read by the MDL stimulate command both have the same file format. Each file can contain input/output data for a number of variables. The number of variables in a particular file is stated at the beginning of the file. Following the line denoting the number of variables, is a set of lines, one for each variable, stating the variable name, variable type and variable dimension. The field in the header is a basic type as defined in the C language, FORTRAN or Ada.

[Mission: ] [Record size: ] [Dict: ] [SimTime: ] [TimeFormat: relative/UTC] Number of variables: { {}}

Figure A.1: Syntax of EuroSim recording files.

Following these definitions is a set of lines, one for each input timepoint, stating the stimuli data to be inserted, or register data generated-, for each of the variables. The order of the values of the variables is the same as the definitions given for the variables. The files all contain binary data for the records of the variable values. The headers of the files are in ASCII. In Figure A.1 (part of) the syntax definition is shown. When the file is generated by the record command, the first variable/column in the file will always be the simulation time vari- able1. Each invocation of the record command results in one record of variable values (see example in Figure A.2).

Mission: Demo48hr.mdl Record size: 20 Dict: Demo48hr.dict SimTime: /simulation_time TimeFormat: relative Number of variables: 3 /simulation_time: double /BouncingBall/ballF77.f/balf77/ballvar$height: float /BouncingBall/ballC.c/ballC/Velocity: double

Figure A.2: An example of a EuroSim recorder file.

1The variable for the simulation time can be specified by an environment variable.

718 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

The naming conventions for EuroSim recorder files are the following:

• for the files read and processed by the stimulation process any file name can be specified with the MDL stimulate command.

• for the files generated by the recording process a filename can be specified in the MDL record command2, or

• for the files generated by the record command, when no file name is specified in the MDL record command, a file name is generated3 with the name rec-X-1.rec.

A.4 The test results file

The data recording process produces an index file in which all recorded Application model variables names are logged, including the name of the file where their values can be found. In Figure A.2 an example of an index file is shown. This file can be used to get a quick overview/index of the various variables recorded to disk during real-time simulation. It is meant to be used during off-line analysis of the recorded data. The name of the index file is derived from the name of the ready-to-run simulator executable filename. If that is SUM.exe then the index file will get the filename SUM.exe.tr.

Filename Variable SateliteDecayTest.rec /simulation_time SateliteDecayTest.rec /Altitude/altitude SateliteDecayTest.rec /Thruster/thrusterOnOff SateliteDecayTest.rec /Altitude/decaySpeed

Figure A.3: An example of a test results file.

A.5 Exports file format

The exports file describes which part of the EuroSim data dictionary may be accessed by external (non- EuroSim) simulators. For each part that should be accessible for external simulators, one can indicate how it can be accessed (read, write, or both) and by whom. The exports file consists of a number of lines, each line describing one part of the data dictionary that may be exported. Empty lines and lines beginning with # are ignored. Data following a # is considered to be a comment. Each non-empty line has the following layout: path id mode users

Where path is the path to the data dictionary which should be exported, id is the name under which this path should be exported, mode is the operation that can be performed (R, W or RW) and users is a list of clients that may request access. The given path that is exported means that every subtree or variable that is located underneath that path may be requested in a view. A simple way therefore to export every variable is to export the /. The id under which the path is exported is the name which the external simulator must use in his access request. The access mode RW is not yet implemented. However, it is possible to add separate read and write export lines. 2This way registration to a named file, and subsequent stimulation from a named file is possible within the same simulation run. For named registration the user should use record "filename" in MDL, for ”blind“ unnamed registration record suffices. 3Note that when the user changes an action containing registration commands the original registration file produced may be overwritten.

c Airbus Defence and Space 719 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

When no users are specified the export operation is valid for all users. For more information, see also the exports(4) man page of EuroSim, and chapter Chapter 32. Example exports file:

# # Example file # /space/station/era era R /space/stars stars RW /space/rockets/ariane esarocket W

Figure A.4: An example of an export file.

A.6 Alias file format

The alias file defines aliases for variables in the data dictionary. An alias can refer to any variable even if it is an element of a structure or array. The alias file format is line oriented. Empty lines are ignored. Comments start with the # sign. Each non-empty line has the following layout:

alias path

where alias is the alias name of the variable indicated by the data dictionary element path. An alias name must start with an alphabetic character and may be followed by zero or more alphanumeric char- acters or underscores. White space is used as a separator and is not significant otherwise.

# # Example alias file # XCAD1002 /SPARC/ControlStatus XZCY2945 /SPARC/setpoints

a /SPARC/setpoints[2] b_2 /SPARC/setpoints[3][3]

Figure A.5: An example of an alias file.

A.7 Initial Condition file format

The Initial Condition file format is either ASCII or binary. The extensions of these files are .snap or .init. The file consists of a header section and a data section. Empty lines and lines starting with # in the header section are ignored as comment lines. However, when the rest of the line following a # character contains valid keyword/value pairs, it is interpreted. Keyword/value line have the form:

#keyword = value

Valid keywords are: comment the comment that was passed when the file was written. May be omitted.

format either ASCII or binary. When omitted the file is interpreted as being ASCII.

simtime the simulation time at the time the snapshot was taken.

720 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

dict the EuroSim data dictionary file from which this file was written. The path to the data dictionary is relative to the place where it can be found. May be omitted. reference an optional version control reference for the state of the model this file’s data dictionary was generated from.

Any other keywords can be generated by dictdump, or by the user, but they are not interpreted. Every initial condition or snapshot file written by EuroSim also contains a comment line indicating the type of snapshot or initial condition file written. It is either:

# contains only differences wrt dict default values or

# contains all current dict values at which indicates whether it is a partial snapshot (or initial condition) file or a complete snapshot containing all the variables in the data dictionary. When the format of the file is binary there is at least one mandatory empty line following the header. The data section of a binary file contains records for each data dictionary symbol as follows:

{ symbol_length+1, symbol, value_length, value } where the symbols are fully qualified data dictionary paths and the values for the symbols are of course in ’binary’ form (no formatting).

When the format of the file is ASCII the records of the data section look like:

{ "InitialCondition: ", symbol, "=", value }

Again the symbols are fully qualified data dictionary paths, the values for the symbols are formatted. The records may extend several lines but the carriage return ’\n’ is then escaped with a \ backslash, so in there is in principle one record per line. Values of arrays and structures (possibly nested) are grouped using curly braces { and }, identical to the syntax of the C language to initialize those values.

The following example shows a typical layout of a full (ASCII) initial condition file:

# EuroSim initial condition file # version = @(#)Header: dumpfile # dict = thermo.dict # comment = complete ascii dump # format = ascii # contains all current dict values at Mon Jan 27 14:15:24 1997 # InitialCondition: /thermo.f/thermo$celltemp = "{ { 0, 0, 0},\ { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}}" InitialCondition: /thermo.f/initthermo/thermo$capa = "{ { 0,\ 0, 0}, { 0, 0, 0}, { 0, 0, 0}, { 0, 0, 0}}" InitialCondition: /thermo.f/initthermo/thermo$condfac = "0" InitialCondition: /thermo.f/initthermo/thermo$emisfac = "0"

A.8 Simulation Definition file format

The format of the .sim file (and also of the .mmi and .usr files) is a simple keyword-value format: keyword value;

c Airbus Defence and Space 721 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

where value is either a number or a text between double quotes. To embed a double quote in the text you have to prefix it with a backslash. To embed a backslash in the text you also have to prefix it with a backslash. Examples:

foo 1; bar "text example"; escape "quote \" backslash \\";

A keyword can also start a nested set of keyword-value pairs. Example:

nested_keyword { key1 value1; key2 value2; }

The simulation definition file supports the following keywords:

version the version number of the file format

server the server to use for the simulator resultsPath the directory where the result files are stored. createSubDir if 1, then create defaultTab the name of the tab page shown on top /

model start a nested section for a model file. See below for valid keywords. schedule start a nested section for a schedule file. See below for valid keywords.

export start a nested section for an exports file. See below for valid keywords.

alias start a nested section for an alias file. See below for valid keywords.

mdl start a nested section for a scenario file. See below for valid keywords. This keyword can be used more than once.

mmi start a nested section for an mmi file. See below for valid keywords. This keyword can be used more than once.

usr start a nested section for an usr file. See below for valid keywords. This keyword can be used more than once.

ic start a nested section for an initial condition file. See below for valid keywords. This keyword can be used more than once. message tab start a nested section for a message tab. See below for valid keywords. This keyword can be used more than once.

Valid keywords for the model, schedule, export, alias and usr nested sections:

path the path of the file required the required version of the file

722 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Valid keywords for the mdl nested section: path the path of the scenario file required the required version of the file caption the caption of the corresponding tab page active if 1, then the scenario is active, otherwise it is inactive iconView if 1, then represent the scenario using an iconview, if 0, then the scenario is represented as a treeview.

Valid keywords for the mmi nested section: path the path of the mmi file required the required version of the file caption the caption of the corresponding tab page Valid keywords for the ic nested section: path the path of the initial condition file required the required version of the initial condition file active if 1, then the initial condition is active, otherwise it is inactive

Valid keywords for the message_tab nested section: name name of the message tab message types list of message type names whose messages are logged in this tab

Syntax SIM /* Simulation Definition file */ : keyvals | tEOF ; keyvals : keyval | keyvals keyval ; keyval : server string ; | version numeric ; | model { file_keyvals } | schedule { file_keyvals } | export { file_keyvals } | alias { file_keyvals } | usr { file_keyvals } | ic { ic_keyvals } | mdl { mdl_keyvals } | mmi { mmi_keyvals }

c Airbus Defence and Space 723 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

| message_tab { message_tab keyvals } ; file_keyvals : file_keyval | file_keyvals file_keyval ; file_keyval : path string ; | required string ; ; ic_keyvals : ic_keyval | ic_keyvals ic_keyval ; ic_keyval : path string ; | required string ; | active numeric ; ; mdl_keyvals : mdl_keyval | mdl_keyvals mdl_keyval ; mdl_keyval : path string ; | caption string ; | required string ; | active numeric ; | iconView numeric ; ; mmi_keyvals : mmi_keyval | mmi_keyvals mmi_keyval ; mmi_keyval : path string ; | required string ; | caption string ; ; message_tab_keyvals : message_tab_keyval | message_tab_keyvals message_tab_keyval ; message_tab_keyval : name string ; | message_types string ; ;

A.9 MMI file format

The format is identical to the simulation definition. The purpose of an MMI file is to define monitors and action buttons on a tab page. The following keywords are valid for the MMI format: version the version number of the file format (should be 2)

724 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

monitor start a nested section for a monitor definition. See below for valid keywords. This keyword can be used more than once.

Valid keywords for the monitor nested section: name the caption of the monitor or action button mdl the scenario file containing the action used by the action button. Use an empty string if not relevant. action the action executed or disabled/enabled by the action button. Use an empty string if not relevant. path The path to the shared object this monitor uses. Can be left out if the monitor is not a plugin. monitorType the type of the monitor:

Type Description 0 Alpha numerical monitor 1 Plot against the simulation time 2 Plot against the wall clock time 3 Plot against another variable 4 Action button 5 Plugin Monitor Table A.2: Monitor Types

history the maximum number of data points that are used for the plot. Use 0 if not relevant. left the position of the left edge of the monitor in pixels top the position of the top edge of the monitor in pixels width the width of the monitor in pixels height the height of the monitor in pixels manualScalingX if 1, then the X-axis has a fixed range, otherwise the X-axis scales automatically. xMin the minimum value of the X-axis xMax the maximum value of the X-axis manualScalingY if 1, then the Y-axis has a fixed range, otherwise the Y-axis scales automatically. yMin the minimum value of the Y-axis yMax the maximum value of the Y-axis var start a nested section for a variable definition. See below for valid keywords. This keyword can be used more than once.

Valid keywords for the var nested section: name the variable to monitor. This is the only keyword if the var belongs to a plugin.

c Airbus Defence and Space 725 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

showLine if 1, then draw the line connecting two data points. lineColor the color of the line. It is the decimal representation of the hexadecimal RGB value 0xR- RGGBB.

symbol the symbol to use for a datapoint.

Value Description 0 No symbol 1 Ellipse 2 Rectangle 3 Diamond 5 Down triangle 6 Up triangle 7 Left triangle 8 Right triangle 9 Cross 10 X-Cross Table A.3: Available Symbols

Note that value 4 is not used. symbolColor the color of the symbol. It is the decimal representation of the hexadecimal RGB value 0xR- RGGBB. readOnly if 1, then this variable is read only.

Valid keywords for the custom nested section: name The key that identifies this custom property.

value The value associated with the custom property.

Syntax MMI /* Man-Machine Interface file */ : keyvals | tEOF ; keyvals : keyval | keyvals keyval ; keyval : monitor { monitor_keyvals } | version numeric ; ; monitor_keyvals

726 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

: monitor_keyval | monitor_keyvals monitor_keyval ; monitor_keyval : var { var_keyvals } | name string ; | mdl string ; | action string ; | path string; | propertiesPath string; | monitorType numeric ; | history numeric ; | left numeric ; | top numeric ; | width numeric ; | height numeric ; | manualScalingX numeric ; | xMin numeric ; | xMax numeric ; | manualScalingY numeric ; | yMin numeric ; | yMax numeric ; ; var_keyvals : var_keyval | var_keyvals var_keyval ; var_keyval : name string ; | showLine numeric ; | lineColor numeric ; | symbol numeric ; | symbolColor numeric ; | readOnly numeric ; ;

A.10 User Program Definition file format

The format is identical to the simulation definition. The purpose of a .usr file is to specify a program that can be used to connect to a running simulator. The following keyword is valid for the .usr format: def the specification of the program and its arguments. Note that the sequence %h is replaced with the hostname of the running simulator and the sequence %c is replaced with the preferred con- nection number.

Syntax USR /* User Program Definition file */ : keyvals | tEOF ; keyvals : keyval

c Airbus Defence and Space 727 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

| keyvals keyval ; keyval : def string ; ;

728 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix B

XML Schemas

The XML files used in EuroSim are officially described by XML schemas. These schema files are located in the lib/schemas subdirectory of the EuroSim installation directory.

c Airbus Defence and Space 729 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

730 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix C

Simulator launch options

The following are the command line options that can be passed to the main() function of the simulator:

-h Show on-line help and exit. -v Enable verbose printing of currently running simulator. -u uid (Numeric) uid for file ownership of recordings etc. -g gid (Numeric) gid for file ownership of recordings etc. -c number Connection number offset for the simulator process. Needed if more simulators are to be run on one host. -x simfile.sim Simulation definition to initially load. -m scenario.mdl Scenario to initially load. -e exportsfile.export Exports file for ExtSimAccess. -i initialcond.init Initial condition file to load. -d datadict.dict Data dictionary to load. -s schedule.sched Schedule file to load the scheduler with. -f number Frequency to run the asynchronous processes with. The default for the asynchronous frequency is 2 Hz. -R directory Directory to write recording files to. Defaults to the directory where the simfile.sim file came from. -l number Period (with respect to asynchronous frequency) for datalogger. Every number’th cycle data values will be delivered to (interested) clients (e.g. a simulation controller with a datamonitor). Defaults to 1. -r number When number is 0, real-time mode is off, when it is 1 it is on. -D flags Debugging flags. Only available when EuroSim libraries were compiled with DEBUG defined. -M modelfile.model The name of the model file used to create the simulator. -E Don’t use the daemon for services (CPU allocation). -I Do not go to initializing state automatically. -S Stand-alone mode (do not wait for client to connect). You may want to use this flag in combination with the -E flag. Useful for debugging from the command line with i.e. gdb.

Note that under normal circumstances the above options will be passed to the simulator by the EuroSim daemon. Example of a debugging session, running the simulator from the command line using gdb. Note that you

c Airbus Defence and Space 731 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

must have root privileges.

$ gdb mysimulator.Linux/mysimulator.exe

(gdb) run -c 1 -x mysimulator.sim -s mysimulator.sched -d mysimulator.Linux/mysimulator.dict -M mysimulator.model -r 1 -user 18157 -g 100 -R result_dir -v -f 10 -E -S

732 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix D

As Fast As Possible (AFAP) simulation

D.1 Introduction

The execution sequence of as fast as possible (AFAP) scheduling is a result of the same constraints as normal real-time scheduling and the overall behavior will thus be the same. However, one should be aware that AFAP scheduling exploits the parallelism of the schedule to a maximum. If a schedule is not well defined, this parallelism could lead to erroneous behavior. Below is an explanation of the opera- tion of the scheduler, followed by some examples illustrating AFAP scheduling and some consequences regarding parallelism.

D.2 Deadlines and simulation time

A task in EuroSim has a deadline which is equal to the sum of its start time and its allowed execution time. A deadline is the point in time at which a task should be ready. In a non real-time simulation the deadline is not a real world time, but a (virtual) simulation time. In a normal speed non real-time simulation this simulation time runs as fast as the real world time. However when a task is not ready before its deadline, the simulation time is halted until the task gets ready. Thus, when a task misses a deadline no more tasks will be started until that task gets ready. When the scheduler is running a simulation as fast as possible it increments the simulation time and starts tasks, until the simulation time reaches the deadline of one of the started tasks. The scheduler then waits until that task is ready and continues to increment the simulation time until the next deadline is reached.

D.3 Example 1: AFAP simulation with 2 independent tasks

Two tasks A and B are scheduled according to the schedule of Figure D.1. Both tasks have an allowed execution time of 15 ms. Task A has a real execution time of 4 ms and runs on processor 1. Task B has a real execution time of 6 ms and runs on processor 2. The real time execution sequence is shown in Figure D.2. Tasks B starts after task A is ready.

A

50Hz/0ms

B

50Hz/5ms

Figure D.1: Schedule of example 1

c Airbus Defence and Space 733 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

simulation time 0 5 10 15 20

real A allowed

real B allowed

0 5 10 15 20 wall clock time

Figure D.2: Real time execution sequence

simulation time 0–10 15 20

A real

B real

0 5 10 15 20 wall clock time

Figure D.3: AFAP execution sequence

Figure D.3 shows the execution sequence of the AFAP simulation. After task A is started, the simulation time may be increased immediately up to 5 ms, because there is no task with a deadline at 5 ms. Task B can thus be started and the simulation time can be increased up to 10 ms. The simulation time can be increased up to 15 ms only after the completion of task A and up to 20 ms after the completion of task B. The 20 ms of simulation time are executed in 6 ms real time, an acceleration factor of 3.3.

In the AFAP simulation task A and B run in parallel where they were running exclusive in the real time simulation.

D.4 Example 2: implicit mutual exclusion of two tasks

Tasks A and B are scheduled as in example 1. However, the allowed execution time for task A is set to 5 ms. The real time execution shown in Figure D.4 does not differ from Figure D.2. But, the parallelism in the AFAP simulation (Figure D.5) has disappeared. The simulation time cannot be incremented up to 5 ms until task A has completed. Due to this implicit exclusion the acceleration factor is 2.

734 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

simulation time 0 5 10 15 20

real A allowed

real B allowed

0 5 10 15 20 wall clock time

Figure D.4: Real time execution sequence with 5 ms allowed execution time for task A

simulation time 0 5–15 20

A real

B real

0 5 10 15 20 wall clock time

Figure D.5: AFAP execution sequence with 5 ms allowed execution time for task A

D.5 Example 3: A chain of tasks is a pipeline and has parallelism

A chain of tasks as shown in Figure D.6 is a pipeline and will be executed as such by the scheduler.

A B C

100Hz/0ms

Figure D.6: A chain of tasks forming a pipeline

The schedule has a basic frequency of 1000 Hz and the tasks have the following properties:

• Processor: any (Schedule Editor default)

• Allowed execution time: 4 ms

• Real execution time: 3 ms

In a real time run these specifications result in the following task sequence:

c Airbus Defence and Space 735 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

simulation time 0 5 10 15 20

real real A allowed allowed

real real B allowed allowed

real real C allowed allowed

0 5 10 15 20 wall clock time

Figure D.7: Real time execution of the task chain

simulation time 0–3 4–7 8–11 12–17 18–21 22–27

A real real real

B real real

C real real

0 5 10 15 20 wall clock time

Figure D.8: AFAP execution of the task chain

After task B has completed simulation time can be incremented to 11 ms allowing task A to start again. According to the schedule this is allowed, since task C does not depend on A. The effect is that task A and C run in parallel. If this is not the intended behavior then task C should be made dependent on task A (Figure D.9) or the sum of all allowed execution times should be made smaller then the task period. In fact, with this schedule parallelism would also occur in the real time situation if every task had a real execution time of 4 ms.

B

A C

100Hz/0ms

Figure D.9: A chain of dependent tasks

D.6 Other effects

Offset + allowed execution time >period If the sum of the offset of a task and its allowed execution time is larger than the period it can happen that the task is started after a state transition.

736 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Timed Events and Timed State Changes . In accelerated mode, Timed Events and Timed State Changes only work properly when they are ex- pressed in simulation time. (Quite trivial.)

Non real time tasks (output connectors) . The execution delay of non real time tasks depends on the load of the system. They are not synchro- nized to real time tasks (by definition). It can thus happen that output connectors overflow because the accelerated periodic tasks are activating them with a too high frequency.

D.7 Performance

Estimates for the acceleration factor in AFAP scheduling can be made with the data form the timings file incremented with the scheduler overhead of Table D.1.

Activity Time (µs) Clock tick 8 Task activation 12 Empty actionMgr 17 Active Action/Recorder/Stimulus 11 Inactive Action/Recorder/Stimulus 1

Table D.1: Scheduler overhead measured on a SGI/Origin 200 R10000@225MHz with EuroSim Mk2rev2

Note that the ActionMgr has a default frequency equal to the basic frequency. This can become one of the major CPU consuming tasks in an accelerated simulation. Accelerated simulations will run faster if the ActionMgr is scheduled at a lower frequency.

D.8 Example of performance computation

Frequency (Hz) Task duration (µs) Clock 1000 Task A 500 100 Task B 20 500 ActionMgr 1000 Recorder 1 100 Recorder 2 10

Table D.2: Example schedule on 1 CPU.

Frequency (Hz) Duration (µs) Subtotal (µs) Total contribution (µs) Tasks Task A 500 20 10000 Task B 20 500 10000 Table D.3: Computation time of the not optimized schedule.

c Airbus Defence and Space 737 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Frequency (Hz) Duration (µs) Subtotal (µs) Total contribution (µs) Total 10000 Scheduler Clock 1000 8 8000 Task A 500 12 6000 Task B 20 12 240 Total 14240 ActionMgr ActionMgr 1000 17+1+1 19000 Recorder 1 100 10 1000 Recorder 2 10 10 100 Total 20100 Total 44340 Table D.3: Computation time of the not optimized schedule.

Maximum acceleration of this schedule: 1000000/44340 = 23. The actionMgr uses 20100/44340 = 45% of the computation time. When the actionMgr is scheduled at 100 Hz it will only use 3000 µs. The maximum acceleration will then be 1000000/27240 = 37. This schedule could be optimized further if a basic frequency of 500 Hz is used, giving another 4000 µs reduction. The maximum acceleration will then be 1000000/23240 = 43.

738 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix E

Scheduler Errors

In this appendix, two categories of errors are described:

• Errors generated by the Schedule Editor when creating or modifying a schedule.

• Errors generated by the EuroSim scheduler during simulation runs.

E.1 Schedule Editor errors

The Schedule Editor helps the model developer by indicating where problems arise during schedule definition. When one of the items placed on the schedule view is red, then there is an error for that item. The error can be viewed in the item attributes window. Below the possible error messages are described. name unique The name entered is already in use by another task. Change the name. number of input flows The item needs (mandatory) input. Add an input. number of output flows The item needs (mandatory) output. Add an output. active flows There is no active flow. Active flows are flows from data generating items. Connect a data generating item. frequency mismatch A task has two input with different input frequencies, or a synchronous store has an input frequency which does not match the assigned input frequency. Remove one of the inputs, change the frequency of one of the inputs, or use a synchronous store in one of the flows. frequency zero The timer of the synchronous store has a frequency of zero. Change it. incorrect ratio The ratio of the input and output frequency of a synchronous store is not 1:n or n:1. Adjust one or both of the frequencies. cycle There is a cycle in the schedule (i.e. following the flows you can come back where you started). Break the cycle by removing a flow or task. critical Timing problem. The scheduler can not guarantee that the task can be completed in the available time. Modify timing of item or items connected to item concerned.

c Airbus Defence and Space 739 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

E.2 Scheduler run-time messages

The errors in this section are generated by the EuroSim scheduler during a simulation run. Each error has in the margin one or two of the following symbols:

N This message is an informational message only. No action is required.

W This message is a warning. It indicates a potential problem, which does not yet prevent the system proceeding.

E This message is an error. The system cannot proceed.

S This message should not occur (it stems from a file generated by EuroSim itself). Submit an SPR for this message.

Each message is accompanied by a short description and recovery suggestions if recovery by the user is possible.

ES: at line nnn, syntax error This error is flagged when the textual schedule definition file contains a syntax error. ES: cannot open scheduler description file sss The schedule definition file could not be opened at initialization of RT_SCHD, probably because it is not present in the current directory. Make sure that the schedule definition in a file named SCHEDULE_FILE is present in the current directory, and restart RT_SCHD. E: at line nnn, number of real time processors must be within the range [1...p] The schedule definition file requests a number of real time processors which is larger than physically available. Correct the definition file by choosing a processor in the reported range, or restart with real time privileges off (no super-user authorities). This latter will result in non real-time execution mode, in which any number of ‘real time’ processors may be emulated. E: at line nnn, basic frequency must be within the range (0...f] A scheduler clock frequency beyond the system-imposed limit has been requested in the sched- ule definition file. Choose a clock frequency which falls within the reported range. ES: at line nnn, task sss has not been defined in the current state In each EuroSim state, tasks must be declared before use in the schedule definition file; appar- ently this is not the case for the reported task. Add (or move) the declaration of the task. ES: at line nnn, store sss has not been defined in the current state In each EuroSim state, stores must be declared before use in the schedule definition file; appar- ently this is not the case for the reported store. Add (or move) the declaration of the store. ES: at line nnn, inputconnector sss has not been defined in the current state In each EuroSim state, input connectors must be declared before use in the schedule defini- tion file; apparently this is not the case for the reported input connector. Add (or move) the declaration of the input connector. ES: at line nnn, outputconnector sss has not been defined in the current state In each EuroSim state, output connectors must be declared before use in the schedule defini- tion file; apparently this is not the case for the reported output connector. Add (or move) the declaration of the output connector. ES: at line nnn, this processor number falls outside the defined range of real time processors In the schedule definition file, a task has been allocated to a processor which is not in the range of real time processors which has been requested in the same file. Lower the processor number of the indicated task such that it falls in the range requested at the RT_PROCESSORS request.

740 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

E: executer process creation failed Creation of a real time task executor process failed. The most probable cause of this situation is insufficient memory. W: cannot run executor on processor p Allocation of one of the real time executor processes to the specified processor failed. This message will be the result of starting RT_SCHD with insufficient privileges. The system will proceed in non real-time mode. When this is not intended, stop the simulation, and restart with super user authorities. W: too many reschedule levels for executor One of the internal scheduler’s stacks overflows. This situation almost always occurs in combi- nation with real time errors. Resolve the cause of the real time errors. W: the task activation tick of the previous cycle was still active at a new tick; this resulted in the loss of one basic cycle This warning is an indication that the system cannot support the requested clock frequency: the periodic part of the scheduler overruns. Reduce the clock frequency. WS: a preemption of the task activation tick detected; this should not have occurred The scheduler detected a double invocation of its periodic part, a situation which definitely should not have occurred. W: too few processors for specified amount of executors The schedule definition file requests a number of real time processors which is larger than physically available. This message is reported in combination with message at line nnn, number of real time processors must be within the range [1...p]. Correct the def- inition file by choosing a processor in the reported range, or restart with real time privileges off (no super-user authorities). This latter will result in non real-time execution mode, in which any number of ‘real time’ processors may be emulated. WS: executor table overflow This message indicates an overflow of one of the scheduler’s internal tables. It should never occur, since the size of this table has been chosen ‘sufficiently’ large. N: execution stopped before task sss In debugging mode, this message reports each task which has hit a breakpoint; this task is the one which will be resumed at the next ‘step’ command. WS: taskpool was too small (extended, but this should not have occurred) This situation indicates that some preallocated memory in unit Sched_TaskPool.c is insuffi- cient. Although it is not expected, this situation might occur in simulations with a large number of different task frequencies or task execution time bounds. The system responds to this situ- ation by dynamically enlarging its memory resources which might theoretically result in real time errors, although the probability of this is very low. Raise an SPR, requesting the size of preallocated memory (FREELIST_POOLSIZE) in Sched_Taskpool.c to be raised, and continue simulating. W: An input event raised to connector sss was lost due to insufficient buffer space. Raise the capacity of this input connector in this state (currently nnn) and rerun the simulation Self explanatory. W: An input event raised to connector sss was lost due to insufficient buffer space. Raise the total capacity of the input connectors in this state (currently nnn) and rerun the simulation Self explanatory.

c Airbus Defence and Space 741 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

W: An output event raised by connector sss was lost due to insufficient buffer space. Raise the total capacity of this output connector in this state (currently nnn) and rerun the simulation Self explanatory. W: pending state buffer overflow; state transition request ignored A very rapid sequence of state transition requests has caused an overflow of an internal buffer. Slow down with changing states by modifying schedule. W: hard real time error at uptime=nnn msec: periodic tasks were still active when they should have completed; basic cycle has been extended An overload condition has been detected, in which execution of a periodic task took longer than its allowed execution time (unless otherwise specified, this allowed time is equal to its activation period). The system responds to this situation by slowing down the real time. Increase number of real time processors used (if possible), or decide if the effective schedule is not optimal. A schedule is not optimal if processors are unused for longer time spans1 where this could have been avoided by a ‘smarter’ activation order of previously executed tasks. In these cases, scheduling can be influenced by processor allocation, use of task offsets and -priorities, and by adding dependencies between tasks. W: illegal state transition from sss to sss (ignored) An unallowed EuroSim state transition has been requested. It is ignored. Check the state transition diagram for legal transitions. W: real time mode transition refused: this machine is non real-time A transition of RT_SCHD’s mode to mode ‘real time’ has been requested in a simulation which runs with insufficient authorities, or which runs on a machine without real- time capabilities. The mode transition is ignored. Re-run with super user authorities, and use a multiprocessor platform. W: frequency change refused: this simulation is in real time execution mode A request has been given to change the clock frequency to a rate different from the rate on which the current schedule is based (200 Hz default). This request is refused in real time simulation mode. Make a mode transition to mode ‘non real-time’. W: frequency change refused: the requested frequency (nn Hz) is larger than the bound imposed by the system (nn Hz) A request has been given to change the clock frequency to a rate higher than a system-imposed bound. This has been ignored. Choose a lower rate. W: itemname hard real time error for itemtype (itemdetails): previous firing not completed; basic cycle has been extended The specified item has generated a hard real time error.

E.3 Low level errors

The errors from the previous section are scheduler run-time errors which are raised through the EuroSim message reporting mechanism. It is possible that errors occur that are not caught by this mechanism. This is usually because:

• They are raised at system initialization, when the message mechanism has not yet been initialized. These errors usually result in a text like ‘error: description’.

• They cannot be caught (e.g. bus errors, access violations). These errors usually result in a core dump.

1‘Longer’ here is relative to the time granularity of the simulation, so it might apply to one or more milliseconds.

742 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

• They are on the level of code assertions, in libraries which do not ‘know’ the message mechanism. These errors usually result in a text like ‘Assertion failed’.

All errors of these kinds are reported through standard error, i.e. they are displayed on the console or the window in which EuroSim was started. In most cases, they indicate a problem in RT_SCHD and should be reported through an SPR. The second category of errors may also be caused by errors in the user code.

c Airbus Defence and Space 743 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

744 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix F

Introduction to CVS

F.1 Introduction

CVS, short for Concurrent Versions System, allows you to save versions of your files for later retrieval by yourself or other users (provided they have sufficient access rights). The files are stored in what is called a “repository”. This chapter describes the basic commands that are required to start using CVS with EuroSim. See [CVS00] for more information on CVS.

F.2 Initializing the repository root

After deciding where to install the CVS repository root (usually a directory on a network drive that is backed-up at regular intervals), you must initialize it:

• Open a shell and change directory to the designated directory (create it first if it doesn’t exist yet): cd repository root directory

• Set the CVSROOT environment variable: export CVSROOT=repository root directory Example for Linux: export CVSROOT=/projects/share/repository See Section F.4 for a description on how to use CVS under Windows.

• Initialize the CVS repository: cvs init

If all went well, a CVSROOT directory is created in the repository root directory. Note that you only have to perform the above steps once.

F.3 Setting up a CVS repository

Once the CVS repository root has been initialized, you can add “repositories” to it. When using CVS with EuroSim, you can create a repository for the directory where your project files are located:

• Go to the directory where the files of your EuroSim project are located (model files, schedule file, etc. . . ). cd project directory

c Airbus Defence and Space 745 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

• Create an empty CVS repository directory in the CVS repository root:

cvs import -I \* -m log msg repository vendor tag release tag The -I option with the escaped wildcard (\*) tells CVS to ignore all files in the project directory. This is done because at this point we do not want to import any files into the repository: we selectively add files to the repository later on by means of the menu commands in the EuroSim tools.

The -m option allows you to enter a descriptive log message for the repository. Enclose the message in quotes or double quotes.

The vendor tag and release tag can be any text, because we are not importing any files at this point. Example:

cvs import -I \* -m ’Test’ MyProject Foo Bar • Go to the parent directory cd ..

• Initialize project directory with the CVS files: cvs checkout -d project directory repository name The project directory should now contain a directory CVS. Example: cvs checkout -d MyProject MyProject

You can now start the EuroSim Project Manager, select your project and select the Tools:Project Settings menu command to set the project repository root to the repository root directory that you assigned to the CVSROOT environment variable. When starting the EuroSim tools from the Project Manager, you can use the Tools:Version menu com- mands to add files to the repository.

F.4 Using CVS under Windows

When you are using Cygwin’s native version of CVS, then specify the CVSROOT environment variable as follows: export CVSROOT=/cygdrive/drive letter/repository root directory Example for Cygwin when your repository is on the F: drive export CVSROOT=/cygdrive/f/repository Other versions of CVS for Windows may require the addition of the local server specification like this: export CVSROOT=:local:drive letter/repository root directory For example: export CVSROOT=:local:F:/repository Consult the README files of the version of CVS that you are using for more information on how to set up CVS.

F.5 More information

You can get more information by typing: man cvs on the command line. Of course the internet provides multiple sources of CVS manuals in multiple formats (.tex, .pdf, etc. . . ). O’Reilly & Associates have a nice pocket reference, see [CVS00].

746 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix G

Software Problem Reports

In case a problem or error with EuroSim occurs, please contact the EuroSim helpdesk, preferably by email to esim-support @eurosim.nl. Document the problem or error with as much detail as possible. Things of interest are:

• Software version numbers

• Hardware specifications

• Sequence of actions (such as selecting files, clicking buttons, changing state of the simulator)

• Contents of files used

Preferably the problem or error should be reproducible. If possible try to create a minimal environment in which the error occurs, to facilitate finding the source of the problem. Please also describe the criticality of the error, which can be one of:

Critical A major problem that hinders the completion of the user’s job. This category includes a time aspect (solution is needed as soon as possible) for the user to be able to finish the job.

Major A serious problem, but the user can still continue with the job.

Minor A problem was noted, but it is not seriously affecting the use of EuroSim. Suggestion A suggestion for the improvement of EuroSim. Question A question on EuroSim details.

When the helpdesk receives your error report and it is not a user error, a Software Problem Report will be logged in the EuroSim problem tracking system. An SPR number is generated and can be provided to you if required. Generally Customer maintain a problem report in their own tracking system, and correlate that report to the EuroSim SPR by included the EuroSim SPR number in their problem report description. Depending on the criticality and your maintenance status the problem may be immediately worked on or delayed untill the next Software Review Board. When the problem report is accepted, it is assigned to a developer and the status changes to Approved for Implementation (A4I). The developer changes the sta- tus to Started, investigates and solves the problem, and subsequently changes the status to Implemented. The Software Review Board accepts the answer, plans its release, and switches the status to Approved for Release (A4R). For each release the ResolvedSPRList text file included with the distribution documents which SPRs have been solved.

c Airbus Defence and Space 747 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

748 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix H

Abbreviations

AFAP As Fast As Possibe

API Application Programmers Interface

ASCII American Standards Code for Information Interchange

COTS Commercial Off The Shelf

CPAN Comprehensive Perl Archive Network Dict Dictionary

DS Airbus Defence and Space

EFO EuroSim Follow-On

EI External Interrupt

ERA European Robotic Arm

ESA European Space Agency Esim EuroSim

ESTEC European Space Research and Technology Centre EuroSim European Real-time Operations Simulator

F77 Fortran 77

FFT Fast Fourier Transform

FIFO First In, First Out

GNAT GNU ADA Translator

GUI Graphical User Interface

HIL Hardware In the Loop

HTML HyperText Markup Language

HTTP HyperText Transfer Protocol Hz hertz

ID Identification

IGS Image Generation System

I/O Input/Output

LCM Least Common Multiple

MDK Model Development Kit

MDL Mission Definition Language

MIF Maker Interchange Format

c Airbus Defence and Space 749 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Mk Mark

MMI Man-Machine Interface

NIVR Netherlands Agency for Aerospace Programs

NLR National Aerospace Laboratory NLR org Organization

OSF Open Software Foundation

PCI Peripheral Component Interconnect

POSIX Portable Operating System Interface

RCS Revision Control System

RPC Remote Procedure Call

SGI Silicon Graphics Incorporated

SMDL Simulation Model Definition Language

SMI Simulation Model Interface

SMP Simulation Model Portability

SMP2 Simulation Model Portability 2

SPR Software Problem Report

SUM Software User Manual

URL Uniform Resource Locator

UTC Coordinated Universal Time

WINNT Windows NT

VME VERSAmodule Eurocard

XML Extensible Markup Language

750 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Appendix I

Definitions

Action From a user’s perspective, an action is part of his scenario, and defines both the required re- sponse to be taken when an event occurs, plus the required event. An action can be one of stimulus, recorder, monitor, intervention, and event. EuroSim provides specific editors for de- fault recorders and stimuli, and a generic action editor for all other actions and customized recorders, stimuli and monitors. Monitor actions are obsolescent and are replaced with MMI definitions. Application definition file Format of files created by LynX; contain initialization and run-time information for a Vega application. Files have a .adf extension. Data dictionary A list of public data variables and parameters extracted from model code, i.e. those which are accessible to the user for (optionally) updating, monitoring and recording. The list is augmented with descriptive information (such as units, default values, ranges). Data View A subset of the data items in the EuroSim data dictionary. Used to define data items which are to be read/written by an external simulator at run time, and therefore provides a mechanism for data between two independent simulators. Entry point A function or procedure in the model code (for which some restrictions apply) which can be used to create tasks in the Schedule Editor.

Event A discrete occurrence during a simulation run, which (can) cause a change in the behavior of the system being simulated, for example a component failure. Execution state The state of a simulator. Certain user requests are only valid in certain states. External simulator A simulator which is not running under EuroSim. Facility management The means of providing maintenance support and project and user management during the simulation life cycle. Flight format Binary format used for input and output by the MultiGen and ModelGen database modelling tools. It is a comprehensive format that can represent nearly all imaging concepts. Files in Flight format are structured as a linear sequence of records and have a .flt extension. Hardware-in-the-loop A piece of equipment which forms part of the real-world system, which is given a real-time interface to the simulation loop.

c Airbus Defence and Space 751 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Initial condition Consistent set of model state values, to put the model into a particular state at the beginning of a simulation run. In EuroSim, the initial condition can be created with the Initial Condition Editor, or it can be a snapshot of values from previous simulation run. Journal Information resulting from a particular simulation run(excluding sampled data values), e.g. log of executed event s, error/warning messages, and marks. Man-in-the-loop A person taking on the role of an operator within the real-world application, who is provided with a real-time interface to the simulation loop. Mark A pointer or reference mark made by a user during a simulation run, to provide an easy means of returning to a point of interest during test analysis. Simulation Definition Complete definition of a particular test for a particular model and schedule, specifying the initial conditions, stimuli and variables which are to be recorded. For on-line evaluation, variables can also be viewed on screen by specifying monitors.

MMI Definition Defines the contents of a tab page in the Simulation Controller used for interacting with the simulator. Normally this tab page contains one or more monitors. Model A set of components (sub-models and data files) which together define the data and behavioral characteristics of a specific real-world system, or part thereof. See Simulator. Observer The user who (optionally) attends asimulation run and who may select variables for viewing, and mark interesting observations, but who is not able to affect the execution outcome in any way. Operational modes EuroSim provides different modes of use which are available to one or more users; for exam- ple, the Model Developer uses EuroSim for simulator development, the Test Analyst uses it for analysis of test results. Particular user activities are only available during particular modes, for example application model s can only be updated during simulator development. EuroSim is able to support two or more modes simultaneously. See simulator development, test prepara- tion, test execution, and test analysis. Phase A time offset between completion of one task and activation of another task which is dependent on that completion, defined as a quantity of wall-clock time. Real-time During real-time execution or interfacing, the time-lining of the activities appears to be that which would be seen in an equivalent situation in the real-world. This is achieved through guaranteed periodicity of processing and response time within fixed deadlines. Schedule A set of attributed tasks, timers, scheduling events and their respective dependencies. The overall behavior of a schedule is deterministic, whereas that of a single task need not be. A schedule is executed by the scheduler. The scheduler has four states: Initializing, Standby, Executing and Exiting. Every state has its own schedule. The same task may appear in one or more state schedules. Simulation The process of using models that behave or operate like a given system when provided a set of controlled inputs. Simulation program The computer program, built out of simulator software, used for the simulation.

752 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Simulation run Execution of a simulator according to specified simulation definition. Simulator A hardware device or simulation program or combination of both with which simulation can be performed. A simulator together with a simulation definition can be used to start a simulation run. Simulator development Mode of operation, where the Model Developer can create and/or update models and simulator definitions, and generate simulators. See Operational Modes. Simulator software Model-dependent software combined with model-independent software for the performance and control of real time and non-real time simulation.

State The current phase in the execution of the simulation. EuroSim states are: initialization, standby, executing and exit.

Stimuli A set of data which are input to the model during a simulation run, which represent data from an interfacing system or sub-system which would normally be present in the real-world; they can be used during replays of simulation runs, to provide copies of the original operator inputs. Sub-model A component of a model, which defines (in source code) an element or set of elements within the real-world application. The parts of a sub-model visible to other “users” are the set of accessible state data items (which are listed as part of the model data dictionary) and a set of operations which can be called by other sub-models or listed within a task within the schedule. System services A set of services offered by EuroSim which can be called directly from model code, for example in order to request information on the current simulation (e.g. simulated time, execution state), or to communicate with HIL devices.

Task A unit within a model schedule consisting of an ordered list of one or more entry points. Task execution starts with the first entry point listed, and suspends (always) after the last entry point listed has been executed. It is possible for tasks to be executed in parallel in a multi-processor environment. Test analysis Mode of operation, where the Test Analyst can mathematically analyze test results, replay vi- sual images and export data for external use. See Operational modes. Test Conductor The user who operates the simulator as a tool to perform a simulation run. Test execution Mode of operation, where the Test Conductor has interactive control of a simulation run, and may initiate on-line events. The Test Conductor and (optionally) an Observer may also monitor data dictionary item values and create marks. See Operational modes. Test preparation Mode of operation, where the Test Conductor can create and/or update simulation definitions, and an Observer can identify data dictionary items for monitoring. See Operational modes. Test results All information resulting from a particular simulation run, i.e. the journal and the recorded data dictionary item values.

c Airbus Defence and Space 753 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Revision Record

Iss Rev Date Reason for Changes change 0 1 11-Mar-1994 Internal review Document creation 0 2 10-Apr-1994 Internal review Expanded contents and internal comments resolved 0 3 15-Dec-1994 Mk0.1 release All document 0 4 7-Feb-1995 Continued All pages updating of issue 0 revision 3

0 5 25-Apr-1995 Issued for DD/R SR/R-1-RID-SRD-74, SR/R-2-RID-SRD-5, AD/R- EuroSim Mk0.1 2-RID-Model ICD-2, AD/R-2-RID-Model ICD-3, AD/R-2-RID-SRD-3, AD/R-2-RID-SUM-2. 1 0 18-May-1995 Internal All pages. comments 1 1 26-Jun-1995 Updated after DDR.

2 0 15-Jul-1996 New document Reference number of document changed to NLR-EFO- for EuroSim SUM-2 Mk0.2

2 1 16-Dec-1996 Issued for DD/R Internal review comments processed. SPRs imple- EuroSim Mk0.2 mented: 166, 364, 370, 380, 397, 406, 462, 475, 484, 571, 574, 578, 603, 612, 629, 633, 652, 657, 712, 814, 840, 960, 961, 1010, 1011, 1045, 1205, 1216, 1273, 1293, 1326, 1483

2 2 17-Feb-1997 Updated after The following RIDs have been implemented: 53..67, DD/R 69..76, 78..102, 104, 106..123, 125..164, 166..187, 202..209, 211..214, 216..224, 226..251, 255..257, 260, 263, 266..269. Note that not-implemented RIDs from the 200 range have been re-issued for the delta DD/R

2 3 25-Apr-1997 Updated after The following RIDs have been implemented: 42..44, delta DD/R 47..51, 53..68, 72..83, 85..88, 90, 91, 93..102, 104..106, 107 (partly), 108..116, 119..123

2 4 1-May-1997 EuroSim Mk1 Inclusion of IGS information/references: reference to SUM IGSSUM, inclusion of IGS overview, definition of IGS interfaces within EuroSim (action IGS-PM7-3). Approved RIDs from DD/R: 68, 77, 103, 105, 124, 125

2 5 24-Jun-1997 Added RID Approved SPRs implemented: 1557, 1549, 1592. numbers for Update Test Analyzer section in accordance with revisions 2 and 3 SPR-1505, 1651. above Updated appendix on MDL following DD/RRID 177 and DD/RRID 103. Also some knock-on changes in Mission Tool Ref- erence.

754 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Iss Rev Date Reason for Changes change

3 0 2-Mar-2000 Mk2 release SPR 1633 ,Section 3.2. 3 1 2-May-2000 Mk2rev1 release Event counter functions added to EuroSim Services. High resolution and max number processors changes added. Recorder file switching and Stimuli cycling changes documented. HLA extension: EsimRTI usage as appendix added. 3 2 6-Oct-2000 Mk2rev2 release Added appendix describing the run-time interface as used by the test controller. Added appendix explaining AFAP scheduling pit- falls. 4 0 14-May-2002 Mk3 release Updated the manual to conform to the new Graphi- cal User Interface 4 1 12-Sep-2003 Mk3rev1 release Converted to LATEX. Updated screenshots. Update descriptions of publish functions (API head- ers), Added description on new ’diff with’ functionality (GUI), Added action button support (Simulation Con- troller), Added description for timebar (Schedule Editor), Added section on user defined EuroSim compatible devices (HW), Updated MDL syntax description, Added chapter for Windows COM interface 4 2 2-Sep-2004 Mk3rev2 release Added new chapters for Model Description Editor and Parameter Exchange Editor. Simulation Controller: added description for exports file, removed sections on IGS. Schedule Editor: added description on how to add Parameter Exchange file(s) to the schedule. Model Editor: Added the Model Description file node. EuroSim files and formats: Added Model Descrip- tion and Parameter Exchange files. Updated screen shots 5 0 18-Apr-2006 Mk4rev0 release Added new chapters for Calibration Editor, SMP2 Editor and the Web Interface. Model Editor: Added the SMP2 Catalogue file node. Updated various screen shots 5 1 28-Jan-2008 Mk4rev1 release Added new chapters for Batch utilities (python, java, tcl), Java interface, Error Injection and the Transfer Sample Protocol. Updated various screen shots 5 2 19-Mar-2011 Mk4rev2 release Added chapters for the new C++ API and Embedded EuroSim, Updated Scheduler chapter on timing and metrics, Updated various screen shots

c Airbus Defence and Space 755 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Iss Rev Date Reason for Changes change 5 3 15-Jun-2011 Mk4rev3 release Work in progress.... Added new interface function esimEventTime, Updated various screen shots 5 4 7-Nov-2011 Mk4rev4 release Work in progress.... Added new interface SMP2, Updated various screen shots 6 0 01-Oct-2012 Mk5rev0 release Updated C++ interface, Updated SMP2 interface, Moved Embedded EuroSim to addon document, Modified the licensing scheme, Removed Irix, SGI, HLA extension (EsimRTI), Updated various screen shots 6 1 22-Jun-2013 Mk5rev1 release Windows7 support, Including UML Transformer via Satellite++ example, Cleaned up Moonlander exam- ple, Documented frontsheet version repaired, Ap- pended Revision History, 6 2 05-Mar-2014 Mk5rev2 release Expanding CPP interface Update of Schedule Editor Reference on Timebar addition of esimTrace func- tions 6 3 20-Mar-2015 Mk5rev3 release Further expanding CPP interface Rewrite of Exter- nal Hardware Chapter Addition of section on file assocations in ME Addition of section on Trouble Shooting Removale of SMP1 reference Restructure of Reference chapters 7 0 18-Nov-2016 Mk6rev0 release Addition of chapter on Matlab/Simulink support, Model Reuse Architecture and chapter on Front-End models. Replaced section on PharLap with section on Embedded EuroSim. Addressed the embedding of EuroSim in other applications Added support to launch simulators using symbolic debugger or mem- ory checker. Improved filtering in DictWidget. Inte- grated support for timebar recording and display in Simulation Controller. Various improvements on the CPP interface, including error injectors and default types for vectors, matrices and quaternions 7 1 01-Apr-2017 Mk6rev1 release Minor corrections and additions (chapter on Front- End models). Adding get view id and get export id extensions with new evExtNewView message 7 2 14-Sep-2017 Mk6rev2 release Expanded Perl section and added get_values doc- umentation for batch interfaces. Small updates on Simulation Controller (connect to server dia- log). significant improvements and changes in the Mil1553 Front-End Model. 7 3 01-Dec-2017 Mk6rev3 release Documented functions to set struct field attributes in CPP api. Updated Error injection in Discrete Front- end model

756 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Iss Rev Date Reason for Changes change 7 4 09-Feb-2018 Mk6rev4 release Added explanation of switch function to let new use calloc rather the malloc. Added explanation of es- imGetTypeName for automatic detection of types. Updated simulation Controller monitor section due to added label capability. Improved explanation of event handling in batch reference chapters. Im- proved description of set_val in batch scripts for structs. Added explanation of vwait behavior in tcl batcht reference. Added explanation on extension of MRAPUB for constants and for developer view only. Documented filters for milcat utility. Added Dictionary Browser section 7 5 16-Aug-2018 Mk6rev5 release Added freeze option to Mra Submodels. Major up- date on ThermoMra, including how to commun- ciate with external equipment. Added document generation support to MRA. Supporting parallel build from Model Editor via build options. Added a configurable Timekeeper model to the front-end models Added configurable Timeline model to the MRA section. Added recdiff to the utilities men- tioned in the Simulation Controller section. Added a description of the memory watchdog. Updated Mil1553 SyncHandler interface from setSyncHan- dler to addSynHandler. 7 6 31-Oct-2018 Mk6rev5 release Updated the definition of the ramp function for CPP port and FeModel errors. 7 7 31-Jan-2019 Mk6rev6 release Added error parser installation in eclipse for use with EuroSim. Added size of structure to info di- alog on dictio variables. Expanded documentation on the CPP Timekeeper model. Expanded the usage of MatLab Simulink code generation for EuroSim. Added support for multicore static SMP2 schedul- ing to SMP2. Removed support for profiling and updated support voor gcov. 8 0 27-Mar-2020 Mk7rev0 release Update of the CPP port and links section for new approach and visibility argument, MRA parameter publication improved, Python 3 support, Etra de- scription and example for MMI plugin, Extra de- scription on starting the sim with sync to second, Describing a makefile extension feature in Model Editor.

c Airbus Defence and Space 757 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Iss Rev Date Reason for Changes change 8 1 30-Mar-2020 Mk7rev1 release Removed support for TSP, Removed support for Web Interface, Improved timing statistics, In and OutPortC for C (POD) structs, Integration of the ESPRiT Discrete plugin, New solution for Param- eter Exchanges, Updated description on Model De- scription Editor Removed Section on Simulator Inte- gration Library Added Section on PUS support Im- proved Discrete Front-End model Improved Front- End stub test interface

758 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Bibliography

c Airbus Defence and Space 759

NLR-EFO-SUM-2 SUM iss: 8 rev: 1

[COM98] Inside distributed COM, 1998, ISBN 1-57231-849-X, Microsoft Press, Eddon & Eddon. Back- ground on (D)COM components and applications.

[CVS00] CVS pocket reference, 2000, ISBN 0-596-00003-0, O’Reilly & Associates, Gregor N. Purdy. Pocket reference to the Concurrent Versions System.

[FAQ05] EuroSim frequently asked questions, 2005, This can be found in $EFOROOT/doc/html/FAQ/faq.html. This file contains the EuroSim Frequently Asked Questions list in HTML format.

[MAN18] EuroSim manual pages, 2018, Stored in $EFOROOT/man. This directory contains the EuroSim on-line manual pages, which can be read using the UNIXman command.

[OM20] Airbus Defence and Space, EuroSim Mk7.1 owner’s manual, 2020, FSS-EFO-TN-530, issue 7 revision 1. This document contains the information relevant for the facility manager of Eu- roSim. Stored in $EFOROOT/doc/pdf/OM.pdf. This file contains the EuroSim Owner’s Man- ual in Adobe Acrobat format. Also stored in directory $EFOROOT/doc/html/OM. This direc- tory contains the EuroSim Owner’s Manual in HTML format.

[PMA18] EuroSim manual pages, 2018, FSS-EFO-SPE-523, issue 6 revision 1, 16-Aug-2018. This docu- ment contains a printed version of all end user relevant manual pages.

[Sec03] ECSS Secretariat (ed.), Ground systems and operations - telemetry and telecommand packet utilization, Space engineering, no. ECSS-E-70-41A, ESA-ESTEC, 2003.

[SMP05a] Simulation model portability 2.0 c++ mapping, 2005, EGOS-SIM-GEN-TN-0102, issue 1, revision 2, 2005/10/28. This document contains the mapping to C++ for both the metamodel and the component model of the SMP2 standard.

[SMP05b] Simulation model portability 2.0 component model, 2005, EGOS-SIM-GEN-TN-0101, issue 1, revi- sion 2, 2005/10/28. This document specifies the component model of the SMP2 standard.

[SMP05c] Simulation model portability 2.0 handbook, 2005, EGOS-SIM-GEN-TN-0099, issue 1, revision 2, 2005/10/28. This document is the Handbook for the SMP2 Standard.

[SMP05d] Simulation model portability 2.0 c++ model development kit, 2005, EGOS-SIM-GEN-TN-1001, issue 1, revision 2, 2005/10/28. This document contains the documentation of the Model Development Kit for the SMP2 standard.

[SMP05e] Simulation model portability 2.0 metamodel, 2005, EGOS-SIM-GEN-TN-0100, issue 1, revision 2, 2005/10/28. This document describes the metamodel specification (SMDL) of the SMP2 standard.

[SPR18] Resolved SPR list, 2018, Stored in $EFOROOT/etc/ResolvedSPRList. This file contains a list of solved bugs (SPRs) of each EuroSim release.

[SRN18] EuroSim Mk7.1 software release notes, 2018, FSS-EFO-SRN-388. Stored in $EFOROOT/etc/SoftwareReleaseNote. Final word from developers before packaging; always contains last and latest information concerning delivered EuroSim release.

[SUM20] Airbus Defence and Space, EuroSim Mk7.1 software user’s manual, 2020, NLR-EFO- SUM-002, issue 8 revision 1. Stored in $EFOROOT/doc/pdf/SUM.pdf. This file contains the EuroSim Software User Manual in Adobe Acrobat format. Also stored in directory $EFOROOT/doc/html/SUM. This directory contains the EuroSim Software User Manual in HTML format.

c Airbus Defence and Space 761 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

Index

EuroSim example script, 366 services java, 369 see services, 196 perl, 345 python, 419 action tcl, 469 action manager number, 155 useful command line utilities, 368 condition, 126, 155 error conditions C see MDL, 125 Interface reference, 193 icons, 151 C language limitations inactive, 155 see API limitations, 209 monitor C++ see monitor, 127 Interface reference, 215 recorder C++ support see recorder, 126 see C++ batch reference, 609 script, 125 see C++ interface reference, 215 editor, 154 Calibration Editor stimulus calibration types, 99 see stimulus, 126 menu, 101 action button overview,9 editor, 162 reference, 99, 313 Action Editor, 154 client overview, 10 see external simulator, 677 action manager COM Interface configuring multiple, 113 reference, 693 multiple, 120 connectors scheduling, 120 output Ada using for I/O, 117 Interface reference, 193 CPU load monitor, 138 ADA language limitations CVS, 745 see API limitations, 209 Use under Windows, 746 AimMil1553 interface, 533 Cxx alias, 142 nl.eurosim.batch alias file EntryInfo, 647 example, 720 eurosim, 644 file format, 720 EventHandler, 634 API EventInfo, 646 examples, 210 EventTypeInfo, 648 limitations ExtSimVar, 656 ADA language, 209 ExtSimVar*, 657 C language, 209 ExtSimView, 654 Fortran language, 209 InitCond, 652 general, 208 Session, 609 Selection, 63 SessionInfo, 649 TaskInfo, 647 Batch utility TmTcLink, 651 cxx, 609 WhereInfo, 646

762 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

data dictionary linking to EuroSim (Tm/Tc), 689 alias, 142 linking to EuroSim, 681 deadlock, 209 performance, 685 Debug Control receiving data, 684 breakpoint on task entry point, 144 receiving events, 684 concepts, 143 selection of shared data, 677 enable/disable task, 144 sending data, 684 return to normal, 144 synchronization, 679 step to next entry point, 143 trace task entry point, 144 FeModel debugging using gdb, 731 Interface reference, 537 dict view file format choosing EuroSim views, 678 alias file, 720 choosing external views, 679 exports file, 719 compression, 683 initial condition, 720 confirmation, 683 MMI, 724 linking variables, 683 recorder, 718 setting up, 682 simulation definition, 721 update frequency, 683 test results, 719 Dictionary Browser User Program Definition, 727 reference, 187 Files created by EuroSim, 715 see data dictionary, 45 flows, 110 usage, 187 Fortran Dynamic Link Libraries Interface reference, 193 see external simulator, 685 Fortran language limitations see API limitations, 209 efoKill, 368 Frequency changers, 108 efoList, 368 entry points, 107 global variables, 209 Error injection Go, 135 Enable for a variable, 79 GUI, 41 Function definition, 85 common dialog buttons, 42 esim common menus, 43 menu, 51 common toolbar buttons, 43 reference, 49 conventions, 41 esim* library functions, 196, 203, 688 elements, 41 esimMil1553 interface, 535 ellipsis, 41 EuroSim keyboard shortcuts, 42 Automatic addition of files to the project, 49 Init, 135 concepts,5 initial condition GUI concepts, 125 see GUI, 41 editor, 142 reference, 49 menu, 143 tools,9 overview, 10 tutorial, 13 file format, 720 evExtByteOrder, 682 Input connector exports file, 681 ERROR, 111 example, 720 FATAL, 111 file format, 719 NON REAL TIME MODE ENTRY, 111 ext* library functions, 681, 682 NOTICE, 111 external debugging facilities, 146 REAL TIME ERROR, 111 external simulator REAL TIME MODE ENTRY, 111 byte order, 682 SNAPSHOT END, 112 case study, 681

c Airbus Defence and Space 763 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

STATE ENTRY, 23, 104, 111 importing submodels, 65 STATE EXIT, 104, 111 options, 67 WARNING, 111 Model Description Editor Datapool, 84 Java Entry point node, 78 Example code, 295 Error injection, 80 Interface reference, 295 Input and output nodes, 79 nl.eurosim.batch Inputs and Outputs group nodes, 78 EntryInfo, 407 menu, 79 eurosim, 405 Model Description file, 83 EventHandler, 394 Model node, 78 EventInfo, 406 objects in model description tree, 77 EventTypeInfo, 408 overview,9 ExtSimVar, 416 reference, 75 ExtSimVar*, 417 Root node, 78 ExtSimView, 415 tree view, 77 InitCond, 412 Use case example, 81 Session, 370 user defined variables, 76 SessionInfo, 409 views, 77 TaskInfo, 407 Model Editor TmTcLink, 412 Make file node in Model Editor, 60 WhereInfo, 407 add generated c++ code, 67 nl.eurosim.model add SMP2 package, 66 EsimRuntime, 297 Build Doc, 71 eurosim, 296 build SMP2 library, 71 Renamable, 300 Calibration file node in Model Editor, 60 Java support Channel node, 63 see Java batch reference, 369 Clear Logging, 71 see Java interface reference, 295 Compiler specification, 70 journal Entry node, 60 marks and comments, 132 Entry nodes, 60 journal file, 130 environment editor, 72 File node, 58 linking Fortran and C, 21 generate c++ code, 72 Matlab generate default package, 72 Interface reference, 303 generate makefile template, 72 Matlab support import generated c++ code, 67 see Matlab interface reference, 303 import SMP2 catalogue, 66 MDL, 125, 325 import SMP2 package, 66 error conditions, 326 Inport node, 63 formal description, 331 menu, 64 functions message pane, 57 built-in, 331 Model Description file node in Model Editor, variables, 327 59 mirroring of data, 677 Model node, 63 Mission Definition Language Object node, 63 see MDL, 125 objects in model tree, 57 MMI Org node, 58 file format, 724 Outport node, 63 mode overview,9 real time/non-real time, 134 Parameter Exchange file node in Model Editor, model 60 creating, 14 Port node, 63

764 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

Preferences dialog, 71 comparison between runs, 183 re-generate and integrate c++ code, 72 user defined function, 180 reference, 55 variable references, 181 Root node, 57 Project,8 Save Logging, 71 Project Editor Sequence node, 63 overview,9 Show Doc, 71 Project Manager showing all nodes, 65 reference, 49 SMP2 Assembly file node in Model Editor, 60 PUS Smp2 lib node, 58 reference, 315 Source file node, 59 Python status bar, 57 eurosim structuring the model, 58 EntryInfo, 455 tab pane, 56 eurosim, 453 toolbar, 56 EventHandler, 443 Transfer node, 61 EventInfo, 454 TransferGroup node, 61 EventTypeInfo, 457 validate SMP2 artefact, 72 ExtSimVar, 465 Variable node, 61 ExtSimVar*, 466 views, 55 ExtSimView, 463 monitor InitCond, 461 editor, 162 Session, 419 formatting and conversion, 164 SessionInfo, 457 graphical, 127 TaskInfo, 456 reducing bandwidth, 126 TmTcLink, 460 multiple action managers, 120 WhereInfo, 455 mutexes, 107 Python support see Python batch reference, 419 non real-time tasks, 106 non-real time real time see simulation mode,8 see simulation mode,8 recorder, 126 observer, 123 editor, 155 offsets, 119 file format, 718 output events, 109 frequency, 156 suspend, 136 Parameter Exchange Editor test results file format, 719 Destination, 91 recording files, 130 Exchange group node, 92 Reset, 135 Exchange parameter node, 92 revision control Exchanges, 91 see version management, 12 menu, 92 objects in Exchange tree, 92 scenario overview,9 diff, 151 Parameter Exchange file, 93 icon view, 150 reference, 89 tree view, 150 Source, 91 schedule Use case example, 93 clocktypes, 121 views, 91 creating, 22 Pause, 135 dependencies, 115 Periodic Switch, 156 error message, 739 Perl support external event handler, 113 see Perl batch reference, 345 external events, 111 plot definition frequency, 112

c Airbus Defence and Space 765 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

main cycle, 119 esimGetMainCycleTime, 204 non-feasible, 114 esimGetProcessor, 206 offsets, 119 esimGetProcessorLoad, 208 predefined events, 111 esimGetRealtime, 205 Schedule Editor esimGetRecordingState, 205 connectors esimGetSimtime, 203 see connectors, 117 esimGetSimtimets, 203 default bindings, 104 esimGetSimtimeYMDHMSs, 204 error messages, 739 esimGetSpeed, 205 External event handlers, 113 esimGetState, 204 external events, 111 esimGetTaskname, 204 flows esimGetTaskRate, 204 see flows, 110 esimGetWallclocktime, 203 Internal and External events, 109 esimGetWallclocktimets, 203 menu, 110 esimInstallErrorHandler, 207 model file, 103 esimMalloc, 203 objects, 103 esimMessage, 205 overview, 10 esimRaise, 204 Predefined events, 111 esimRealloc, 203 Predefined output events, 112 esimRecClose, 206 reference, 103 esimRecDoubleArrayFieldAdd, 206 Schedule Configuration, 112 esimRecDoubleFieldAdd, 206 see schedule, 103 esimRecFloatArrayFieldAdd, 206 stores esimRecFloatFieldAdd, 206 see stores, 108 esimRecInt16ArrayFieldAdd, 206 tasks esimRecInt16FieldAdd, 206 see tasks, 104 esimRecInt32ArrayFieldAdd, 206 timers esimRecInt32FieldAdd, 206 see timers, 109 esimRecInt64ArrayFieldAdd, 206 scheduling esimRecInt64FieldAdd, 206 the action manager, 120 esimRecInt8ArrayFieldAdd, 206 semaphores, 209 esimRecInt8FieldAdd, 206 serial interface, 533 esimRecOpen, 206 services esimRecUint16ArrayFieldAdd, 206 description, 203 esimRecUint16FieldAdd, 206 esimCalloc, 203 esimRecUint32ArrayFieldAdd, 206 esimDisableTask, 204 esimRecUint32FieldAdd, 206 esimEnableTask, 204 esimRecUint64ArrayFieldAdd, 206 esimEntrypointFrequency, 204 esimRecUint64FieldAdd, 206 esimError, 205 esimRecUint8ArrayFieldAdd, 206 esimEventCount, 205 esimRecUint8FieldAdd, 206 esimEventData, 205 esimRecWriteHeader, 206 esimEventHandlerDispatch, 205 esimRecWriteRaw, 206 esimEventHandlerInstall, 205 esimRecWriteRecord, 206 esimEventHandlerUninstall, 205 esimReport, 205 esimEventRaiseTimed, 204 esimReportAddSeverity, 206 esimEventTime, 205 esimSetLoadMeasureInterval, 208 esimFatal, 205 esimSetRealtime, 205 esimFree, 203 esimSetRecordingState, 205 esimGetHeapUsage, 208 esimSetSimtime, 204 esimGetHighResWallclocktime, 203 esimSetSimtimets, 204 esimGetMainCycleBoundarySimtime, 204 esimSetSimtimeYMDHMSs, 204 esimGetMainCycleBoundaryWallclocktime, 204 esimSetSpeed, 205

766 c Airbus Defence and Space NLR-EFO-SUM-2 SUM iss: 8 rev: 1

esimSetState, 204 Schedule, 143 esimSetStateTimed, 204 Script Monitors, 126 esimStrdup, 203 set default, 131 esimThreadCreate, 206 tab pane, 128 esimThreadExit, 206 Timebar esimThreadKill, 206 Enable, 137 esimVersion, 207 timing analysis, 147 esimWarning, 205 toolbar, 127 options, 731 User-defined monitor, 165 synopsis, 196 windows, 127 simulation simulation definition bandwidth creating, 24 actual, 139 file format, 721 estimated, 139 referencing a model file, 124 disconnect, 134 referencing a schedule file, 124 ftpreconnect, 134 referencing an alias file, 124 kill, 136 referencing an exports file, 124 lifecycle,5 referencing initial condition files, 124 mode,8, 129 referencing scenario files, 124 reconnect, 133 selection of active initial condition, 125 server, 129, 133 use of multiple initial conditions, 125 speed, 129 simulation log state, 129 see journal, 128 transitions, 119 simulation output view, 110 files, 130 time, 129 user-defined directory, 139 traceability, 129 simulation state tracing, 136 see state transitions,8 user role, 129 simulator,7 wall clock time, 129 command line options, 731 Simulation Controller data dictionary,7 input files, 124 development,6 MMI definitions, 124 elements,6 image definitions, 124 external, 677 stimuli, 124 model,7 user program definitions, 124 prefcon, 682, 689, 731 menu, 127, 130 state,7 message pane, 128 state change, 109 message tab pane, 167 task,7 overview, 10 Simulink preferences, 137 Interface reference, 303 reference, 123 SMP2 Start Mode, 137 artefact validation, 287 Debug, 137 assembly code generation, 287 Memory Check, 137 c++ code generation, 287 Normal, 137 c++ code integration, 287 status bar, 129 component model, 288 tab page generation of default package, 287 API, 149 in EuroSim, 287 Input Files, 140 MDK, 288 Messages, 128 model development kit, 288 MMI, 159 reference, 285 Scenario, 150 schedule conversion, 287

c Airbus Defence and Space 767 iss: 8 rev: 1 SUM NLR-EFO-SUM-2

scheduling scenarios, 293 see Tcl batch reference, 469 schemas, 288 Test analysis,6 Smp.cat, 288 Test Analyzer smp2cat2pkg, 287 PV-WAVE smp2gen, 287 access to recorded data, 183 smp2glue, 287 examples, 183 smp2sched, 287 help, 185 smp2val, 287 interface, 185 support of features, 288 operators and functions, 182 snapshot, 136 variables, 183 Software Problem Report, 747 main window, 171 starting EuroSim overview, 10 Linux, 13 reference, 171 Windows, 13 Test execution,6 state transitions,8 Test preparation,6 Step, 135 test result file, 130 stimulus, 126 thread editor, 157 creation, 206 frequency, 157 exit, 206 input via a function, 157 kill, 206 Stop, 135 timers, 109 stores, 115 timings file, 130 asynchronous TM/TC Link, 687 behavior, 114 case study, 688 synchronous, 108 characteristics, 688 mutual exclusive tasks, 116 customizing, 689 timing output frequency, 117 receiving packets, 690 synchronization sending packets, 690 external applications, 679 trace file, 130 triggers, 110 Task Sequencer, 114 troubleshooting, 31 tasks, 104 activation methods, 104 User Program Definition disabling from MDL, 335 creating a, 132 enabling from MDL, 335 file format, 727 intersection between, 64, 113 triggering from MDL, 335 version management, 12 TCL baselining models, 12 eurosim CVS, 745 EntryInfo, 505 repository, 12 eurosim, 503 requirement, 12 Event handler callbacks, 493 traceable simulation, 12 EventInfo, 504 XML Schemas, 729 EventTypeInfo, 507 ExtSimVar, 515 ExtSimVar*, 516 ExtSimView, 514 InitCond, 511 Session, 469 SessionInfo, 507 TaskInfo, 506 TmTcLink, 510 WhereInfo, 505 TCL support

768 c Airbus Defence and Space