文档库 最新最全的文档下载
当前位置:文档库 › FMI_for_ModelExchange_and_CoSimulation_v2.0

FMI_for_ModelExchange_and_CoSimulation_v2.0

FMI_for_ModelExchange_and_CoSimulation_v2.0
FMI_for_ModelExchange_and_CoSimulation_v2.0

Functional Mock-up Interface for

Model Exchange and Co-Simulation

Document version: 2.0

July 25, 2014

This document defines the Functional Mock-up Interface (FMI), version 2.0. FMI is a tool independent standard to support both model exchange and co-simulation of dynamic models using a combination of xml-files and C-code (either compiled in DLL/shared libraries or in source code). The first version, FMI 1.0, was published in 2010. The FMI development was initiated by Daimler AG with the goal to improve the exchange of simulation models between suppliers and OEMs. As of today, development of the standard continues through the participation of 16 companies and research institutes. FMI 1.0 is supported by over 45 tools and is used by automotive and non-automotive organizations throughout Europe, Asia and North America.

On the Downloads page (https://https://www.wendangku.net/doc/389916829.html,/downloads), this specification, as well as supporting C-header and xml schema files, and an FMI compliance checker is provided. In addition, sample models (exported from different tools in FMI format) are provided to assist tool vendors to ensure compatibility with other tools, as well as a test suite to check whether connected FMUs are appropriately handled by a tool.

Contact the FMI development group at contact@https://www.wendangku.net/doc/389916829.html,.

History / Road Map

Version Date Remarks

1.0 2010-01-26 First version of FMI for Model Exchange

1.0 2010-10-12 First version of FMI for Co-Simulation

2.0 2014-07-25 Second version of FMI for Model Exchange and Co-Simulation

Please, report issues that you find with this specification to the public FMI issue tracking system: https://https://www.wendangku.net/doc/389916829.html,

License of this document

Copyright ? 2008-2011 MODELISAR consortium and

2012-2014 Modelica Association Project “FMI”

This document is provided “as is" without any warranty. It is licensed under the CC-BY-SA (Creative Commons Attribution-Sharealike 4.0 International) license, which is the license used by Wikipedia. Human-readable summary of the license text from https://www.wendangku.net/doc/389916829.html,/licenses/by-sa/4.0/:

You are free to:

Share — copy and redistribute the material in any medium or format

Remix — remix, transform, and build upon the material

for any purpose, even commercially.

The licensor cannot revoke these freedoms as long as you follow the license terms.

Under the following terms:

Attribution — You must give appropriate credit, provide a link to the license, and indicate

if changes were made. You may do so in any reasonable manner, but not in any way that

suggests the licensor endorses you or your use.

Share Alike — If you remix, transform, or build upon the material, you must distribute your

contributions under the same license as the original.

The legal license text and disclaimer is available at:

https://www.wendangku.net/doc/389916829.html,/licenses/by-sa/4.0/legalcode

Note:

Article (3a) of this license requires that modifications of this work must clearly label, demarcate or otherwise identify that changes were made.

The C header and XML-schema files that accompany this document are available under the BSD 2-Clause license (https://www.wendangku.net/doc/389916829.html,/licenses/bsd-license.html) with the extension that

modifications must be also provided under the BSD 2-Clause license.

Attention is drawn to the possibility that some of the elements of this document may be the subject of patent rights. Modelica Association shall not be held responsible for identifying such patent rights.

If you have improvement suggestions, please send them to the FMI development group at

mailto:contact@https://www.wendangku.net/doc/389916829.html,.

Abstract

This document defines the Functional Mock-up Interface (FMI), version 2.0 to (a) exchange dynamic models between tools and (b) define tool coupling for dynamic system simulation environments.

FMI for Model Exchange (chapter 3)

The intention is that a modeling environment can generate C code of a dynamic system model that can be utilized by other modeling and simulation environments. Models are described by differential, algebraic and discrete equations with time-, state- and step-events. If the C code describes a continuous system, then this system is solved with the integrators of the environment where it is used. The models

to be treated by this interface can be large for usage in offline or online simulation, or can be used in embedded control systems on micro-processors.

FMI for Co-Simulation (chapter 4)

The intention is to provide an interface standard for coupling of simulation tools in a co-simulation environment. The data exchange between subsystems is restricted to discrete communication points. In the time between two communication points, the subsystems are solved independently from each other by their individual solver. Master algorithms control the data exchange between subsystems and the synchronization of all simulation solvers (slaves). Both, rather simple master algorithms, as well as more sophisticated ones are supported. Note, that the master algorithm itself is not part of the FMI standard.

FMI Common Concepts (chapter 2)

The two interface standards have many parts in common. In particular, it is possible to utilize several instances of a model and/or a co-simulation tool and to connect them together. The interfaces are independent of the target environment because no header files are used that depend on the target environment (with exception of the data types of the target platform). This allows generating one dynamic link library that can be utilized in any environment on the same platform. A model, a co-simulation slave or the coupling part of a tool, is distributed in one zip file called FMU (Functional Mock-up Unit) that contains several files:

(1) An XML file contains the definition of all exposed variables in the FMU and other static information. It is

then possible to run the FMU on a target system without this information, in other words with no unnecessary overhead.

(2) All needed model equations or the access to co-simulation tools are provided with a small set of easy to

use C functions. A new caching technique allows a more efficient evaluation of the model equations than in other approaches. These C functions can either be provided in source and/or binary form. Binary forms for different platforms can be included in the same FMU zip file.

(3) The model equations or the co-simuation tool can be either provided directly in the FMU, or the FMU

contains only a generic communication module that communicates with an external tool that evaluates or simulates the model. In the XML file information about the capabilities of the FMU are present, for example to characterize the ability of a co-simulation slave to support advanced master algorithms such as the usage of variable communication step sizes, higher order signal extrapolation, or others.

(4) Further data can be included in the FMU zip file, especially a model icon (bitmap file), documentation

files, maps and tables needed by the FMU, and/or all object libraries or dynamic link libraries that are utilized.

A growing set of tools supports FMI. The actual list of tools is available at:

https://https://www.wendangku.net/doc/389916829.html,/tools

About FMI 2.0

This version 2.0 is a major enhancement compared to FMI 1.0, where the FMI 1.0 Model Exchange and Co-Simulation standards have been merged, and many improvements have been incorporated, often due to practical experience when using the FMI 1.0 standards. New features are usually optional (need neither be supported by the tool that exports an FMU, nor by the tool that imports an FMU). Details are provided in appendix A.3.1. The appendix of the FMI 1.0 specification has been mostly moved in an extended and improved form to a companion document

“FunctionalMockupInterface-ImplementationHints.pdf”

where practical information for the implementation of the FMI standard is provided.

Conventions used in this Document

?Non-normative text is given in square brackets in italic font: [especially examples are defined in this style.].

?Arrays appear in two forms:

o In the end-user/logical view, one- and two-dimensional arrays are used. Here the convention of linear algebra, the control community and the most important tools in this area is utilized, in other words the first element along one dimension starts at index one. In all these cases, the starting index is also explicitly mentioned at the respective definition of the array. Example: In the

modelDescription.xml file, the set of exposed variables is defined as ordered sets where the first element is referenced with index one (these indices are, for example, used to define the

sparseness structure of partial derivative matrices).

o In the implementation view, one-dimensional C-arrays are used. In order to access an array element the C-convention is used. For example, the first element of input argument x for function setContinuousStates(..) is x[0].

FMI 2.0 Implementation Help

If you plan to export or import models in FMI 2.0 format, you may find the following tools/models helpful for your development (available from https://https://www.wendangku.net/doc/389916829.html,/downloads):

?FMU Compliance Checker

Free software to check whether an FMI model is compliant to the FMI standard.

?FMUs from other tools

In order to test the import of FMI models from other vendors in your tool, a set of test FMUs are provided.

?Library to test connected FMUs

Free Modelica library to test difficult cases of connected FMI models.

?FMU Software Development Kit

Free software development kit by QTronic to demonstrate basic use of FMI.

?FMI Library

Free software package by Modelon that enables integration of FMI models in applications.

Contents

1.Overview (8)

1.1Properties and Guiding Ideas (9)

1.2Acknowledgements (12)

2.FMI Common Concepts for Model Exchange and Co-Simulation (13)

2.1FMI Application Programming Interface (13)

2.1.1Header Files and Naming of Functions (13)

2.1.2Platform Dependent Definitions (fmi2TypesPlatform.h ) (15)

2.1.3Status Returned by Functions (16)

2.1.4Inquire Platform and Version Number of Header Files (18)

2.1.5Creation, Destruction and Logging of FMU Instances (18)

2.1.6Initialization, Termination, and Resetting an FMU (21)

2.1.7Getting and Setting Variable Values (23)

2.1.8Getting and Setting the Complete FMU State (24)

2.1.9Getting Partial Derivatives (25)

2.2FMI Description Schema (28)

2.2.1Definition of an FMU (fmiModelDescription) (29)

2.2.2Definition of Units (UnitDefinitions) (33)

2.2.3Definition of Types (TypeDefinitions) (38)

2.2.4Definition of Log Categories (LogCategories) (42)

2.2.5Definition of a Default Experiment (DefaultExperiment) (43)

2.2.6Definition of Vendor Annotations (VendorAnnotations) (43)

2.2.7Definition of Model Variables (ModelVariables) (44)

2.2.8Definition of the Model Structure (ModelStructure) (55)

2.2.9Variable Naming Conventions (variableNamingConvention) (64)

2.3FMU Distribution (65)

3.FMI for Model Exchange (69)

3.1Mathematical Description (69)

3.2FMI Application Programming Interface (79)

3.2.1Providing Independent Variables and Re-initialization of Caching (79)

3.2.2Evaluation of Model Equations (80)

3.2.3State Machine of Calling Sequence (82)

3.2.4Pseudo Code Example (86)

3.3FMI Description Schema (88)

3.3.1Model Exchange FMU (ModelExchange) (89)

3.3.2Example XML Description File (91)

4.FMI for Co-Simulation (93)

4.1Mathematical Description (94)

4.1.1Basics (94)

4.1.2Mathematical Model (96)

4.2FMI Application Programming Interface (99)

4.2.1Transfer of Input / Output Values and Parameters (99)

4.2.2Computation (100)

4.2.3Retrieving Status Information from the Slave (102)

4.2.4State Machine of Calling Sequence from Master to Slave (103)

4.2.5Pseudo Code Example (106)

4.3FMI Description Schema (108)

4.3.1Co-Simulation FMU (CoSimulation) (108)

4.3.2Example XML Description File (111)

5.Literature (114)

Appendix A FMI Revision History (115)

A.1Version 1.0 – FMI for Model Exchange (115)

A.2Version 1.0 – FMI for Co-Simulation (116)

A.3Version 2.0 – FMI for Model Exchange and Co-Simulation (117)

A.3.1Overview (117)

A.3.2Main changes (118)

A.3.3Contributors (122)

Appendix B Glossary (124)

1. Overview

The FMI (Functional Mock-up Interface) defines an interface to be implemented by an executable called FMU (Functional Mock-up Unit). The FMI functions are used (called) by a simulation environment to create one or more instances of the FMU and to simulate them, typically together with other models. An FMU may either have its own solvers (FMI for Co-Simulation, chapter 4) or require the simulation environment to perform numerical integration (FMI for Model Exchange, chapter 3). The goal of this interface is that the calling of an FMU in a simulation environment is reasonably simple. No provisions

are provided in this document how to generate an FMU from a modeling environment. Hints for implementation can be found in the companion document “FunctionalMockupInterface-ImplementationHints.pdf“.

The FMI for Model Exchange interface defines an interface to the model of a dynamic system described by differential, algebraic and discrete-time equations and to provide an interface to evaluate these equations as needed in different simulation environments, as well as in embedded control systems, with explicit or implicit integrators and fixed or variable step-size. The interface is designed to allow the description of large models.

The FMI for Co-Simulation interface is designed both for the coupling of simulation tools (simulator coupling, tool coupling), and coupling with subsystem models, which have been exported by their simulators together with its solvers as runnable code. The goal is to compute the solution of time dependent coupled systems consisting of subsystems that are continuous in time (model components

that are described by differential-algebraic equations) or time-discrete (model components that are described by difference equations, for example discrete controllers). In a block representation of the coupled system, the subsystems are represented by blocks with (internal) state variables x(t) that are connected to other subsystems (blocks) of the coupled problem by subsystem inputs u(t) and subsystem outputs y(t).

In case of tool coupling, the modular structure of coupled problems is exploited in all stages of the simulation process beginning with the separate model setup and pre-processing for the individual subsystems in different simulation tools. During time integration, the simulation is again performed independently for all subsystems restricting the data exchange between subsystems to discrete communication points. Finally, also the visualization and post-processing of simulation data is done individually for each subsystem in its own native simulation tool.

The two interfaces have large parts in common. These parts are defined in chapter 2. In particular:

?FMI Application Programming Interface (C)

All needed equations or tool coupling computations are evaluated by calling standardized “C”

functions. “C” is used, because it is the most portable programming language today and is the only programming language that can be utilized in all embedded control systems.

?FMI Description Schema (XML)

The schema defines the structure and content of an XML file generated by a modeling environment.

This XML file contains the definition of all variables of the FMU in a standardized way. It is then

possible to run the C code in an embedded system without the overhead of the variable definition (the alternative would be to store this information in the C code and access it via function calls, but this is neither practical for embedded systems nor for large models). Furthermore, the variable

definition is a complex data structure and tools should be free how to represent this data structure in their programs. The selected approach allows a tool to store and access the variable definitions

(without any memory or efficiency overhead of standardized access functions) in the programming language of the simulation environment, such as C++, C#, Java, or Python. Note, there are many free and commercial libraries in different programming languages to read XML files into an

appropriate data structure, see for example https://www.wendangku.net/doc/389916829.html,/wiki/XML#Parsers, and especially

the efficient open source parser SAX (https://www.wendangku.net/doc/389916829.html,/,

https://www.wendangku.net/doc/389916829.html,/wiki/Simple_API_for_XML ).

An FMU (in other words a model without integrators, a runnable model with integrators, or a tool coupling interface) is distributed in one zip file. The zip file contains (more details are given in section 2.3):

?

The FMI Description File (in XML format). ? The C sources of the FMU, including the needed run-time libraries used in the model, and/or

?

Figure 1Blochwitz et.al. 2011 and 1.1 starting from high-level properties to low-level implementation issues.

Expressivity : The FMI provides the necessary features that Modelica ?, Simulink ? and SIMPACK ?

models 1 can be transformed to an FMU.

Stability : FMI is expected to be supported by many simulation tools world wide. Implementing such

support is a major investment for tool vendors. Stability and backwards compatibility of the FMI

has therefore high priority. To support this, the FMI defines 'capability flags' that will be used by

1 Modelica is a registered trademark of the Modelica Association, Simulink is a registered trademark of the MathWorks Inc., SIMPACK is a registered trademark of SIMPACK AG.

future versions of the FMI to extend and improve the FMI in a backwards compatible way,

whenever feasible.

Implementation: FMUs can be written manually or can be generated automatically from a modeling environment. Existing manually coded models can be transformed manually to a model

according to the FMI standard.

Processor independence: It is possible to distribute an FMU without knowing the target processor. This allows to run an FMU on a PC, a Hardware-in-the-Loop simulation platform or as part of the

controller software of an ECU, e. g. as part of an AUTOSAR SWC. Keeping the FMU

independent of the target processor increases the usability of the FMU and is even required by the AUTOSAR software component model. Implementation: using a textual FMU (distribute the C source of the FMU).

Simulator independence: It is possible to compile, link and distribute an FMU without knowing the target simulator. Reason: The standard would be much less attractive otherwise, unnecessarily

restricting the later use of an FMU at compile time and forcing users to maintain simulator

specific variants of an FMU. Implementation: using a binary FMU. When generating a binary

FMU, e. g. a Windows dynamic link library (.dll) or a Linux shared object library (.so), the target operating system and eventually the target processor must be known. However, no run-time

libraries, source files or header files of the target simulator are needed to generate the binary

FMU. As a result, the binary FMU can be executed by any simulator running on the target

platform (provided the necessary licenses are available, if required from the model or from the

used run-time libraries).

Small run-time overhead: Communication between an FMU and a target simulator through the FMI does not introduce significant run time overhead. This is achieved by a new caching technique (to

avoid computing the same variables several times) and by exchanging vectors instead of scalar quantities.

Small footprint: A compiled FMU (the executable) is small. Reason: An FMU may run on an ECU (Electronic Control Unit, for example a micro processor), and ECUs have strong memory

limitations. This is achieved by storing signal attributes (names, units, etc.) and all other static

information not needed for model evaluation in a separate text file (= Model Description File) that is not needed on the micro processor where the executable might run.

Hide data structure: The FMI for Model Exchange does not prescribe a data structure (a C struct) to represent a model. Reason: the FMI standard shall not unnecessarily restrict or prescribe a

certain implementation of FMUs or simulators (whoever holds the model data), to ease

implementation by different tool vendors.

Support many and nested FMUs: A simulator may run many FMUs in a single simulation run and/or multiple instances of one FMU. The inputs and outputs of these FMUs can be connected with

direct feed through. Moreover, an FMU may contain nested FMUs.

Numerical Robustness: The FMI standard allows that problems which are numerically critical (for example time and state events, multiple sample rates, stiff problems) can be treated in a robust way.

Hide cache: A typical FMU will cache computed results for later reuse. To simplify usage and to reduce error possibilities by a simulator, the caching mechanism is hidden from the usage of the FMU.

Reason: First, the FMI should not force an FMU to implement a certain caching policy. Second, this helps to keep the FMI simple. Implementation: The FMI provides explicit methods (called by the FMU environment) for setting properties that invalidate cached data. An FMU that chooses to implement a cache may maintain a set of 'dirty' flags, hidden from the simulator. A get method,

e. g. to a state, will then either trigger a computation, or return cached data, depending on the

value of these flags.

Support numerical solvers: A typical target simulator will use numerical solvers. These solvers require vectors for states, derivatives and zero-crossing functions. The FMU directly fills the values of

such vectors provided by the solvers. Reason: minimize execution time. The exposure of these vectors conflicts somewhat with the 'hide data structure' requirement, but the efficiency gain

justifies this.

Explicit signature: The intended operations, argument types and return values are made explicit in the signature. For example an operator (such as 'compute_derivatives') is not passed as an int

argument but a special function is called for this. The 'const' prefix is used for any pointer that

should not be changed, including 'const char*' instead of 'char*'. Reason: the correct use of the FMI can be checked at compile time and allows calling of the C code in a C++ environment

(which is much stricter on ‘const’ as C is). This will help to develop FMUs that use the FMI in the intended way.

Few functions: The FMI consists of a few, 'orthogonal' functions, avoiding redundant functions that could be defined in terms of others. Reason: This leads to a compact, easy to use, and hence

attractive API with a compact documentation.

Error handling: All FMI methods use a common set of methods to communicate errors.

Allocator must free: All memory (and other resources) allocated by the FMU are freed (released) by the FMU. Likewise, resources allocated by the simulator are released by the simulator. Reason: this helps to prevent memory leaks and runtime errors due to incompatible runtime environments for different components.

Immutable strings: All strings passed as arguments or returned are read-only and must not be modified by the receiver. Reason: This eases the reuse of strings.

Named list elements: All lists defined in the fmiModelDescription.xsd XML schema file have a String attribute name to a list element. This attribute must be unique with respect to all other name

attributes of the same list.

Use C: The FMI is encoded using C, not C++. Reason: Avoid problems with compiler and linker dependent behavior. Run FMU on embedded target.

This version of the functional mock-up interface does not have the following desirable properties. They might be added in a future version:

?The FMI for Model Exchange is for ordinary differential equations in state space form (ODE). It is not for a general differential-algebraic equation system. However, algebraic equation systems inside the FMU are supported (for example the FMU can report to the environment to re-run the current step with a smaller step size since a solution could not be found for an algebraic equation system).

?Special features as might be useful for multi-body system programs, like SIMPACK, are not included.

?The interface is for simulation and for embedded systems. Properties that might be additionally needed for trajectory optimization, for example derivatives of the model with respect to parameters during continuous integration, are not included.

?No explicit definition of the variable hierarchy in the XML file.

?The number of states and number of event indicators are fixed for an FMU and cannot be changed.

1.2 Acknowledgements

Until Dec. 2011, this work was carried out within the ITEA2 MODELISAR project (project number: ITEA 2–07006, https://https://www.wendangku.net/doc/389916829.html,/project/modelisar.html).

Daimler AG, DLR, ITI GmbH, Martin Luther University Halle-Wittenberg, QTronic GmbH and SIMPACK AG thank BMBF for partial funding of this work within MODELISAR (BMBF F?rderkennzeichen: 01lS0800x).

Dassault Systèmes (Sweden) thanks the Swedish funding agency VINNOVA (2008-02291) for partial funding of this work within MODELISAR.

LMS Imagine and IFPEN thank DGCIS for partial funding of this work within MODELISAR.

Since Sept. 2012 until Nov. 2015, this work is partially carried out within the ITEA2 MODRIO project (project number: ITEA 2–11004, https://https://www.wendangku.net/doc/389916829.html,/project/modrio.html).

?DLR, ITI GmbH, QTronic GmbH and SIMPACK AG thank BMBF for partial funding of this work within MODRIO (BMBF F?rderkennzeichen: 01IS12022E).

?Dassault Systèmes (Sweden), Link?ping University and Modelon AB thank the Swedish funding agency VINNOVA (2012--01157) for partial funding of this work within MODRIO.

?Siemens PLM Software (France) and IFPEN thank DGCIS for partial funding of this work within MODRIO.

2. FMI Common Concepts for Model Exchange and Co-Simulation

In this chapter, the concepts are defined that are common for “model exchange” and for “co-simulation”. In both cases, FMI defines an input/output block of a dynamic model where the distribution of the block, the platform dependent header file, several access functions, as well as the schema files are identical. The definitions that are specific to the particular case are defined in chapters 3 and 4.

Below, the term FMU (Functional Mock-up Unit) will be used as common term for a model in the “FMI for model exchange” format, or a co-simulation slave in the “FMI for co-simulation” format. Note, the interface supports several instances of one FMU.

2.1 FMI Application Programming Interface

This section contains the common interface definitions to execute functions of an FMU from a C program.

Note, the following general properties hold for an FMU:

?FMI functions of one instance don't need to be thread safe.

[For example, if the functions of one instance of an FMU are accessed from more than one thread, the multi-threaded environment that uses the FMU must guarantee that the calling sequences of functions defined in section 3.2.3 and section 4.2.4. are used. The FMU itself does not implement any services to support this.]

?FMI functions must not change global settings which affects other processes/threads. An FMI function may change settings of the process/thread in which it is called (such as floating point control registers), provided these changes are restored before leaving the function or before a callback function is called.

[So functions of different FMU instances can be called safely in any order. Additionally, they can be called in parallel provided the functions are called in different process/threads. If an FMI function changes for example the floating point control word of the CPU, it must restore the previous value before return of the function. For x86 CPUs, the floating point control word is set using the fldcw instruction. This can be used to switch on additional exceptions such as "floating point division by zero". An FMU might temporarily change the floating point control word and get notified on floating point exceptions internally, but has to restore the flag and clear the floating point status word before return of the respective FMI function.]

2.1.1 Header Files and Naming of Functions

Three header files are provided that define the interface of an FMU. In all header files the convention is used that all C function and type definitions start with the prefix “fmi2”:

?“fmi2TypesPlatform.h”

contains the type definitions of the input and output arguments of the functions. This header file must be used both by the FMU and by the target simulator. If the target simulator has different definitions in the header file (for example “typedef float fmi2Real” instead of “typedef double fmi2Real”), then the FMU needs to be re-compiled with the header file used by the target simulator. Note, the

header file platform for which the model was compiled can be inquired in the target simulator with

fmi2GetTypesPlatform, see section 2.1.4.

[Example for a definition in this header file:

typedef double fmi2Real;

]

?“fmi2FunctionTypes.h“

contains typedef definitions of all function prototypes of an FMU. When dynamically loading an FMU, these definitions can be used to type-cast the function pointers to the respective function definition.

[Example for a definition in this header file:

typedef fmi2Status fmi2SetTimeTYPE(fmi2Component, fmi2Real);

]

?“fmi2Functions.h”

contains the function prototypes of an FMU that can be accessed in simulation environments and that are defined in chapters 2, 3, and 4. This header file includes “fmi2TypesPlatform.h” and

“fmi2FunctionTypes.h”. Note, the header file version number for which the model was compiled, can be inquired in the target simulator with fmi2GetVersion, see section 2.1.4.

[Example for a definition in this header file2:

FMI2_Export fmi2SetTimeTYPE fmi2SetTime;

]

The goal is that both textual and binary representations of FMUs are supported and that several FMUs might be present at the same time in an executable (for example FMU A may use an FMU B). In order for this to be possible, the names of the functions in different FMUs must be different or function pointers must be used. To support the first variant macros are provided in “fmi2Functions.h” to build the actual function names by using a function prefix that depends on how the FMU is shipped. Typically, FMU functions are used as follows:

// FMU is shipped with C source code, or with static link library

#define FMI2_FUNCTION_PREFIX MyModel_

#include "fmi2Functions.h"

< usage of the FMU functions >

// FMU is shipped with DLL/SharedObject

#include "fmi2Functions.h"

< usage of the FMU functions >

A function that is defined as “fmi2GetReal” is changed by the macros to the following function name:

?FMU is shipped with C source code, or with static link library:

The constructed function name is “MyModel_fmi2GetReal”, in other words the function name is prefixed with the model name and an “_”. As FMI2_FUNCTION_PREFIX the “modelIdentifier”

”attribute defined in , or

is used, together with “_” at the end (see sections 3.3.1 and 4.3.1). A simulation environment can therefore construct the relevant function names by

generating code for the actual function call. In case of a static link library, the name of the library is MyModel.lib on Windows, and libMyModel.a on Linux, in other words the “modelIdentifier”

attribute is used as library name.

?FMU is shipped with DLL/SharedObject:

The constructed function name is “fmi2GetReal”, in other words it is not changed. A simulation environment will then dynamically load this library and will explicitly import the function symbols by providing the FMI function names as strings. The name of the library is MyModel.dll on Windows or MyModel.so on Linux, in other words the “modelIdentifier” attribute is used as library name.

2 For Microsoft and Cygwin compilers, “FMI2_Export“ is defined as “__declspec(dllexport)“ and for Gnu-Compilers “FMI2_Export“ is defined as “__attribute__((visibility("default")))“ in order to export the name for dynamic loading. Otherwise it is an empty definition.

[An FMU can be optionally shipped so that it basically contains only the communication to another tool (needsExecutionTool = true, see section 4.3.1). This is particularily common for co-simulation tasks. In FMI 1.0, the function names are always prefixed with the model name and therefore a DLL/Shared Object has to be generated for every model. FMI 2.0 improves this situation since model names are no longer used as prefix in case of DLL/Shared Objects: Therefore one DLL/Shared Object can be used for all models in case of tool coupling. If an FMU is imported into a simulation environment, this is usually performed dynamically (based on the FMU name, the corresponding FMU is loaded during execution of the simulation environment) and then it does not matter whether a model name is prefixed or not.]

Since “modelIdentifier” is used as prefix of a C-function name it must fulfill the restrictions on C-function names (only letters, digits and/or underscores are allowed). [For example if modelName = “A.B.C“, then modelIdentifier might be “A_B_C“]. Since “modelIdentifier” is also used as name in a file system, it must also fulfill the restrictions of the targeted operating system. Basically, this means that it should be short. For example the Windows API only supports full path-names of a file up to 260 characters (see: https://www.wendangku.net/doc/389916829.html,/en-us/library/aa365247%28VS.85%29.aspx).

2.1.2 Platform Dependent Definitions (fmi2TypesPlatform.h )

To simplify porting, no C types are used in the function interfaces, but the alias types defined in this section. All definitions in this section are provided in the header file “fmi2TypesPlatform.h”.

#define fmi2TypesPlatform "default"

A definition that can be inquired with fmi2GetTypesPlatform. It is used to uniquely identify the

header file used for compilation of a binary. [The “default” definition below is suitable for most

common platforms. It is recommended to use this “default” definition for all binary FMUs. Only for

source code FMUs, a change might be useful in some cases.]:

fmi2Component : an opaque object pointer

fmi2ComponentEnvironment: an opaque object pointer

fmi2FMUstate : an opaque object pointer

fmi2ValueReference : value handle type

fmi2Real : real data type

fmi2Integer : integer data type

fmi2Boolean : datatype to be used with fmi2True and

fmi2False

fmi2Char : character data type (size of one character)

fmi2String : pointer to a vector of fmi2Char characters

('\0' terminated, UTF8 encoded)

fmi2Byte : smallest addressable unit of the machine

(typically one byte)

typedef void* fmi2Component;

This is a pointer to an FMU specific data structure that contains the information needed to

process the model equations or to process the co-simulation of the respective slave. This data

structure is implemented by the environment that provides the FMU, in other words the calling

environment does not know its content and the code to process it must be provided by the FMU

generation environment and must be shipped with the FMU.

typedef void* fmi2ComponentEnvironment;

This is a pointer to a data structure in the simulation environment that calls the FMU. Via this

pointer, data from the modelDescription.xml file [(for example mapping of valueReferences to

variable names)] can be transferred between the simulation environment and the logger function

(see section 2.1.5).

typedef void* fmi2FMUstate;

This is a pointer to a data structure in the FMU that saves the internal FMU state of the actual or

a previous time instant. This allows to restart a simulation from a previous FMU state (see section

2.1.8)

typedef unsigned int fmi2ValueReference;

This is a handle to a (base type) variable value of the model. Handle and base type (such as

fmi2Real) uniquely identify the value of a variable. Variables of the same base type that have

the same handle, always have identical values, but other parts of the variable definition might be

different [(for example min/max attributes)].

All structured entities, like records or arrays, are “flattened” into a set of scalar values of type fmi2Real, fmi2Integer etc. An fmi2ValueReference references one such scalar. The

coding of fmi2ValueReference is a “secret” of the environment that generated the FMU. The

interface to the equations only provides access to variables via this handle. Extracting concrete

information about a variable is specific to the used environment that reads the Model Description

File in which the value handles are defined.

If a function in the following sections is called with a wrong “fmi2ValueReference” value [(for example setting a constant with a fmi2SetReal(..) function call)], then the function has to

return with an error (fmi2Status = fmi2Error, see section 2.1.3).

typedef double fmi2Real ; // Data type for floating point real numbers typedef int fmi2Integer; // Data type for signed integer numbers

typedef int fmi2Boolean; // Data type for Boolean numbers

// (only two values: fmi2False, fmi2True) typedef char fmi2Char; // Data type for one character

typedef const fmi2Char* fmi2String; // Data type for character strings

// (′\0′ terminated, UTF8 encoded)

typedef char fmi2Byte; // Data type for the smallest addressable // unit, typically one byte

#define fmi2True 1

#define fmi2False 0

These are the basic data types used in the interfaces of the C functions. More data types might

be included in future versions of the interface. In order to keep flexibility, especially for embedded

systems or for high performance computers, the exact data types or the word length of a number

are not standardized. Instead, the precise definition (in other words the header file

“fmi2TypesPlatform.h”) is provided by the environment where the FMU shall be used. In most

cases, the definition above will be used. If the target environment has different definitions and the

FMU is distributed in binary format, it must be newly compiled and linked with this target header

file.

If an fmi2String variable is passed as input argument to a FMI function and the FMU needs to use the string later, the FMI function must copy the string before it returns and store it in the

internal FMU memory, because there is no guarantee for the lifetime of the string after the function has returned.

If an fmi2String variable is passed as output argument from a FMI function and the string shall be used in the target environment, the target environment must copy the whole string (not

only the pointer). The memory of this string may be deallocated by the next call to any of the FMI

interface functions (the string memory might also be just a buffer, that is reused)

2.1.3 Status Returned by Functions

This section defines the “status” flag (an enumeration of type fmi2Status defined in file

“fmi2FunctionTypes.h”) that is returned by all functions to indicate the success of the function call:

typedef enum { fmi2OK,

fmi2Warning,

fmi2Discard,

fmi2Error,

fmi2Fatal,

fmi2Pending } fmi2Status;

Status returned by functions. The status has the following meaning

fmi2OK – all well

fmi2Warning – things are not quite right, but the computation can continue. Function “logger” was called in the model (see below) and it is expected that this function has shown the prepared

information message to the user.

fmi2Discard – this return status is only possible, if explicitly defined for the corresponding function3 (ModelExchange: fmi2SetReal, fmi2SetInteger, fmi2SetBoolean, fmi2SetString,

fmi2SetContinuousStates, fmi2GetReal, fmi2GetDerivatives,

fmi2GetContinuousStates,fmi2GetEventIndicators;

CoSimulation: fmi2SetReal, fmi2SetInteger, fmi2SetBoolean, fmi2SetString, fmi2DoStep, fmiGetXXXStatus):

For “model exchange”: It is recommended to perform a smaller step size and evaluate the model equations again, for example because an iterative solver in the model did not converge or because a function is outside of its domain (for example sqrt()). If this is not possible, the

simulation has to be terminated.

For “co-simulation”: fmi2Discard is returned also if the slave is not able to return the required

status information. The master has to decide if the simulation run can be continued.

In both cases, function “logger” was called in the FMU (see below) and it is expected that this

function has shown the prepared information message to the user if the FMU was called in debug

mode (loggingOn = fmi2True). Otherwise, “logger” should not show a message.

fmi2Error – the FMU encountered an error. The simulation cannot be continued with this FMU instance. If one of the functions returns fmi2Error, it can be tried to restart the simulation from a

formerly stored FMU state by calling fmi2SetFMUstate. This can be done if the capability flag

canGetAndSetFMUstate is true and fmu2GetFMUstate was called before in non-erroneous state. If not, the simulation cannot be continued and fmi2FreeInstance or fmi2Reset must be called

afterwards.4

Further processing is possible after this call; especially other FMU instances are not affected.

Function “logger” was called in the FMU (see below) and it is expected that this function has shown the prepared information message to the user.

fmi2Fatal – the model computations are irreparably corrupted for all FMU instances. [For example, due to a run-time exception such as access violation or integer division by zero during the execution of an fmi function]. Function “logger” was called in the FMU (see below) and it is expected that this function has shown the prepared information message to the user. It is not possible to call any other function for any of the FMU instances.

fmi2Pending – is returned only from the co-simulation interface, if the slave executes the function in an

3 Functions fmi2SetXXX are usually not performing calculations but just store the passed values in internal buffers. The actual calculation is performed by fmi2GetXXX functions. Still fmi2SetXXX functions could check whether the input arguments are in their validity range. If not, these functions could return with fmi2Discard.

4 Typically, fmi2Error return is for non-numerical reasons, like …disk full“. There might be cases where the environment can fix such errors (eventually with the help oft the user), and then simulation can continue at the last consistent state defined with fmi2SetFMUstate.

asynchronous way. That means the slave starts to compute but returns immediately. The master has to call fmi2GetStatus(..., fmi2DoStepStatus) to determine, if the slave has finished the

computation. Can be returned only by fmi2DoStep and by fmi2GetStatus (see section 4.2.3).

2.1.4 Inquire Platform and Version Number of Header Files

This section documents functions to inquire information about the header files used to compile its functions.

const char* fmi2GetTypesPlatform(void);

Returns the string to uniquely identify the “fmi2TypesPlatform.h” header file used for

compilation of the functions of the FMU. The function returns a pointer to a static string specified

by “fmi2TypesPlatform” defined in this header file. The standard header file, as documented in

this specification, has fmi2TypesPlatform set to “default” (so this function usually returns

“default”).

const char* fmi2GetVersion(void);

Returns the version of the “fmi2Functions.h” header file which was used to compile the

functions of the FMU. The function returns “fmiVersion” which is defined in this header file. The

standard header file as documented in this specification has version “2.0” (so this function

usually returns “2.0”).

2.1.5 Creation, Destruction and Logging of FMU Instances

This section documents functions that deal with instantiation, destruction and logging of FMUs.

fmi2Component fmi2Instantiate(fmi2String instanceName,

fmi2Type fmuType,

fmi2String fmuGUID,

fmi2String fmuResourceLocation,

const fmi2CallbackFunctions* functions, fmi2Boolean visible,

fmi2Boolean loggingOn);

typedef enum {fmi2ModelExchange,

fmi2CoSimulation

}fmi2Type;

The function returns a new instance of an FMU. If a null pointer is returned, then instantiation

failed. In that case, “functions->logger” was called with detailed information about the

reason. An FMU can be instantiated many times (provided capability flag

canBeInstantiatedOnlyOncePerProcess = false).

This function must be called successfully, before any of the following functions can be called.

For co-simulation, this function call has to perform all actions of a slave which are necessary

before a simulation run starts (for example loading the model file, compilation...).

Argument instanceName is a unique identifier for the FMU instance. It is used to name the

instance, for example in error or information messages generated by one of the fmi2XXX

functions. It is not allowed to provide a null pointer and this string must be non-empty (in

other words must have at least one character that is no white space). [If only one FMU is

simulated, as instanceName attribute modelName or

modelIdentifier=”..”> from the XML schema fmiModelDescription might be used.]

Argument fmuType defines the type of the FMU:

?= fmi2ModelExchange: FMU with initialization and events; between events simulation of continuous systems is performed with external integrators from the environment

(see section 3).

?= fmi2CoSimulation: Black box interface for co-simulation (see section 4).

Argument fmuGUID is used to check that the modelDescription.xml file (see section 2.3) is compatible with the C code of the FMU. It is a vendor specific globally unique identifier of the XML file (for example it is a “fingerprint” of the relevant information stored in the XML file). It is stored in the XML file as attribute “guid” (see section 2.2.1) and has to be passed to the

fmi2Instantiate function via argument fmuGUID. It must be identical to the one stored

inside the fmi2Instantiate function. Otherwise the C code and the XML file of the FMU are not consistent to each other. This argument cannot be null.

Argument fmuResourceLocation is an URI according to the IETF RFC3986 syntax to

indicate the location to the “resources” directory of the unzipped FMU archive. The

following schemes must be understood by the FMU:

?Mandatory: “file” with absolute path (either including or omitting the authority component) ?Optional: “http”, “https”, “ftp”

?Reserved: “fmi2” for FMI for PLM.

[Example: An FMU is unzipped in directory “C:\temp\MyFMU”, then

fmuResourceLocation = "file:///C:/temp/MyFMU/resources" or

"file:/C:/temp/MyFMU/resources". Function fmi2Instantiate is then able to read all needed resources from this directory, for example maps or tables used by the FMU.]

Argument functions provides callback functions to be used from the FMU functions to

utilize resources from the environment (see type fmi2CallbackFunctions below).

Argument visible = fmi2False defines that the interaction with the user should be

reduced to a minimum (no application window, no plotting, no animation, etc.), in other words the FMU is executed in batch mode. If visible = fmi2True, the FMU is executed in

interactive mode and the FMU might require to explicitly acknowledge start of simulation /

instantiation / initialization (acknowledgment is non-blocking).

If loggingOn=fmi2True, debug logging is enabled. If loggingOn=fmi2False, debug

logging is disabled. [The FMU enable/disables LogCategories which are useful for

debugging according to this argument. Which LogCategories the FMU sets is unspecified.]

typedef struct {

void (*logger)(fmi2ComponentEnvironment componentEnvironment,

fmi2String instanceName,

fmi2Status status,

fmi2String category,

fmi2String message, ...);

void* (*allocateMemory)(size_t nobj, size_t size);

void (*freeMemory) (void* obj);

void (*stepFinished) (fmi2ComponentEnvironment componentEnvironment,

fmi2Status status);

fmi2ComponentEnvironment componentEnvironment;

} fmi2CallbackFunctions;

The struct contains pointers to functions provided by the environment to be used by the

FMU. It is not allowed to change these functions between fmi2Instantiate(..) and

fmi2Terminate(..) calls. Additionally, a pointer to the environment is provided

(componentEnvironment) that needs to be passed to the “logger” function, in order that the

logger function can utilize data from the environment, such as mapping a valueReference to a string. In the unlikely case that fmi2Component is also needed in the logger, it has to be passed via argument componentEnvironment. Argument componentEnvironment may be a null pointer.

The componentEnvironment pointer is also passed to the stepFinished(..) function in order that the environment can provide an efficient way to identify the slave that called stepFinished(..).

In the default fmi2FunctionTypes.h file, typedef s for the function definitions are present to simplify the usage. This is non-normative. The functions have the following meaning:

Function logger:

Pointer to a function that is called in the FMU, usually if a fmi2XXX function does not behave as desired. If “logger” is called with “status = fmi2OK”, then the message is a pure information message. “instanceName” is the instance name of the model that calls this function. “category” is the category of the message. The meaning of “category” is defined by the modeling environment that generated the FMU. Depending on this modeling environment, none, some or all allowed values of “category” for this FMU are defined in the modelDescription.xml file via element “”, see section 2.2.4. Only messages are provided by function logger that have a category according to a call to fmi2SetDebugLogging (see below). Argument “message” is provided in the same way and with the same format control as in function “printf” from the C standard library. [Typically, this function prints the message and stores it optionally in a log file.]

All string-valued arguments passed by the FMU to the logger may be deallocated by the FMU directly after function logger returns. The environment must therefore create copies of these strings if it needs to access these strings later.

The logger function will append a line break to each message when writing messages after each other to a terminal or a file (the messages may also be shown in other ways, for example as separate text-boxes in a GUI). The caller may include line-breaks (using "\n") within the message, but should avoid trailing line breaks.

Variables are referenced in a message with “##” where

is “r” for fmi2Real, “i” for fmi2Integer, “b” for fmi2Boolean and “s” for

fmi2String. If character “#”shall be included in the message, it has to be prefixed with “#”, so “#” is an escape character. [Example:

A message of the form

“#r1365# must be larger than zero (used in IO channel ##4)”

might be changed by the logger function to

“body.m must be larger than zero (used in IO channel #4)”

if “body.m” is the name of the fmi2Real variable with fmi2ValueReference =

1365.]

Function allocateMemory:

Pointer to a function that is called in the FMU if memory needs to be allocated. If attribute “canNotUseMemoryManagementFunctions = true” in

, then function allocateMemory is not used in the FMU and a void pointer can be provided. If this attribute has a value of “false” (which is the default), the FMU must not use malloc, calloc or other memory allocation functions. One reason is that these functions might not be available for embedded systems on the target machine. Another reason is that the environment may have optimized or specialized memory allocation functions. allocateMemory returns a

相关文档