Claudio Gomes 7 gadi atpakaļ
vecāks
revīzija
e60d316d73

+ 37 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/parser/stack.h

@@ -0,0 +1,37 @@
+/*
+ * Copyright QTronic GmbH. All rights reserved.
+ */
+
+/* -------------------------------------------------------------------------
+ * stack.c
+ * A stack of pointers.
+ * Author: Jakob Mauss, January 2010.
+ * -------------------------------------------------------------------------*/
+
+#ifndef STACK_H
+#define STACK_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+    void** stack;
+    int stackSize;    // allocated size of stack
+    int stackPos;     // array index of top element, -1 if stack is empty.
+    int initialSize;  // how many element to allocate initially
+    int inc;          // how many elements to allocate when stack gets full
+} Stack;
+
+Stack* stackNew(int initialSize, int inc);
+int stackIsEmpty(Stack* s);
+int stackPush(Stack* s, void* e);
+void* stackPeek(Stack* s);
+void* stackPop(Stack* s);
+void** stackPopAllAsArray(Stack* s, int *size);
+void** stackLastPopedAsArray0(Stack* s, int n);
+void stackFree(Stack* s);
+
+#ifdef __cplusplus
+} // closing brace for extern "C"
+#endif
+#endif // STACK_H

+ 960 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/parser/xml_parser.c

@@ -0,0 +1,960 @@
+/*
+ * Copyright QTronic GmbH. All rights reserved.
+ */
+
+/* -------------------------------------------------------------------------
+ * xml_Parser.c
+ * A parser for file modelVariables.xml of an FMU.
+ * The parser creates an AST (abstract syntax tree) for a given XML file.
+ * The root node of the AST is of type ModelDescription.
+ * Validation already performed by this parser
+ * - check for match of open/close elements (performed by Expat)
+ * - check element, attribute and enum value names, all case sensitive
+ * - check for each element that is has the expected parent element
+ * - check for correct sequence of elements
+ * - check for each attribute value that it is of the expected type
+ * - check that all declaredType values reference an existing Type
+ * Validation to be performed by this parser
+ * - check that required attributes are present
+ * - check that dependencies are only declared for outputs and
+ *   refer only to inputs
+ * Author: Jakob Mauss, January 2010.
+ * -------------------------------------------------------------------------*/
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef STANDALONE_XML_PARSER
+#define logThis(n, ...) printf(__VA_ARGS__);printf("\n")
+#else
+#include "GlobalIncludes.h"
+#include "logging.h" // logThis
+#endif // STANDALONE_XML_PARSER
+
+#include "xml_parser.h"
+
+const char *elmNames[SIZEOF_ELM] = {
+    "fmiModelDescription","UnitDefinitions","BaseUnit","DisplayUnitDefinition","TypeDefinitions",
+    "Type","RealType","IntegerType","BooleanType","StringType","EnumerationType","Item",
+    "DefaultExperiment","VendorAnnotations","Tool","Annotation", "ModelVariables","ScalarVariable",
+    "DirectDependency", "Name", "Real","Integer","Boolean","String","Enumeration",
+    "Implementation","CoSimulation_StandAlone","CoSimulation_Tool","Model","File","Capabilities"
+};
+
+const char *attNames[SIZEOF_ATT] = {
+    "fmiVersion","displayUnit","gain","offset","unit","name","description","quantity", "relativeQuantity",
+    "min","max","nominal","declaredType","start","fixed","startTime","stopTime","tolerance","value",
+    "valueReference","variability","causality","alias", "modelName","modelIdentifier","guid","author",
+    "version","generationTool","generationDateAndTime","variableNamingConvention","numberOfContinuousStates",
+    "numberOfEventIndicators","input",
+    "canHandleVariableCommunicationStepSize","canHandleEvents","canRejectSteps","canInterpolateInputs",
+    "maxOutputDerivativeOrder","canRunAsynchronuously","canSignalEvents","canBeInstantiatedOnlyOncePerProcess",
+    "canNotUseMemoryManagementFunctions","file","entryPoint","manualStart","type"
+};
+
+const char *enuNames[SIZEOF_ENU] = {
+    "flat","structured","constant","parameter","discrete","continuous",
+    "input","output", "internal","none","noAlias","alias","negatedAlias"
+};
+
+#define XMLBUFSIZE 1024
+char text[XMLBUFSIZE];       // XML file is parsed in chunks of length XMLBUFZIZE
+XML_Parser parser = NULL;    // non-NULL during parsing
+Stack* stack = NULL;         // the parser stack
+char* data = NULL;           // buffer that holds element content, see handleData
+int skipData=0;              // 1 to ignore element content, 0 when recording content
+
+// -------------------------------------------------------------------------
+// Low-level functions for inspecting the model description 
+
+const char* getString(void* element, Att a){
+    Element* e = (Element*)element;
+    const char** attr = e->attributes;
+    int i;
+    for (i=0; i<e->n; i+=2)
+        if (attr[i]==attNames[a]) return attr[i+1];
+    return NULL;
+}
+
+double getDouble(void* element, Att a, ValueStatus* vs){
+    double d = 0;
+    const char* value = getString(element, a);
+    if (!value) { *vs=valueMissing; return d; }
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;
+    return d;
+}
+
+// getInt() is also used to retrieve Enumeration values from XML,
+// e.g. the start value for a variable of user-defined enumeration type.
+int getInt(void* element, Att a, ValueStatus* vs){
+    int n = 0;
+    const char* value = getString(element, a);
+    if (!value) { *vs=valueMissing; return n; }
+    *vs = (1==sscanf(value, "%d", &n)) ? valueDefined : valueIllegal;
+    return n;
+}
+
+unsigned int getUInt(void* element, Att a, ValueStatus* vs){
+    unsigned int u = -1;
+    const char* value = getString(element, a);
+    if (!value) { *vs=valueMissing; return u; }
+    *vs = (1==sscanf(value, "%u", &u)) ? valueDefined : valueIllegal;
+    return u;
+}
+
+char getBoolean(void* element, Att a, ValueStatus* vs){
+    const char* value = getString(element, a);
+    if (!value) { *vs=valueMissing; return 0; };
+    *vs = valueDefined;
+    if (!strcmp(value, "true")) return 1;
+    if (!strcmp(value, "false")) return 0;
+    *vs = valueIllegal;
+    return 0;
+}
+
+static Enu checkEnumValue(const char* enu);
+
+// Retrieve the value of the given built-in enum attribute.
+// If the value is missing, this is marked in the ValueStatus
+// and the corresponding default is returned.
+// Returns enu_BAD_DEFINED or a globally unique id for the value such that
+// enuNames[id] is the string representation of the enum value.
+Enu getEnumValue(void* element, Att a, ValueStatus* vs) {
+    const char* value = getString(element, a);
+    Enu id;
+    *vs = valueDefined;
+    if (!value) {
+        *vs = valueMissing;
+        switch (a) {
+            case att_variableNamingConvention: return enu_flat;
+            case att_variability: return enu_continuous;
+            case att_causality: return enu_internal;
+            case att_alias: return enu_noAlias;
+            default: return enu_BAD_DEFINED;
+        }
+    }
+    id = checkEnumValue(value);
+    if (id == enu_BAD_DEFINED) *vs = valueIllegal;
+    return id;
+}
+
+// -------------------------------------------------------------------------
+// Convenience methods for accessing the model description. 
+// Use is only safe after the ast has been successfully validated.
+
+const char* getModelIdentifier(ModelDescription* md) {
+    const char* modelId = getString(md, att_modelIdentifier);
+    assert(modelId); // this is a required attribute
+    return modelId;
+}
+
+int getNumberOfStates(ModelDescription* md) {
+    ValueStatus vs;
+    int n = getUInt(md, att_numberOfContinuousStates, &vs);
+    assert(vs==valueDefined); // this is a required attribute
+    return n;
+}
+
+int getNumberOfEventIndicators(ModelDescription* md) {
+    ValueStatus vs;
+    int n = getInt(md, att_numberOfEventIndicators, &vs);
+    assert(vs==valueDefined); // this is a required attribute
+    return n;
+}
+
+// name is a required attribute of ScalarVariable, Type, Item, Annotation, and Tool
+const char* getName(void* element) { 
+    const char* name = getString(element, att_name);
+    assert(name); // this is a required attribute
+    return name;
+}
+
+// returns one of: input, output, internal, none
+// if value is missing, the default internal is returned
+Enu getCausality(void* scalarVariable) {
+    ValueStatus vs;
+    return getEnumValue(scalarVariable, att_causality, &vs);
+}
+
+// returns one of constant, parameter, discrete, continuous
+// if value is missing, the default continuous is returned
+Enu getVariability(void* scalarVariable) {
+    ValueStatus vs;
+    return getEnumValue(scalarVariable, att_variability, &vs);
+}
+
+// returns one of noAlias, alias, negatedAlias
+// if value is missing, the default noAlias is returned
+Enu getAlias(void* scalarVariable) {
+    ValueStatus vs;
+    return getEnumValue(scalarVariable, att_alias, &vs);
+}
+
+// the vr is unique only for one of the 4 base data types r,i,b,s and
+// may also be fmiUndefinedValueReference = 4294967295 = 0xFFFFFFFF
+// here, i means integer or enumeration
+fmiValueReference getValueReference(void* scalarVariable) {
+    ValueStatus vs;
+    fmiValueReference vr = getUInt(scalarVariable, att_valueReference, &vs);
+    assert(((Element*)scalarVariable)->type == elm_ScalarVariable);
+    assert(vs==valueDefined); // this is a required attribute
+    return vr;
+}
+
+// the name is unique within a fmu
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name) {
+    int i;
+    if (md->modelVariables) {
+        for (i=0; md->modelVariables[i]; i++){
+            ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];
+            if (!strcmp(getName(sv), name)) return sv;
+        }
+    }
+    return NULL;
+}
+
+// Enumeration and Integer have the same base type while
+// Real, String, Boolean define own base types.
+int sameBaseType(Elm t1, Elm t2){
+    return t1==t2 ||
+           t1==elm_Enumeration && t2==elm_Integer ||
+           t2==elm_Enumeration && t1==elm_Integer;
+}
+
+// returns NULL if variable not found or vr==fmiUndefinedValueReference
+// problem: vr/type in not a unique key, may return alias
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){
+    int i;
+    if (md->modelVariables && vr!=fmiUndefinedValueReference)
+    for (i=0; md->modelVariables[i]; i++){
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];
+        if (sameBaseType(type, sv->typeSpec->type) && getValueReference(sv) == vr)
+            return sv;
+    }
+    return NULL;
+}
+
+// returns NULL if variable not found or vr==fmiUndefinedValueReference
+// problem: vr/type in not a unique key, return just the non alias variable
+ScalarVariable* getNonAliasVariable(ModelDescription* md, fmiValueReference vr, Elm type){
+    int i;
+    if (md->modelVariables && vr!=fmiUndefinedValueReference)
+    for (i=0; md->modelVariables[i]; i++){
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];
+        if (sameBaseType(type, sv->typeSpec->type) && getValueReference(sv) == vr && getAlias(sv) == enu_noAlias)
+            return sv;
+    }
+    return NULL;
+}
+
+Type* getDeclaredType(ModelDescription* md, const char* declaredType){
+    int i;
+    if (declaredType && md->typeDefinitions)
+    for (i=0; md->typeDefinitions[i]; i++){
+        Type* tp = (Type*)md->typeDefinitions[i];
+        if (!strcmp(declaredType, getName(tp))) return tp;
+    }
+    return NULL;
+}
+
+// Get attribute value from variable or from declared type, or NULL.
+const char* getString2(ModelDescription* md, void* tp, Att a) {
+    Type* type;
+    const char* value = getString(tp, a);
+    if (value) return value; // found
+    // search declared type, if any
+    type = getDeclaredType(md, getString(tp, att_declaredType));
+    return type ? getString(type->typeSpec, a) : NULL;
+}
+
+// Get description from variable or from declared type, or NULL.
+const char * getDescription(ModelDescription* md, ScalarVariable* sv){
+    const char* value = getString(sv, att_description);
+    Type* type;
+    if (value) return value; // found
+    // search declared type, if any
+    type = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));
+    return type ? getString(type, att_description) : NULL;
+}
+
+// Get attribute value from scalar variable given by vr and type,
+// incl. default value provided by declared type, if any.
+const char *getVariableAttributeString(ModelDescription* md, 
+        fmiValueReference vr, Elm type, Att a) {
+    const char* value;
+    Type* tp;
+    ScalarVariable* sv = getVariable(md, vr, type);
+    if (!sv) return NULL;
+    value = getString(sv->typeSpec, a);
+    if (value) return value; // found
+    // search declared type, if any
+    tp = getDeclaredType(md, getString(sv->typeSpec, att_declaredType));
+    return tp ? getString(tp->typeSpec, a) : NULL;
+}
+
+// Get attribute value from scalar variable given by vr and type,
+// incl. default value provided by declared type, if any.
+double getVariableAttributeDouble(ModelDescription* md, 
+        fmiValueReference vr, Elm type, Att a, ValueStatus* vs){
+    double d = 0;
+    const char* value = getVariableAttributeString(md, vr, type, a);
+    if (!value) { *vs = valueMissing; return d; }
+    *vs = (1==sscanf(value, "%lf", &d)) ? valueDefined : valueIllegal;
+    return d;
+}
+
+// Get nominal value from real variable or its declared type.
+// Return 1, if no nominal value is defined.
+double getNominal(ModelDescription* md, fmiValueReference vr){
+    ValueStatus vs;
+    double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs);
+    return vs==valueDefined ? nominal : 1.0;
+}
+
+// -------------------------------------------------------------------------
+// Various checks that log an error and stop the parser 
+
+// Returns 0 to indicate error
+static int checkPointer(const void* ptr){
+    if (! ptr) {
+        logThis(ERROR_FATAL, "Out of memory");
+        if (parser) XML_StopParser(parser, XML_FALSE);
+        return 0; // error
+    }
+    return 1; // success
+}
+
+static int checkName(const char* name, const char* kind, const char* array[], int n){
+    int i;
+    for (i=0; i<n; i++) {
+        if (!strcmp(name, array[i])) return i;
+    }
+    logThis(ERROR_FATAL, "Illegal %s %s", kind, name);
+    XML_StopParser(parser, XML_FALSE);
+    return -1;
+}
+
+// Returns elm_BAD_DEFINED to indicate error
+static Elm checkElement(const char* elm){
+    return (Elm)checkName(elm, "element", elmNames, SIZEOF_ELM);
+}
+
+// Returns att_BAD_DEFINED to indicate error
+static Att checkAttribute(const char* att){
+    return (Att)checkName(att, "attribute", attNames, SIZEOF_ATT);
+}
+
+// Returns enu_BAD_DEFINED to indicate error
+static Enu checkEnumValue(const char* enu){
+    return (Enu)checkName(enu, "enum value", enuNames, SIZEOF_ENU);
+}
+
+static void logFatalTypeError(const char* expected, Elm found) {
+    logThis(ERROR_FATAL, "Wrong element type, expected %s, found %s",
+            expected, elmNames[found]);
+    XML_StopParser(parser, XML_FALSE);
+}
+
+// Returns 0 to indicate error
+// Verify that Element elm is of the given type
+static int checkElementType(void* element, Elm e) {
+    Element* elm = (Element* )element;
+    if (elm->type == e) return 1; // success
+    logFatalTypeError(elmNames[e], elm->type);
+    return 0; // error
+}
+
+// Returns 0 to indicate error
+// Verify that the next stack element exists and is of the given type
+// If e==elm_BAD_DEFINED, the type check is omitted
+static int checkPeek(Elm e) {
+    if (stackIsEmpty(stack)) {
+        logThis(ERROR_FATAL, "Illegal document structure, expected %s",
+            e==elm_BAD_DEFINED ? "xml element" : elmNames[e]);
+        XML_StopParser(parser, XML_FALSE);
+        return 0; // error
+    }
+    return e==elm_BAD_DEFINED ? 1 : checkElementType(stackPeek(stack), e);
+}
+
+// Returns NULL to indicate error
+// Get the next stack element, it is of the given type.
+// If e==elm_BAD_DEFINED, the type check is omitted
+static void* checkPop(Elm e){
+    return checkPeek(e) ? stackPop(stack) : NULL;
+}
+
+// -------------------------------------------------------------------------
+// Helper
+
+AstNodeType getAstNodeType(Elm e){
+    switch (e) {
+    case elm_fmiModelDescription:
+        return astModelDescription;
+    case elm_Type:
+        return astType;
+    case elm_ScalarVariable:
+        return astScalarVariable;
+    case elm_CoSimulation_StandAlone:
+    case elm_CoSimulation_Tool:
+        return astCoSimulation;
+    case elm_BaseUnit:
+    case elm_EnumerationType:
+    case elm_Tool:
+    case elm_UnitDefinitions:
+    case elm_TypeDefinitions:
+    case elm_VendorAnnotations:
+    case elm_ModelVariables:
+    case elm_DirectDependency:
+    case elm_Model:
+        return astListElement;
+    default:
+        return astElement;
+    }
+}
+
+// Returns 0 to indicate error
+// Copies the attr array and all values.
+// Replaces all attribute names by constant literal strings.
+// Converts the null-terminated array into an array of known size n.
+int addAttributes(Element* el, const char** attr) {
+    int n;
+    Att a;
+    const char** att = NULL;
+    for (n=0; attr[n]; n+=2);
+    if (n>0) {
+        att = (const char **)calloc(n, sizeof(char*));
+        if (!checkPointer(att)) return 0;
+    }
+    for (n=0; attr[n]; n+=2) {
+        char* value = strdup(attr[n+1]);
+        if (!checkPointer(value)) {
+            free((void *)att);
+            return 0;
+        }
+        a = checkAttribute(attr[n]);
+        if (a == att_BAD_DEFINED) {
+            free(value);
+            free((void *)att);
+            return 0;  // illegal attribute error
+        }
+        att[n  ] = attNames[a]; // no heap memory
+        att[n+1] = value;       // heap memory
+    }
+    el->attributes = att; // NULL if n=0
+    el->n = n;
+    return 1; // success
+}
+
+// Returns NULL to indicate error
+Element* newElement(Elm type, int size, const char** attr) {
+    Element* e = (Element*)calloc(1, size);
+    if (!checkPointer(e)) return NULL;
+    e->type = type;
+    e->attributes = NULL;
+    e->n=0;
+    if (!addAttributes(e, attr)) {
+        free(e);
+        return NULL;
+    }
+    return e;
+}
+
+// -------------------------------------------------------------------------
+// callback functions called by the XML parser 
+
+// Create and push a new element node
+static void XMLCALL startElement(void *context, const char *elm, const char **attr) {
+    Elm el;
+    void* e;
+    int size;
+    //logThis(ERROR_INFO, "start %s", elm);
+    el = checkElement(elm);
+    if (el==elm_BAD_DEFINED) return; // error
+    skipData = (el != elm_Name); // skip element content for all elements but Name
+    switch(getAstNodeType(el)){
+        case astElement:          size = sizeof(Element); break;
+        case astListElement:      size = sizeof(ListElement); break;
+        case astType:             size = sizeof(Type); break;
+        case astScalarVariable:   size = sizeof(ScalarVariable); break;
+        case astCoSimulation:     size = sizeof(CoSimulation); break;
+        case astModelDescription: size = sizeof(ModelDescription); break;
+        default: assert(0);
+    }
+    e = newElement(el, size, attr);
+    if (checkPointer(e)) stackPush(stack, e);
+}
+
+// Pop all elements of the given type from stack and
+// add it to the ListElement that follows.
+// The ListElement remains on the stack.
+static void popList(Elm e) {
+    int n = 0;
+    Element** array;
+    Element* elm = (Element *)stackPop(stack);
+    while (elm->type == e) {
+        elm = (Element *)stackPop(stack);
+        n++;
+    }
+    stackPush(stack, elm); // push ListElement back to stack
+    array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list
+    if (getAstNodeType(elm->type)!=astListElement) {
+        free(array);
+        return; // failure
+    }
+    ((ListElement*)elm)->list = array;
+    return; // success only if list!=NULL
+}
+
+// Pop the children from the stack and
+// check for correct type and sequence of children
+static void XMLCALL endElement(void *context, const char *elm) {
+    Elm el;
+    //logThis(ERROR_INFO, "  end %s", elm);
+    el = checkElement(elm);
+    switch(el) {
+        case elm_fmiModelDescription:
+            {
+                 ModelDescription* md;
+                 ListElement** ud = NULL;     // NULL or list of BaseUnits
+                 Type**        td = NULL;     // NULL or list of Types
+                 Element*      de = NULL;     // NULL or DefaultExperiment
+                 ListElement** va = NULL;     // NULL or list of Tools
+                 ScalarVariable** mv = NULL;  // NULL or list of ScalarVariable
+                 CoSimulation *cs = NULL;     // NULL or CoSimulation
+                 ListElement* child;
+
+                 child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                 if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) {
+                     cs = (CoSimulation*)child;
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 if (child->type == elm_ModelVariables){
+                     mv = (ScalarVariable**)child->list;
+                     free(child);
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 if (child->type == elm_VendorAnnotations){
+                     va = (ListElement**)child->list;
+                     free(child);
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 if (child->type == elm_DefaultExperiment){
+                     de = (Element*)child;
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 if (child->type == elm_TypeDefinitions){
+                     td = (Type**)child->list;
+                     free(child);
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 if (child->type == elm_UnitDefinitions){
+                     ud = (ListElement**)child->list;
+                     free(child);
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+                 // work around bug of SimulationX 3.x which places Implementation at wrong location
+                 if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) {
+                     cs = (CoSimulation*)child;
+                     child = (ListElement *)checkPop(elm_BAD_DEFINED);
+                     if (!child) return;
+                 }
+
+                 if (!checkElementType(child, elm_fmiModelDescription)) return;
+                 md = (ModelDescription*)child;
+                 md->modelVariables = mv;
+                 md->vendorAnnotations = va;
+                 md->defaultExperiment = de;
+                 md->typeDefinitions = td;
+                 md->unitDefinitions = ud;
+                 md->cosimulation = cs;
+                 stackPush(stack, md);
+                 break;
+            }
+        case elm_Implementation:
+            {
+                 // replace Implementation element
+                 void* cs = checkPop(elm_BAD_DEFINED);
+                 void* im = checkPop(elm_Implementation);
+                 if (!cs || !im) return;
+                 stackPush(stack, cs);
+                 //printf("im=%x att=%x\n",im,((Element*)im)->attributes);
+                 free(im);
+                 el = ((Element*)cs)->type;
+                 break;
+            }
+        case elm_CoSimulation_StandAlone:
+            {
+                 Element* ca = (Element *)checkPop(elm_Capabilities);
+                 CoSimulation* cs = (CoSimulation *)checkPop(elm_CoSimulation_StandAlone);
+                 if (!ca || !cs) return;
+                 cs->capabilities = ca;
+                 stackPush(stack, cs);
+                 break;
+            }
+        case elm_CoSimulation_Tool:
+            {
+                 ListElement* mo = (ListElement *)checkPop(elm_Model);
+                 Element* ca = (Element *)checkPop(elm_Capabilities);
+                 CoSimulation* cs = (CoSimulation *)checkPop(elm_CoSimulation_Tool);
+                 if (!ca || !mo || !cs) return;
+                 cs->capabilities = ca;
+                 cs->model = mo;
+                 stackPush(stack, cs);
+                 break;
+            }
+        case elm_Type:
+            {
+                Type* tp;
+                Element* ts = (Element *)checkPop(elm_BAD_DEFINED);
+                if (!ts) return;
+                if (!checkPeek(elm_Type)) return;
+                tp = (Type*)stackPeek(stack);
+                switch (ts->type) {
+                    case elm_RealType:
+                    case elm_IntegerType:
+                    case elm_BooleanType:
+                    case elm_StringType:
+                    case elm_EnumerationType:
+                        break;
+                    default:
+                         logFatalTypeError("RealType or similar", ts->type);
+                         return;
+                }
+                tp->typeSpec = ts;
+                break;
+            }
+        case elm_ScalarVariable:
+            {
+                ScalarVariable* sv;
+                Element** list = NULL;
+                Element* child = (Element *)checkPop(elm_BAD_DEFINED);
+                if (!child) return;
+                if (child->type==elm_DirectDependency){
+                    list = ((ListElement*)child)->list;
+                    free(child);
+                    child = (Element *)checkPop(elm_BAD_DEFINED);
+                    if (!child) return;
+                }
+                if (!checkPeek(elm_ScalarVariable)) return;
+                sv = (ScalarVariable*)stackPeek(stack);
+                switch (child->type) {
+                    case elm_Real:
+                    case elm_Integer:
+                    case elm_Boolean:
+                    case elm_String:
+                    case elm_Enumeration:
+                        break;
+                    default:
+                         logFatalTypeError("Real or similar", child->type);
+                         return;
+                }
+                sv->directDependencies = list;
+                sv->typeSpec = child;
+                break;
+            }
+        case elm_ModelVariables:    popList(elm_ScalarVariable); break;
+        case elm_VendorAnnotations: popList(elm_Tool);break;
+        case elm_Tool:              popList(elm_Annotation); break;
+        case elm_TypeDefinitions:   popList(elm_Type); break;
+        case elm_EnumerationType:   popList(elm_Item); break;
+        case elm_UnitDefinitions:   popList(elm_BaseUnit); break;
+        case elm_BaseUnit:          popList(elm_DisplayUnitDefinition); break;
+        case elm_DirectDependency:  popList(elm_Name); break;
+        case elm_Model:             popList(elm_File); break;
+        case elm_Name:
+            {
+                 // Exception: the name value is represented as element content.
+                 // All other values of the XML file are represented using attributes.
+                 Element* name = (Element *)checkPop(elm_Name);
+                 if (!name) return;
+                 name->n = 2;
+                 name->attributes = (const char **)malloc(2*sizeof(char*));
+                 name->attributes[0] = attNames[att_input];
+                 name->attributes[1] = data;
+                 data = NULL;
+                 skipData = 1; // stop recording element content
+                 stackPush(stack, name);
+                 break;
+            }
+        case elm_BAD_DEFINED: return; // illegal element error
+        default: // must be a leaf Element
+                 assert(getAstNodeType(el)==astElement);
+                 break;
+    }
+    // All children of el removed from the stack.
+    // The top element must be of type el now.
+    checkPeek(el);
+}
+
+// Called to handle element data, e.g. "xy" in <Name>xy</Name>
+// Can be called many times, e.g. with "x" and then with "y" in the example above.
+// Feature in expat:
+// For some reason, if the element data is the empty string (Eg. <a></a>)
+// instead of an empty string with len == 0 we get "\n". The workaround is
+// to replace this with the empty string whenever we encounter "\n".
+void XMLCALL handleData(void *context, const XML_Char *s, int len) {
+    int n;
+    if (skipData) return;
+    if (!data) {
+        // start a new data string
+        if (len == 1 && s[0] == '\n') {
+            data = strdup("");
+        } else {
+            data = (char *)malloc(len + 1);
+            strncpy(data, s, len);
+            data[len] = '\0';
+        }
+    }
+    else {
+        // continue existing string
+        n = strlen(data) + len;
+        data = (char *)realloc(data, n+1);
+        strncat(data, s, len);
+        data[n] = '\0';
+    }
+    return;
+}
+
+
+#ifdef STANDALONE_XML_PARSER
+// -------------------------------------------------------------------------
+// printing
+ 
+static void printList(int indent, void** list);
+
+void printElement(int indent, void* element){
+    int i;
+    Element* e = (Element*)element;
+    if (!e) return;
+    // print attributes
+    for (i=0; i<indent; i++) printf(" ");
+    printf("%s", elmNames[e->type]);
+    for (i=0; i<e->n; i+=2)
+        printf(" %s=%s", e->attributes[i], e->attributes[i+1]);
+    printf("\n");
+    // print child nodes
+    indent += 2;
+    switch (getAstNodeType(e->type)) {
+        case astElement:
+            // we already printed the attributes
+            break;
+        case astListElement:
+            printList(indent, (void **)((ListElement*)e)->list);
+            break;
+        case astScalarVariable:
+            printElement(indent, ((Type*)e)->typeSpec);
+            printList(indent, (void **)((ScalarVariable*)e)->directDependencies);
+            break;
+        case astType:
+            printElement(indent, ((Type*)e)->typeSpec);
+            break;
+        case astCoSimulation: {
+            CoSimulation* cs = (CoSimulation*)e;
+            printElement(indent, cs->capabilities);
+            printElement(indent, cs->model);
+            break;
+        }
+        case astModelDescription: {
+            ModelDescription *md = (ModelDescription*)e;
+            printList(indent, (void **)md->unitDefinitions);
+            printList(indent, (void **)md->typeDefinitions);
+            printElement(indent, md->defaultExperiment);
+            printList(indent, (void **)md->vendorAnnotations);
+            printList(indent, (void **)md->modelVariables);
+            printElement(indent, md->cosimulation);
+            break;
+        }
+    }
+}
+
+static void printList(int indent, void** list){
+    int i;
+    if (list) for (i=0; list[i]; i++)
+        printElement(indent, list[i]);
+}
+
+#endif // STANDALONE_XML_PARSER
+
+// -------------------------------------------------------------------------
+// free memory of the AST
+
+static void freeList(void** list);
+
+void freeElement(void* element){
+    int i;
+    Element* e = (Element *)element;
+    if (!e) return;
+    // free attributes
+    for (i=0; i<e->n; i+=2)
+        free((void *)e->attributes[i+1]);
+    if (e->attributes) free((void *)e->attributes);
+    // free child nodes
+    switch (getAstNodeType(e->type)) {
+        case astElement:
+            // we already freed the attributes
+            break;
+        case astListElement:
+            freeList((void **)((ListElement*)e)->list);
+            break;
+        case astScalarVariable:
+            freeList((void **)((ScalarVariable*)e)->directDependencies);
+        case astType:
+            freeElement(((Type*)e)->typeSpec);
+            break;
+        case astCoSimulation: {
+            CoSimulation* cs = (CoSimulation*)e;
+            freeElement(cs->capabilities);
+            freeElement(cs->model);
+            break;
+        }
+        case astModelDescription: {
+            ModelDescription* md = (ModelDescription*)e;
+            freeList((void **)md->unitDefinitions);
+            freeList((void **)md->typeDefinitions);
+            freeElement(md->defaultExperiment);
+            freeList((void **)md->vendorAnnotations);
+            freeList((void **)md->modelVariables);
+            freeElement(md->cosimulation);
+            break;
+        }
+    }
+    // free the struct
+    free(e);
+}
+
+static void freeList(void** list){
+    int i;
+    if (!list) return;
+    for (i=0; list[i]; i++)
+        freeElement(list[i]);
+    free(list);
+}
+
+// -------------------------------------------------------------------------
+// Validation - done after parsing to report all errors 
+
+ModelDescription* validate(ModelDescription* md) {
+    int error = 0;
+    int i;
+    if (md->modelVariables)
+    for (i=0; md->modelVariables[i]; i++){
+        ScalarVariable* sv = (ScalarVariable*)md->modelVariables[i];
+        const char* declaredType = getString(sv->typeSpec, att_declaredType);
+        Type* declType = getDeclaredType(md, declaredType);
+        if (declaredType && declType==NULL) {
+            logThis(ERROR_WARNING, "Declared type %s of variable %s not found in modelDescription.xml", declaredType, getName(sv));
+            error++;
+        }
+    }
+    if (error) {
+        logThis(ERROR_ERROR, "Found %d error in modelDescription.xml", error);
+        return NULL;
+    }
+    return md;
+}
+
+// -------------------------------------------------------------------------
+// Entry function parse() of the XML parser 
+
+static void cleanup(FILE *file) {
+    stackFree(stack);
+    stack = NULL;
+    XML_ParserFree(parser);
+    parser = NULL;
+    fclose(file);
+}
+
+ModelDescription* parse_encoding(const char* xmlPath, const char *encoding) {
+    ModelDescription* md = NULL;
+    FILE *file;
+    int done = 0;
+    stack = stackNew(100, 10);
+    if (!checkPointer(stack)) return NULL; // failure
+    parser = XML_ParserCreate(encoding);
+    if (!checkPointer(parser)) return NULL; // failure
+    XML_SetElementHandler(parser, startElement, endElement);
+    XML_SetCharacterDataHandler(parser, handleData);
+    file = fopen(xmlPath, "rb");
+    if (file == NULL) {
+        logThis(ERROR_ERROR, "Cannot open file '%s'", xmlPath);
+        XML_ParserFree(parser);
+        return NULL; // failure
+    }
+    logThis(ERROR_INFO, "parse %s", xmlPath);
+    while (!done) {
+        int n = fread(text, sizeof(char), XMLBUFSIZE, file);
+        if (n != XMLBUFSIZE) done = 1;
+        if (!XML_Parse(parser, text, n, done)){
+            logThis(ERROR_ERROR, "Parse error in file %s at line %d:\n%s\n",
+                xmlPath,
+                XML_GetCurrentLineNumber(parser),
+                XML_ErrorString(XML_GetErrorCode(parser)));
+            while (!stackIsEmpty(stack)) md = (ModelDescription *)stackPop(stack);
+            if (md) freeElement(md);
+            cleanup(file);
+            return NULL; // failure
+        }
+    }
+    md = (ModelDescription *)stackPop(stack);
+    assert(stackIsEmpty(stack));
+    cleanup(file);
+    //printElement(1, md); // debug
+    return validate(md); // success if all refs are valid
+}
+
+// Returns NULL to indicate failure
+// Otherwise, return the root node md of the AST.
+// The receiver must call freeElement(md) to release AST memory.
+ModelDescription* parse(const char* xmlPath) {
+    // UTF-8
+    // ISO-8859-1
+    // US-ASCII
+    // UTF-16
+    ModelDescription* md = NULL;
+    md = parse_encoding(xmlPath, "UTF-8");
+    if (md != NULL) {
+        return md;
+    }
+    logThis(ERROR_WARNING, "Failed to parse using UTF-8, will try ISO-8859-1 encoding. %s", xmlPath);
+    md = parse_encoding(xmlPath, "ISO-8859-1");
+    if (md != NULL) {
+        return md;
+    }
+    logThis(ERROR_WARNING, "Failed to parse using ISO-8859-1, will try US-ASCII encoding. %s", xmlPath);
+    md = parse_encoding(xmlPath, "US-ASCII");
+    if (md != NULL) {
+        return md;
+    }
+    logThis(ERROR_ERROR, "Failed to parse xml because of wrong encoding. %s", xmlPath);
+    return NULL;
+}
+
+// #define TEST
+#ifdef TEST
+int main(int argc, char**argv) {
+    ModelDescription* md;
+    // { char c='c'; while(c!='g') scanf("%c", &c); } // to debug: wait for the g key
+
+    if (argc!=2) {
+        printf("usage: xml_parser <filename>");
+        return;
+    }
+    logThis(ERROR_INFO, "Parsing %s ...\n", argv[1]);
+    md = parse(argv[1]);
+    if (md) {
+        printf("Successfully parsed %s\n", argv[1]);
+        printElement(1, md);
+        freeElement(md);
+    }
+    dumpMemoryLeaks();
+}
+#endif  // TEST

+ 180 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/parser/xml_parser.h

@@ -0,0 +1,180 @@
+/*
+ * Copyright QTronic GmbH. All rights reserved.
+ */
+
+/* -------------------------------------------------------------------------
+ * xml_parser.h
+ * A parser for file modelVariables.xml of an FMU.
+ * Supports "FMI for Model Exchange 1.0" and "FMI for Co-Simulation 1.0".
+ * Author: Jakob Mauss, January 2010. 
+ * -------------------------------------------------------------------------*/
+
+#ifndef xml_parser_h
+#define xml_parser_h
+
+// define XML_STATIC before including expat.h
+// to prevent error when linking with libexpatMT.lib
+#define XML_STATIC 
+#include "expat.h"
+#include "stack.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef fmiModelTypes_h
+#ifndef fmiPlatformTypes_h
+typedef unsigned int fmiValueReference;
+#endif
+#endif
+
+#define fmiUndefinedValueReference (fmiValueReference)(-1)
+
+#define SIZEOF_ELM 31
+extern const char *elmNames[SIZEOF_ELM];
+
+#define SIZEOF_ATT 47
+extern const char *attNames[SIZEOF_ATT];
+
+#define SIZEOF_ENU 13
+extern const char *enuNames[SIZEOF_ENU];
+
+// Attributes
+typedef enum {
+    elm_BAD_DEFINED = -1,
+    elm_fmiModelDescription,elm_UnitDefinitions,elm_BaseUnit,elm_DisplayUnitDefinition,elm_TypeDefinitions,
+    elm_Type,elm_RealType,elm_IntegerType,elm_BooleanType,elm_StringType,elm_EnumerationType,elm_Item,
+    elm_DefaultExperiment,elm_VendorAnnotations,elm_Tool,elm_Annotation,elm_ModelVariables,elm_ScalarVariable,
+    elm_DirectDependency,elm_Name,elm_Real,elm_Integer,elm_Boolean,elm_String,elm_Enumeration,
+    elm_Implementation,elm_CoSimulation_StandAlone,elm_CoSimulation_Tool,elm_Model,elm_File,elm_Capabilities
+} Elm;
+
+// Attributes
+typedef enum {
+    att_BAD_DEFINED = -1,
+    att_fmiVersion,att_displayUnit,att_gain,att_offset,att_unit,att_name,att_description,att_quantity,att_relativeQuantity,
+    att_min,att_max,att_nominal,att_declaredType,att_start,att_fixed,att_startTime,att_stopTime,att_tolerance,att_value,
+    att_valueReference,att_variability,att_causality,att_alias,att_modelName,att_modelIdentifier,att_guid,att_author,
+    att_version,att_generationTool,att_generationDateAndTime,att_variableNamingConvention,att_numberOfContinuousStates,
+    att_numberOfEventIndicators,att_input,
+    att_canHandleVariableCommunicationStepSize,att_canHandleEvents,att_canRejectSteps,att_canInterpolateInputs,
+    att_maxOutputDerivativeOrder,att_canRunAsynchronuously,att_canSignalEvents,att_canBeInstantiatedOnlyOncePerProcess,
+    att_canNotUseMemoryManagementFunctions,att_entryPoint,att_manualStart,att_type
+} Att;
+
+// Enumeration values
+typedef enum {
+    enu_BAD_DEFINED = -1,
+    enu_flat,enu_structured,enu_constant,enu_parameter,enu_discrete,enu_continuous,
+    enu_input,enu_output,enu_internal,enu_none,enu_noAlias,enu_alias,enu_negatedAlias
+} Enu;
+
+// AST node for element 
+// DisplayUnitDefinition, RealType, IntegerType, BooleanType, StringType, DefaultExperiment,
+// Item, Annotation, Name, Real, Integer, Boolean, String, Enumeration, Capabilities, File
+typedef struct {
+    Elm type;          // element type
+    const char** attributes; // null or n attribute value strings
+    int n;             // size of attributes, even number
+} Element;
+
+// AST node for element that has a list of elements 
+// BaseUnit, EnumerationType, Tool, DirectDependency, Model
+typedef struct {
+    Elm type;          // element type
+    const char** attributes; // null or n attribute value strings
+    int n;             // size of attributes, even number
+    Element** list;    // null-terminated array of pointers to elements, not null
+} ListElement;
+
+// AST node for element Type
+typedef struct {
+    Elm type;          // element type
+    const char** attributes; // null or n attribute value strings
+    int n;             // size of attributes, an even number
+    Element* typeSpec; // one of RealType, IntegerType etc.
+} Type;
+
+// AST node for element ScalarVariable
+typedef struct {
+    Elm type;          // element type
+    const char** attributes; // null or n attribute value strings
+    int n;             // size of attributes, even number
+    Element* typeSpec; // one of Real, Integer, etc
+    Element** directDependencies; // null or null-terminated list of Name
+    int  modelIdx;     // only used in fmu10
+} ScalarVariable;
+
+// AST node for element CoSimulation_StandAlone and CoSimulation_Tool
+typedef struct {
+    Elm type;                // one of elm_CoSimulation_StandAlone and elm_CoSimulation_Tool
+    const char** attributes; // null or n attribute value strings
+    int n;                   // size of attributes, even number
+    Element* capabilities;   // a set of capability attributes
+    ListElement* model;      // non-NULL to support tool coupling, NULL for standalone
+} CoSimulation;
+
+// AST node for element ModelDescription
+typedef struct {
+    Elm type;                // element type
+    const char** attributes; // null or n attribute value strings
+    int n;                   // size of attributes, even number
+    ListElement** unitDefinitions;    // NULL or null-terminated list of BaseUnits
+    Type**        typeDefinitions;    // NULL or null-terminated list of Types
+    Element*      defaultExperiment;  // NULL or DefaultExperiment
+    ListElement** vendorAnnotations;  // NULL or null-terminated list of Tools
+    ScalarVariable** modelVariables;  // NULL or null-terminated list of ScalarVariable
+    CoSimulation* cosimulation;       // NULL if this ModelDescription is for model exchange only
+} ModelDescription;
+
+// types of AST nodes used to represent an element
+typedef enum { 
+    astElement,
+    astListElement,
+    astType,
+    astScalarVariable,
+    astCoSimulation,
+    astModelDescription
+} AstNodeType;
+
+// Possible results when retrieving an attribute value from an element
+typedef enum { 
+    valueMissing,
+    valueDefined,
+    valueIllegal
+} ValueStatus;
+
+// Public methods: Parsing and low-level AST access
+ModelDescription* parse(const char* xmlPath);
+const char* getString(void* element, Att a);
+double getDouble     (void* element, Att a, ValueStatus* vs);
+int getInt           (void* element, Att a, ValueStatus* vs);
+unsigned int getUInt (void* element, Att a, ValueStatus* vs);
+char getBoolean      (void* element, Att a, ValueStatus* vs);
+Enu getEnumValue     (void* element, Att a, ValueStatus* vs);
+void freeElement     (void* element);
+
+// Convenience methods for AST access. To be used after successful validation only.
+const char* getModelIdentifier(ModelDescription* md);
+int getNumberOfStates(ModelDescription* md);
+int getNumberOfEventIndicators(ModelDescription* md);
+const char* getName(void* element);
+Enu getCausality(void* scalarVariable);
+Enu getVariability(void* scalarVariable);
+Enu getAlias(void* scalarVariable);
+fmiValueReference getValueReference(void* scalarVariable);
+ScalarVariable* getVariableByName(ModelDescription* md, const char* name);
+ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type);
+ScalarVariable* getNonAliasVariable(ModelDescription* md, fmiValueReference vr, Elm type);
+Type* getDeclaredType(ModelDescription* md, const char* declaredType);
+const char* getString2(ModelDescription* md, void* sv, Att a);
+const char * getDescription(ModelDescription* md, ScalarVariable* sv);
+const char * getVariableAttributeString(ModelDescription* md, fmiValueReference vr, Elm type, Att a);
+double getVariableAttributeDouble(ModelDescription* md, fmiValueReference vr, Elm type, Att a, ValueStatus* vs);
+//double getNominal(ModelDescription* md, ScalarVariable* sv);
+double getNominal(ModelDescription* md, fmiValueReference vr);
+
+#ifdef __cplusplus
+} // closing brace for extern "C"
+#endif
+#endif // xml_parser_h

+ 602 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/sim_support.c

@@ -0,0 +1,602 @@
+/* -------------------------------------------------------------------------
+ * sim_support.c
+ * Functions used by both FMU simulators fmu10sim_me and fmu10sim_cs
+ * to parse command-line arguments, to unzip and load an fmu, 
+ * to write CSV file, and more.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <stdarg.h>
+
+#ifdef FMI_COSIMULATION
+#include "fmi_cs.h"
+#else
+#include "fmi_me.h"
+#endif
+
+#include "xmlVersionParser.h"
+#include "sim_support.h"
+
+#if !WINDOWS
+#define MAX_PATH 1024
+#include <unistd.h>  // mkdtemp()
+#include <dlfcn.h> //dlsym()
+#endif /* WINDOWS */
+
+extern FMU fmu;
+
+#if WINDOWS
+int unzip(const char *zipPath, const char *outPath) {
+    int code;
+    char binPath[BUFSIZE];
+    int n = BUFSIZE + strlen(UNZIP_CMD) + strlen(outPath) + 3 +  strlen(zipPath) + 9;
+    char* cmd = (char*)calloc(sizeof(char), n);
+
+    // %FMUSDK_HOME%\bin to find 7z.dll and 7z.exe
+    if (!GetEnvironmentVariable("FMUSDK_HOME", binPath, BUFSIZE)) {
+        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
+            printf ("error: Environment variable FMUSDK_HOME not defined\n");
+        }
+        else {
+            printf ("error: Could not get value of FMUSDK_HOME\n");
+        }
+        return 0; // error
+    }
+    strcat(binPath, "\\fmu10\\bin");
+    // run the unzip command
+    // remove "> NUL" to see the unzip protocol
+    sprintf(cmd, "%s\\%s\"%s\" \"%s\" > NUL", binPath, UNZIP_CMD, outPath, zipPath);
+    // printf("cmd='%s'\n", cmd);
+    code = system(cmd);
+    free(cmd);
+    if (code!=SEVEN_ZIP_NO_ERROR) {
+        printf("7z: ");
+        switch (code) {
+            case SEVEN_ZIP_WARNING:            printf("warning\n"); break;
+            case SEVEN_ZIP_ERROR:              printf("error\n"); break;
+            case SEVEN_ZIP_COMMAND_LINE_ERROR: printf("command line error\n"); break;
+            case SEVEN_ZIP_OUT_OF_MEMORY:      printf("out of memory\n"); break;
+            case SEVEN_ZIP_STOPPED_BY_USER:    printf("stopped by user\n"); break;
+            default: printf("unknown problem\n");
+        }
+    }
+
+    return (code==SEVEN_ZIP_NO_ERROR || code==SEVEN_ZIP_WARNING) ? 1 : 0;
+}
+
+#else /* WINDOWS */
+
+int unzip(const char *zipPath, const char *outPath) {
+    int code;
+    int n;
+    char* cmd;
+
+    // run the unzip command
+    n = strlen(UNZIP_CMD) + strlen(outPath) + 1 +  strlen(zipPath) + 16;
+    cmd = (char*)calloc(sizeof(char), n);
+    sprintf(cmd, "%s%s \"%s\" > /dev/null", UNZIP_CMD, outPath, zipPath);
+    printf("cmd='%s'\n", cmd);
+    code = system(cmd);
+    free(cmd);
+    if (code!=SEVEN_ZIP_NO_ERROR) {
+        printf("%s: ", UNZIP_CMD);
+        switch (code) {
+            case 1:            printf("warning\n"); break;
+            case 2:            printf("error\n"); break;
+            case 3:            printf("severe error\n"); break;
+            case 4:
+            case 5:
+            case 6:
+            case 7:
+                               printf("out of memory\n"); break;
+            case 10:           printf("command line error\n"); break;
+            default:           printf("unknown problem %d\n", code);
+        }
+    }
+    return (code==SEVEN_ZIP_NO_ERROR || code==SEVEN_ZIP_WARNING) ? 1 : 0;
+}
+#endif /* WINDOWS */
+
+#if WINDOWS
+// fileName is an absolute path, e.g. C:\test\a.fmu
+// or relative to the current dir, e.g. ..\test\a.fmu
+// Does not check for existence of the file
+static char* getFmuPath(const char* fileName){
+    char pathName[MAX_PATH];
+    int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL);
+    return n ? strdup(pathName) : NULL;
+}
+
+static char* getTmpPath() {
+    char tmpPath[BUFSIZE];
+    if(! GetTempPath(BUFSIZE, tmpPath)) {
+        printf ("error: Could not find temporary disk space\n");
+        return NULL;
+    }
+    strcat(tmpPath, "fmu\\");
+    return strdup(tmpPath);
+}
+
+#else /* WINDOWS */
+// fmuFileName is an absolute path, e.g. "C:\test\a.fmu"
+// or relative to the current dir, e.g. "..\test\a.fmu"
+static char* getFmuPath(const char* fmuFileName){
+  /* Not sure why this is useful.  Just returning the filename. */
+  return strdup(fmuFileName);
+}
+static char* getTmpPath() {
+  char template[13];  // Lenght of "fmuTmpXXXXXX" + null
+  sprintf(template, "%s", "fmuTmpXXXXXX");
+  //char *tmp = mkdtemp(strdup("fmuTmpXXXXXX"));
+  char *tmp = mkdtemp(template);
+  if (tmp==NULL) {
+    fprintf(stderr, "Couldn't create temporary directory\n");
+    exit(1);
+  }
+  char * results = calloc(sizeof(char), strlen(tmp) + 2);
+  strncat(results, tmp, strlen(tmp));
+  return strcat(results, "/");
+}
+#endif /* WINDOWS */
+
+char *getTempFmuLocation() {
+    char *tempPath = getTmpPath();
+    char *fmuLocation = (char *)calloc(sizeof(char), 8 + strlen(tempPath));
+    strcpy(fmuLocation, "file://");
+    strcat(fmuLocation, tempPath);
+    free(tempPath);
+    return fmuLocation;
+}
+
+static void* getAdr(int* s, FMU *fmu, const char* functionName){
+    char name[BUFSIZE];
+    void* fp;
+    sprintf(name, "%s_%s", getModelIdentifier(fmu->modelDescription), functionName);
+#if WINDOWS
+    fp = GetProcAddress(fmu->dllHandle, name);
+#else /* WINDOWS */
+    fp = dlsym(fmu->dllHandle, name);
+#endif /* WINDOWS */
+    if (!fp) {
+        printf ("warning: Function %s not found in dll\n", name);
+#if WINDOWS
+#else /* WINDOWS */
+        printf ("Error was: %s\n", dlerror());
+#endif /* WINDOWS */
+        *s = 0; // mark dll load as 'failed'
+    }
+    return fp;
+}
+
+// Load the given dll and set function pointers in fmu
+// Return 0 to indicate failure
+static int loadDll(const char* dllPath, FMU *fmu) {
+    int s = 1;
+#if WINDOWS
+    HANDLE h = LoadLibrary(dllPath);
+#else /* WINDOWS */
+    HANDLE h = dlopen(dllPath, RTLD_LAZY);
+#endif /* WINDOWS */
+    if (!h) {
+#if WINDOWS
+#else
+        printf("The error was: %s\n", dlerror());
+#endif
+        printf("error: Could not load %s\n", dllPath);
+        return 0; // failure
+    }
+    fmu->dllHandle = h;
+
+#ifdef FMI_COSIMULATION   
+    fmu->getTypesPlatform        = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetTypesPlatform");
+    if (s==0) { 
+        s = 1; // work around bug for FMUs exported using Dymola 2012 and SimulationX 3.x
+        fmu->getTypesPlatform    = (fGetTypesPlatform)   getAdr(&s, fmu, "fmiGetModelTypesPlatform");
+        if (s==1) printf("  using fmiGetModelTypesPlatform instead\n");
+    }
+    fmu->instantiateSlave        = (fInstantiateSlave)   getAdr(&s, fmu, "fmiInstantiateSlave");
+    fmu->initializeSlave         = (fInitializeSlave)    getAdr(&s, fmu, "fmiInitializeSlave");
+    fmu->terminateSlave          = (fTerminateSlave)     getAdr(&s, fmu, "fmiTerminateSlave");
+    fmu->resetSlave              = (fResetSlave)         getAdr(&s, fmu, "fmiResetSlave");
+    fmu->freeSlaveInstance       = (fFreeSlaveInstance)  getAdr(&s, fmu, "fmiFreeSlaveInstance");
+    fmu->setRealInputDerivatives = (fSetRealInputDerivatives) getAdr(&s, fmu, "fmiSetRealInputDerivatives");
+    fmu->getRealOutputDerivatives = (fGetRealOutputDerivatives) getAdr(&s, fmu, "fmiGetRealOutputDerivatives");
+    fmu->cancelStep              = (fCancelStep)         getAdr(&s, fmu, "fmiCancelStep");
+    fmu->doStep                  = (fDoStep)             getAdr(&s, fmu, "fmiDoStep");
+    // SimulationX 3.4 and 3.5 do not yet export getStatus and getXStatus: do not count this as failure here
+    fmu->getStatus               = (fGetStatus)          getAdr(&s, fmu, "fmiGetStatus");
+    fmu->getRealStatus           = (fGetRealStatus)      getAdr(&s, fmu, "fmiGetRealStatus");
+    fmu->getIntegerStatus        = (fGetIntegerStatus)   getAdr(&s, fmu, "fmiGetIntegerStatus");
+    fmu->getBooleanStatus        = (fGetBooleanStatus)   getAdr(&s, fmu, "fmiGetBooleanStatus");
+    fmu->getStringStatus         = (fGetStringStatus)    getAdr(&s, fmu, "fmiGetStringStatus");
+
+#else // FMI for Model Exchange 1.0
+    fmu->getModelTypesPlatform   = (fGetModelTypesPlatform) getAdr(&s, fmu, "fmiGetModelTypesPlatform");
+    fmu->instantiateModel        = (fInstantiateModel)   getAdr(&s, fmu, "fmiInstantiateModel");
+    fmu->freeModelInstance       = (fFreeModelInstance)  getAdr(&s, fmu, "fmiFreeModelInstance");
+    fmu->setTime                 = (fSetTime)            getAdr(&s, fmu, "fmiSetTime");
+    fmu->setContinuousStates     = (fSetContinuousStates)getAdr(&s, fmu, "fmiSetContinuousStates");
+    fmu->completedIntegratorStep = (fCompletedIntegratorStep)getAdr(&s, fmu, "fmiCompletedIntegratorStep");
+    fmu->initialize              = (fInitialize)         getAdr(&s, fmu, "fmiInitialize");
+    fmu->getDerivatives          = (fGetDerivatives)     getAdr(&s, fmu, "fmiGetDerivatives");
+    fmu->getEventIndicators      = (fGetEventIndicators) getAdr(&s, fmu, "fmiGetEventIndicators");
+    fmu->eventUpdate             = (fEventUpdate)        getAdr(&s, fmu, "fmiEventUpdate");
+    fmu->getContinuousStates     = (fGetContinuousStates)getAdr(&s, fmu, "fmiGetContinuousStates");
+    fmu->getNominalContinuousStates = (fGetNominalContinuousStates)getAdr(&s, fmu, "fmiGetNominalContinuousStates");
+    fmu->getStateValueReferences = (fGetStateValueReferences)getAdr(&s, fmu, "fmiGetStateValueReferences");
+    fmu->terminate               = (fTerminate)          getAdr(&s, fmu, "fmiTerminate");
+#endif 
+    fmu->getVersion              = (fGetVersion)         getAdr(&s, fmu, "fmiGetVersion");
+    fmu->setDebugLogging         = (fSetDebugLogging)    getAdr(&s, fmu, "fmiSetDebugLogging");
+    fmu->setReal                 = (fSetReal)            getAdr(&s, fmu, "fmiSetReal");
+    fmu->setInteger              = (fSetInteger)         getAdr(&s, fmu, "fmiSetInteger");
+    fmu->setBoolean              = (fSetBoolean)         getAdr(&s, fmu, "fmiSetBoolean");
+    fmu->setString               = (fSetString)          getAdr(&s, fmu, "fmiSetString");
+    fmu->getReal                 = (fGetReal)            getAdr(&s, fmu, "fmiGetReal");
+    fmu->getInteger              = (fGetInteger)         getAdr(&s, fmu, "fmiGetInteger");
+    fmu->getBoolean              = (fGetBoolean)         getAdr(&s, fmu, "fmiGetBoolean");
+    fmu->getString               = (fGetString)          getAdr(&s, fmu, "fmiGetString");
+    return s; 
+}
+
+static void printModelDescription(ModelDescription* md){
+    Element* e = (Element*)md;  
+    int i;
+    printf("%s\n", elmNames[e->type]);
+    for (i=0; i<e->n; i+=2) 
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);
+#ifdef FMI_COSIMULATION   
+    if (!md->cosimulation) {
+        printf("error: No Implementation element found in model description. This FMU is not for Co-Simulation.\n");
+        exit(EXIT_FAILURE);
+    }
+    e = md->cosimulation->capabilities;
+    printf("%s\n", elmNames[e->type]);
+    for (i=0; i<e->n; i+=2) 
+        printf("  %s=%s\n", e->attributes[i], e->attributes[i+1]);
+#endif // FMI_COSIMULATION  
+}
+
+void loadFMU(const char* fmuFileName) {
+    char* fmuPath;
+    char* tmpPath;
+    char* xmlPath;
+    char* dllPath;
+    
+    // get absolute path to FMU, NULL if not found
+    fmuPath = getFmuPath(fmuFileName);
+    if (!fmuPath) exit(EXIT_FAILURE);
+
+    // unzip the FMU to the tmpPath directory
+    tmpPath = getTmpPath();
+    if (!unzip(fmuPath, tmpPath)) exit(EXIT_FAILURE);
+
+    // parse tmpPath\modelDescription.xml
+    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);
+    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);
+
+    // parse tmpPath\modelDescription.xml
+    xmlPath = calloc(sizeof(char), strlen(tmpPath) + strlen(XML_FILE) + 1);
+    sprintf(xmlPath, "%s%s", tmpPath, XML_FILE);
+    // check FMI version of the FMU to match current simulator version
+    if (!checkFmiVersion(xmlPath)) {
+        free(xmlPath);
+        free(fmuPath);
+        free(tmpPath);
+        exit(EXIT_FAILURE);
+    }
+
+    fmu.modelDescription = parse(xmlPath);
+    free(xmlPath);
+    if (!fmu.modelDescription) exit(EXIT_FAILURE);
+    printModelDescription(fmu.modelDescription);
+
+    // load the FMU dll
+    dllPath = calloc(sizeof(char), strlen(tmpPath) + strlen(DLL_DIR)
+            + strlen( getModelIdentifier(fmu.modelDescription)) +  strlen(DLL_SUFFIX) + 1);
+    sprintf(dllPath,"%s%s%s%s", tmpPath, DLL_DIR, getModelIdentifier(fmu.modelDescription), DLL_SUFFIX);
+    if (!loadDll(dllPath, &fmu)) {
+        free(dllPath);
+        free(fmuPath);
+        free(tmpPath);
+        exit(EXIT_FAILURE);
+    }
+    free(dllPath);
+    free(fmuPath);
+    free(tmpPath);
+}
+
+int checkFmiVersion(const char *xmlPath) {
+    char *xmlFmiVersion = extractVersion(xmlPath);
+    if (xmlFmiVersion == NULL) {
+        printf("The FMI version of the FMU could not be read: %s", xmlPath);
+        return 0;
+    } else if (strcmp(xmlFmiVersion, fmiVersion) == 0) {
+        free(xmlFmiVersion);
+        return 1;
+    }
+    printf("The FMU to simulate is FMI %s standard, but expected a FMI %s standard FMU", fmiVersion, xmlFmiVersion);
+    free(xmlFmiVersion);
+    return 0;
+}
+
+void deleteUnzippedFiles() {
+    char *fmuTempPath = getTmpPath();
+    char *cmd = (char *)calloc(15 + strlen(fmuTempPath), sizeof(char));
+#if WINDOWS
+    sprintf(cmd, "rmdir /S /Q %s", fmuTempPath);
+#else /* WINDOWS */
+    sprintf(cmd, "rm -rf %s", fmuTempPath);
+#endif /* WINDOWS */
+    system(cmd);
+    free(cmd);
+    free(fmuTempPath);
+}
+
+static void doubleToCommaString(char* buffer, double r){
+    char* comma;
+    sprintf(buffer, "%.16g", r);
+    comma = strchr(buffer, '.');
+    if (comma) *comma = ',';
+}
+
+// output time and all non-alias variables in CSV format
+// if separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.
+// otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used
+// as decimal dot in floating-point numbers.
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, fmiBoolean header) {
+    int k;
+    fmiReal r;
+    fmiInteger i;
+    fmiBoolean b;
+    fmiString s;
+    fmiValueReference vr;
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;
+    char buffer[32];
+
+    // print first column
+    if (header) 
+        fprintf(file, "time");
+    else {
+        if (separator==',')
+            fprintf(file, "%.16g", time);
+        else {
+            // separator is e.g. ';' or '\t'
+            doubleToCommaString(buffer, time);
+            fprintf(file, "%s", buffer);
+        }
+    }
+
+    // print all other columns(void *)
+    for (k=0; vars[k]; k++) {
+        ScalarVariable* sv = vars[k];
+        if (getAlias(sv)!=enu_noAlias) continue;
+        if (header) {
+            // output names only
+            if (separator==',') {
+                // treat array element, e.g. print a[1, 2] as a[1.2]
+                const char* s = getName(sv);
+                fprintf(file, "%c", separator);
+                while (*s) {
+                   if (*s!=' ') fprintf(file, "%c", *s==',' ? '.' : *s);
+                   s++;
+                }
+             }
+            else
+                fprintf(file, "%c%s", separator, getName(sv));
+        }
+        else {
+            // output values
+            vr = getValueReference(sv);
+            switch (sv->typeSpec->type){
+                case elm_Real:
+                    fmu->getReal(c, &vr, 1, &r);
+                    if (separator==',') 
+                        fprintf(file, ",%.16g", r);
+                    else {
+                        // separator is e.g. ';' or '\t'
+                        doubleToCommaString(buffer, r);
+                        fprintf(file, "%c%s", separator, buffer);
+                    }
+                    break;
+                case elm_Integer:
+                case elm_Enumeration:
+                    fmu->getInteger(c, &vr, 1, &i);
+                    fprintf(file, "%c%d", separator, i);
+                    break;
+                case elm_Boolean:
+                    fmu->getBoolean(c, &vr, 1, &b);
+                    fprintf(file, "%c%d", separator, b);
+                    break;
+                case elm_String:
+                    fmu->getString(c, &vr, 1, &s);
+                    fprintf(file, "%c%s", separator, s);
+                    break;
+                default: 
+                    fprintf(file, "%cNoValueForType=%d", separator,sv->typeSpec->type);
+            }
+        }
+    } // for
+
+    // terminate this row
+    fprintf(file, "\n");
+}
+
+static const char* fmiStatusToString(fmiStatus status){
+    switch (status){
+        case fmiOK:      return "ok";
+        case fmiWarning: return "warning";
+        case fmiDiscard: return "discard";
+        case fmiError:   return "error";
+        case fmiFatal:   return "fatal";
+#ifdef FMI_COSIMULATION
+        case fmiPending: return "fmiPending";
+#endif
+        default:         return "?";
+    }
+}
+
+// search a fmu for the given variable
+// return NULL if not found or vr = fmiUndefinedValueReference
+static ScalarVariable* getSV(FMU* fmu, char type, fmiValueReference vr) {
+    int i;
+    Elm tp;
+    ScalarVariable** vars = fmu->modelDescription->modelVariables;
+    if (vr==fmiUndefinedValueReference) return NULL;
+    switch (type) {
+        case 'r': tp = elm_Real;    break;
+        case 'i': tp = elm_Integer; break;
+        case 'b': tp = elm_Boolean; break;
+        case 's': tp = elm_String;  break;
+        default:  tp = elm_BAD_DEFINED; break;
+    }
+    for (i=0; vars[i]; i++) {
+        ScalarVariable* sv = vars[i];
+        if (vr==getValueReference(sv) && tp==sv->typeSpec->type)
+            return sv;
+    }
+    return NULL;
+}
+
+// replace e.g. #r1365# by variable name and ## by # in message
+// copies the result to buffer
+static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){
+    int i=0; // position in msg
+    int k=0; // position in buffer
+    int n;
+    char c = msg[i];
+    while (c!='\0' && k < nBuffer) {
+        if (c!='#') {
+            buffer[k++]=c;
+            i++;
+            c = msg[i];
+        } else if (strlen(msg + i + 1) >= 3
+               && (strncmp(msg + i + 1, "IND", 3) == 0 || strncmp(msg + i + 1, "INF", 3) == 0)) {
+            // 1.#IND, 1.#INF
+            buffer[k++]=c;
+            i++;
+            c = msg[i];
+        } else {
+            char* end = strchr(msg+i+1, '#');
+            if (!end) {
+                printf("unmatched '#' in '%s'\n", msg);
+                buffer[k++]='#';
+                break;
+            }
+            n = end - (msg+i);
+            if (n==1) {
+                // ## detected, output #
+                buffer[k++]='#';
+                i += 2;
+                c = msg[i];
+            }
+            else {
+                char type = msg[i+1]; // one of ribs
+                fmiValueReference vr;
+                int nvr = sscanf(msg+i+2, "%u", &vr);
+                if (nvr==1) {
+                    // vr of type detected, e.g. #r12#
+                    ScalarVariable* sv = getSV(fmu, type, vr);
+                    const char* name = sv ? getName(sv) : "?";
+                    sprintf(buffer+k, "%s", name);
+                    k += strlen(name);
+                    i += (n+1);
+                    c = msg[i]; 
+                }
+                else {
+                    // could not parse the number
+                    printf("illegal value reference at position %d in '%s'\n", i+2, msg);
+                    buffer[k++]='#';
+                    break;
+                }
+            }
+        }
+    } // while
+    buffer[k] = '\0';
+}
+
+#define MAX_MSG_SIZE 1000
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status,
+               fmiString category, fmiString message, ...) {
+    char msg[MAX_MSG_SIZE];
+    char* copy;
+    va_list argp;
+
+    // replace C format strings
+    va_start(argp, message);
+    vsprintf(msg, message, argp);
+    va_end(argp);
+
+    // replace e.g. ## and #r12#  
+    copy = strdup(msg);
+    replaceRefsInMessage(copy, msg, MAX_MSG_SIZE, &fmu);
+    free(copy);
+    
+    // print the final message
+    if (!instanceName) instanceName = "?";
+    if (!category) category = "?";
+    printf("%s %s (%s): %s\n", fmiStatusToString(status), instanceName, category, msg);
+}
+
+int error(const char* message){
+    printf("%s\n", message);
+    return 0;
+}
+
+void parseArguments(int argc, char *argv[], const char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator) {
+    // parse command line arguments
+    if (argc>1) {
+        *fmuFileName = argv[1];
+    }
+    else {
+        printf("error: no fmu file\n");
+        printHelp(argv[0]);
+        exit(EXIT_FAILURE);
+    }
+    if (argc>2) {
+        if (sscanf(argv[2],"%lf", tEnd) != 1) {
+            printf("error: The given end time (%s) is not a number\n", argv[2]);
+            exit(EXIT_FAILURE);
+        }
+    }
+    if (argc>3) {
+        if (sscanf(argv[3],"%lf", h) != 1) {
+            printf("error: The given stepsize (%s) is not a number\n", argv[3]);
+            exit(EXIT_FAILURE);
+        }
+    }
+    if (argc>4) {
+        if (sscanf(argv[4],"%d", loggingOn) != 1 || *loggingOn<0 || *loggingOn>1) {
+            printf("error: The given logging flag (%s) is not boolean\n", argv[4]);
+            exit(EXIT_FAILURE);
+        }
+    }
+    if (argc>5) {
+        if (strlen(argv[5]) != 1) {
+            printf("error: The given CSV separator char (%s) is not valid\n", argv[5]);
+            exit(EXIT_FAILURE);
+        }
+        switch (argv[5][0]) {
+            case 'c': *csv_separator = ','; break; // comma
+            case 's': *csv_separator = ';'; break; // semicolon
+            default:  *csv_separator = argv[5][0]; break; // any other char
+        }
+    }
+    if (argc>6) {
+        printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]);
+        printHelp(argv[0]);
+    }
+}
+
+void printHelp(const char* fmusim) {
+    printf("command syntax: %s <model.fmu> <tEnd> <h> <loggingOn> <csv separator>\n", fmusim);
+    printf("   <model.fmu> .... path to FMU, relative to current dir or absolute, required\n");
+    printf("   <tEnd> ......... end  time of simulation, optional, defaults to 1.0 sec\n");
+    printf("   <h> ............ step size of simulation, optional, defaults to 0.1 sec\n");
+    printf("   <loggingOn> .... 1 to activate logging,   optional, defaults to 0\n");
+    printf("   <csv separator>. separator in csv file,   optional, c for ',', s for';', defaults to c\n");
+}

+ 69 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/sim_support.h

@@ -0,0 +1,69 @@
+/* -------------------------------------------------------------------------
+ * sim_support.h
+ * Functions used by the FMU simulation fmusim_me and fmusim_cs.
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#if WINDOWS
+// Used 7z options, version 4.57:
+// -x   Extracts files from an archive with their full paths in the current dir, or in an output dir if specified
+// -aoa Overwrite All existing files without prompt
+// -o   Specifies a destination directory where files are to be extracted
+#define UNZIP_CMD "7z x -aoa -o"
+#else /* WINDOWS */
+// -o   Overwrite existing files without prompting
+// -d   The directory in which to write files.
+#define UNZIP_CMD "unzip -o -d "
+#endif /* WINDOWS */
+
+#define XML_FILE  "modelDescription.xml"
+#define RESULT_FILE "result.csv"
+#define BUFSIZE 4096
+
+#if WINDOWS
+#ifdef _WIN64
+#define DLL_DIR   "binaries\\win64\\"
+#else /* _WIN64 */
+#define DLL_DIR   "binaries\\win32\\"
+#endif /* _WIN64 */
+
+#define DLL_SUFFIX ".dll"
+
+#else /* WINDOWS */
+#if __APPLE__
+
+// Use these for platforms other than OpenModelica
+#define DLL_DIR   "binaries/darwin64/"
+#define DLL_SUFFIX ".dylib"
+
+#else /* __APPLE__ */
+// Linux
+#ifdef __x86_64
+#define DLL_DIR   "binaries/linux64/"
+#else
+// It may be necessary to compile with -m32, see ../Makefile
+#define DLL_DIR   "binaries/linux32/"
+#endif /*__x86_64*/
+#define DLL_SUFFIX ".so"
+
+#endif /* __APPLE__ */
+#endif /* WINDOWS */
+
+// return codes of the 7z command line tool
+#define SEVEN_ZIP_NO_ERROR 0 // success
+#define SEVEN_ZIP_WARNING 1  // e.g., one or more files were locked during zip
+#define SEVEN_ZIP_ERROR 2
+#define SEVEN_ZIP_COMMAND_LINE_ERROR 7
+#define SEVEN_ZIP_OUT_OF_MEMORY 8
+#define SEVEN_ZIP_STOPPED_BY_USER 255
+
+void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...);
+int unzip(const char *zipPath, const char *outPath);
+void parseArguments(int argc, char *argv[], const char** fmuFileName, double* tEnd, double* h, int* loggingOn, char* csv_separator);
+void loadFMU(const char* fmuFileName);
+int checkFmiVersion(const char *xmlPath);
+void deleteUnzippedFiles();
+void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, fmiBoolean header);
+int error(const char* message);
+void printHelp(const char* fmusim);
+char *getTempFmuLocation(); // caller has to free the result

+ 86 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/xmlVersionParser.c

@@ -0,0 +1,86 @@
+/*
+ * Copyright QTronic GmbH. All rights reserved.
+ */
+
+/* ---------------------------------------------------------------------------*
+ * xmlVersionParser.c
+ *
+ * Author: Adrian Tirea
+ * ---------------------------------------------------------------------------*/
+
+#ifdef STANDALONE_XML_PARSER
+#include <string.h>
+#define logThis(n, ...) printf(__VA_ARGS__); printf("\n")
+#define checkStrdup(str) strdup(str)
+#define BOOL int
+#define TRUE 1
+#define FALSE 0
+#else
+#include "GlobalIncludes.h"
+#include "logging.h"  // logThis
+#include "minutil.h"  // checkStrdup
+#endif  // STANDALONE_XML_PARSER
+
+#include <libxml/xmlreader.h>
+#include "xmlVersionParser.h"
+
+// Element and attribute that identify the fmiVersion.
+#define ELM_fmiModelDescription_NAME "fmiModelDescription"
+#define ATT_fmiVersion_NAME "fmiVersion"
+
+static BOOL readNextInXml(xmlTextReaderPtr xmlReader) {
+    int ret;
+    do {
+        ret = xmlTextReaderRead(xmlReader);
+    } while (ret == 1 && xmlTextReaderNodeType(xmlReader) == XML_READER_TYPE_COMMENT);
+
+    if (ret != 1) {
+        return FALSE;
+    }
+    return TRUE;
+}
+
+// The receiver must free the return.
+static char *extractFmiVersionAttribute(xmlTextReaderPtr xmlReader) {
+    char *value = (char *)xmlTextReaderGetAttribute(xmlReader, ATT_fmiVersion_NAME);
+    char *result = value ? (char *)checkStrdup(value) : NULL;
+    xmlFree(value);
+    return result;
+}
+
+// The receiver must free the return.
+static char *streamFile(const char *xmlPath) {
+    xmlTextReaderPtr xmlReader;
+    char *fmiVersion = NULL;
+    xmlReader = xmlReaderForFile(xmlPath, NULL, 0);
+    if (xmlReader != NULL) {
+        if (readNextInXml(xmlReader)) {
+            // I expect that first element is fmiModelDescription.
+            if (0 != strcmp((char *)xmlTextReaderConstLocalName(xmlReader), ELM_fmiModelDescription_NAME)) {
+                logThis(ERROR_ERROR, "Expected '%s' element. Found instead: '%s'",
+                    ELM_fmiModelDescription_NAME, xmlTextReaderConstLocalName(xmlReader));
+            } else {
+                fmiVersion = extractFmiVersionAttribute(xmlReader);
+            }
+        } else {
+            logThis(ERROR_ERROR, "Syntax error parsing xml file '%s'", xmlPath);
+        }
+        xmlFreeTextReader(xmlReader);
+    } else {
+        logThis(ERROR_ERROR, "Cannot open file '%s'", xmlPath);
+    }
+    return fmiVersion;
+}
+
+// Returns NULL to indicate failure
+// Otherwise, return the version of this FMU.
+// The receiver must free the returned string.
+char *extractVersion(const char *xmlDescriptionPath) {
+    char *fmiVersion;
+
+    fmiVersion = streamFile(xmlDescriptionPath);
+    // do NOT call here xmlCleanupParser() because we don't know all other modules linked into this DLL that
+    // might be using libxml2. For memory leak detections call xmlCleanupParser() just before exit()
+    //xmlCleanupParser();
+    return fmiVersion;
+}

+ 29 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/shared/xmlVersionParser.h

@@ -0,0 +1,29 @@
+/*
+ * Copyright QTronic GmbH. All rights reserved.
+ */
+
+/* ---------------------------------------------------------------------------*
+ * xmlVersionParser.h
+ * Parse a xml model description of a FMI 1.0 or FMI 2.0 model to extract its
+ * fmi version.
+ *
+ * Author: Adrian Tirea
+ * ---------------------------------------------------------------------------*/
+
+#ifndef xmlVersionParser_h
+#define xmlVersionParser_h
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef _MSC_VER
+#pragma comment(lib, "libxml2.lib")
+#pragma comment(lib, "wsock32.lib")
+#endif /* _MSC_VER */
+
+char *extractVersion(const char *xmlDescriptionPath);
+
+#ifdef __cplusplus
+} // closing brace for extern "C"
+#endif
+#endif // xmlVersionParser_h

+ 69 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/build_fmusim_me.bat

@@ -0,0 +1,69 @@
+@echo off 
+rem ------------------------------------------------------------
+rem This batch builds the FMU simulator fmusim_me.exe
+rem Usage: build_fmusim_me.bat (-win64)
+rem Copyright QTronic GmbH. All rights reserved
+rem ------------------------------------------------------------
+
+setlocal
+
+echo -----------------------------------------------------------
+echo building fmusim_me.exe - FMI for Model Exchange 2.0
+echo -----------------------------------------------------------
+
+rem save env variable settings
+set PREV_PATH=%PATH%
+if defined INCLUDE set PREV_INCLUDE=%INLUDE%
+if defined LIB     set PREV_LIB=%LIB%
+if defined LIBPATH set PREV_LIBPATH=%LIBPATH%
+
+if "%1"=="-win64" (set FMI_PLATFORM=win64) else (set FMI_PLATFORM=win32)
+if not exist ..\bin\%FMI_PLATFORM% mkdir ..\bin\%FMI_PLATFORM%
+
+rem setup the compiler
+if %FMI_PLATFORM%==win64 (
+if defined VS140COMNTOOLS (call "%VS140COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+if defined VS120COMNTOOLS (call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+if defined VS110COMNTOOLS (call "%VS110COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+if defined VS100COMNTOOLS (call "%VS100COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64) else ^
+goto noCompiler
+) else (
+if defined VS140COMNTOOLS (call "%VS140COMNTOOLS%\vsvars32.bat") else ^
+if defined VS120COMNTOOLS (call "%VS120COMNTOOLS%\vsvars32.bat") else ^
+if defined VS110COMNTOOLS (call "%VS110COMNTOOLS%\vsvars32.bat") else ^
+if defined VS100COMNTOOLS (call "%VS100COMNTOOLS%\vsvars32.bat") else ^
+if defined VS90COMNTOOLS (call "%VS90COMNTOOLS%\vsvars32.bat") else ^
+if defined VS80COMNTOOLS (call "%VS80COMNTOOLS%\vsvars32.bat") else ^
+goto noCompiler
+)
+
+set SRC=main.c ..\shared\sim_support.c ..\shared\xmlVersionParser.c ..\shared\parser\XmlParser.cpp ..\shared\parser\XmlElement.cpp ..\shared\parser\XmlParserCApi.cpp
+set INC=/I..\shared\include /I..\shared /I..\shared\parser
+set OPTIONS= /nologo /EHsc /DSTANDALONE_XML_PARSER /DLIBXML_STATIC
+
+rem create fmusim_me.exe in the model_exchange dir
+pushd model_exchange
+cl %SRC% %INC% %OPTIONS% /Fefmusim_me.exe /link /LIBPATH:..\shared\parser\%FMI_PLATFORM%
+del *.obj
+popd
+if not exist model_exchange\fmusim_me.exe goto compileError
+move /Y model_exchange\fmusim_me.exe ..\bin\%FMI_PLATFORM%
+goto done
+
+:noCompiler
+echo No Microsoft Visual C compiler found
+
+:compileError
+echo build of fmusim_me.exe failed
+
+:done
+rem undo variable settings performed by vsvars32.bat
+set PATH=%PREV_PATH%
+if defined PREV_INCLUDE set INCLUDE=%PREV_INLUDE%
+if defined PREV_LIB     set LIB=%PREV_LIB%
+if defined PREV_LIBPATH set LIBPATH=%PREV_LIBPATH%
+echo done.
+
+endlocal

+ 288 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/model_exchange/main.c

@@ -0,0 +1,288 @@
+/* ------------------------------------------------------------------------- 
+ * main.c
+ * Implements simulation of a single FMU instance using the forward Euler
+ * method for numerical integration.
+ * Command syntax: see printHelp()
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and 
+ * writes the computed solution to file 'result.csv'.
+ * The CSV file (comma-separated values) may e.g. be plotted using 
+ * OpenOffice Calc or Microsoft Excel. 
+ * This program demonstrates basic use of an FMU.
+ * Real applications may use advanced numerical solvers instead, means to 
+ * exactly locate state events in time, graphical plotting utilities, support 
+ * for co-execution of many FMUs, stepping and debug support, user control
+ * of parameter and start values etc. 
+ * All this is missing here.
+ *
+ * Revision history
+ *  07.03.2014 initial version released in FMU SDK 2.0.0
+ *
+ * Free libraries and tools used to implement this simulator:
+ *  - header files from the FMU specification
+ *  - libxml2 XML parser, see http://xmlsoft.org
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org
+ * Author: Adrian Tirea
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include "fmi2.h"
+#include "sim_support.h"
+
+FMU fmu; // the fmu to simulate
+
+// simulate the given FMU using the forward euler method.
+// time events are processed by reducing step size to exactly hit tNext.
+// state events are checked and fired only at the end of an Euler step. 
+// the simulator may therefore miss state events and fires state events typically too late.
+static int simulate(FMU* fmu, double tEnd, double h, fmi2Boolean loggingOn, char separator,
+                    int nCategories, char **categories) {
+    int i;
+    double dt, tPre;
+    fmi2Boolean timeEvent, stateEvent, stepEvent, terminateSimulation;
+    double time;
+    int nx;                          // number of state variables
+    int nz;                          // number of state event indicators
+    double *x = NULL;                // continuous states
+    double *xdot = NULL;             // the corresponding derivatives in same order
+    double *z = NULL;                // state event indicators
+    double *prez = NULL;             // previous values of state event indicators
+    fmi2EventInfo eventInfo;         // updated by calls to initialize and eventUpdate
+    ModelDescription* md;            // handle to the parsed XML file
+    const char* guid;                // global unique id of the fmu
+    fmi2CallbackFunctions callbacks = {fmuLogger, calloc, free, NULL, fmu}; // called by the model during simulation
+    fmi2Component c;                 // instance of the fmu
+    fmi2Status fmi2Flag;             // return code of the fmu functions
+    fmi2Real tStart = 0;             // start time
+    fmi2Boolean toleranceDefined = fmi2False; // true if model description define tolerance
+    fmi2Real tolerance = 0;          // used in setting up the experiment
+    fmi2Boolean visible = fmi2False; // no simulator user interface
+    const char *instanceName;        // instance name
+    char *fmuResourceLocation = getTempResourcesLocation(); // path to the fmu resources as URL, "file://C:\QTronic\sales"
+    int nSteps = 0;
+    int nTimeEvents = 0;
+    int nStepEvents = 0;
+    int nStateEvents = 0;
+    FILE* file;
+    ValueStatus vs;
+
+    // instantiate the fmu
+    md = fmu->modelDescription;
+    guid = getAttributeValue((Element *)md, att_guid);
+    instanceName = getAttributeValue((Element *)getModelExchange(md), att_modelIdentifier);
+    c = fmu->instantiate(instanceName, fmi2ModelExchange, guid, fmuResourceLocation,
+                        &callbacks, visible, loggingOn);
+    free(fmuResourceLocation);
+    if (!c) return error("could not instantiate model");
+
+    if (nCategories > 0) {
+        fmi2Flag = fmu->setDebugLogging(c, fmi2True, nCategories, categories);
+        if (fmi2Flag > fmi2Warning) {
+            return error("could not initialize model; failed FMI set debug logging");
+        }
+    }
+
+    // allocate memory
+    nx = getDerivativesSize(getModelStructure(md)); // number of continuous states is number of derivatives
+                                                    // declared in model structure
+    nz = getAttributeInt((Element *)md, att_numberOfEventIndicators, &vs); // number of event indicators
+    x    = (double *) calloc(nx, sizeof(double));
+    xdot = (double *) calloc(nx, sizeof(double));
+    if (nz>0) {
+        z    =  (double *) calloc(nz, sizeof(double));
+        prez =  (double *) calloc(nz, sizeof(double));
+    }
+    if ((!x || !xdot) || (nz>0 && (!z || !prez))) return error("out of memory");
+
+    // open result file
+    if (!(file = fopen(RESULT_FILE, "w"))) {
+        printf("could not write %s because:\n", RESULT_FILE);
+        printf("    %s\n", strerror(errno));
+        free (x);
+        free(xdot);
+        free(z);
+        free(prez);
+        return 0; // failure
+    }
+
+    // setup the experiment, set the start time
+    time = tStart;
+    fmi2Flag = fmu->setupExperiment(c, toleranceDefined, tolerance, tStart, fmi2True, tEnd);
+    if (fmi2Flag > fmi2Warning) {
+        return error("could not initialize model; failed FMI setup experiment");
+    }
+
+    // initialize
+    fmi2Flag = fmu->enterInitializationMode(c);
+    if (fmi2Flag > fmi2Warning) {
+        return error("could not initialize model; failed FMI enter initialization mode");
+    }
+    fmi2Flag = fmu->exitInitializationMode(c);
+    if (fmi2Flag > fmi2Warning) {
+        return error("could not initialize model; failed FMI exit initialization mode");
+    }
+
+    // event iteration
+    eventInfo.newDiscreteStatesNeeded = fmi2True;
+    eventInfo.terminateSimulation = fmi2False;
+    while (eventInfo.newDiscreteStatesNeeded && !eventInfo.terminateSimulation) {
+        // update discrete states
+        fmi2Flag = fmu->newDiscreteStates(c, &eventInfo);
+        if (fmi2Flag > fmi2Warning) return error("could not set a new discrete state");
+    }
+
+    if (eventInfo.terminateSimulation) {
+        printf("model requested termination at t=%.16g\n", time);
+    } else {
+        // enter Continuous-Time Mode
+        fmu->enterContinuousTimeMode(c);
+        // output solution for time tStart
+        outputRow(fmu, c, tStart, file, separator, fmi2True);  // output column names
+        outputRow(fmu, c, tStart, file, separator, fmi2False); // output values
+
+        // enter the simulation loop
+        while (time < tEnd) {
+            // get current state and derivatives
+            fmi2Flag = fmu->getContinuousStates(c, x, nx);
+            if (fmi2Flag > fmi2Warning) return error("could not retrieve states");
+            fmi2Flag = fmu->getDerivatives(c, xdot, nx);
+            if (fmi2Flag > fmi2Warning) return error("could not retrieve derivatives");
+
+            // advance time
+            tPre = time;
+            time = min(time+h, tEnd);
+            timeEvent = eventInfo.nextEventTimeDefined && eventInfo.nextEventTime < time;
+            if (timeEvent) time = eventInfo.nextEventTime;
+            dt = time - tPre;
+            fmi2Flag = fmu->setTime(c, time);
+            if (fmi2Flag > fmi2Warning) error("could not set time");
+
+            // perform one step
+            for (i = 0; i < nx; i++) x[i] += dt * xdot[i]; // forward Euler method
+            fmi2Flag = fmu->setContinuousStates(c, x, nx);
+            if (fmi2Flag > fmi2Warning) return error("could not set states");
+            if (loggingOn) printf("Step %d to t=%.16g\n", nSteps, time);
+
+            // check for state event
+            for (i = 0; i < nz; i++) prez[i] = z[i];
+            fmi2Flag = fmu->getEventIndicators(c, z, nz);
+            if (fmi2Flag > fmi2Warning) return error("could not retrieve event indicators");
+            stateEvent = FALSE;
+            for (i=0; i<nz; i++)
+                stateEvent = stateEvent || (prez[i] * z[i] < 0);
+
+            // check for step event, e.g. dynamic state selection
+            fmi2Flag = fmu->completedIntegratorStep(c, fmi2True, &stepEvent, &terminateSimulation);
+            if (fmi2Flag > fmi2Warning) return error("could not complete intgrator step");
+            if (terminateSimulation) {
+                printf("model requested termination at t=%.16g\n", time);
+                break; // success
+            }
+
+            // handle events
+            if (timeEvent || stateEvent || stepEvent) {
+                fmu->enterEventMode(c);
+                if (timeEvent) {
+                    nTimeEvents++;
+                    if (loggingOn) printf("time event at t=%.16g\n", time);
+                }
+                if (stateEvent) {
+                    nStateEvents++;
+                    if (loggingOn) for (i=0; i<nz; i++)
+                        printf("state event %s z[%d] at t=%.16g\n",
+                               (prez[i]>0 && z[i]<0) ? "-\\-" : "-/-", i, time);
+                }
+                if (stepEvent) {
+                    nStepEvents++;
+                    if (loggingOn) printf("step event at t=%.16g\n", time);
+                }
+
+                // event iteration in one step, ignoring intermediate results
+                eventInfo.newDiscreteStatesNeeded = fmi2True;
+                eventInfo.terminateSimulation = fmi2False;
+                while (eventInfo.newDiscreteStatesNeeded && !eventInfo.terminateSimulation) {
+                    // update discrete states
+                    fmi2Flag = fmu->newDiscreteStates(c, &eventInfo);
+                    if (fmi2Flag > fmi2Warning) return error("could not set a new discrete state");
+
+                    // check for change of value of states
+                    if (eventInfo.valuesOfContinuousStatesChanged && loggingOn) {
+                        printf("continuous state values changed at t=%.16g\n", time);
+                    }
+                    if (eventInfo.nominalsOfContinuousStatesChanged && loggingOn){
+                        printf("nominals of continuous state changed  at t=%.16g\n", time);
+                    }
+                }
+                if (eventInfo.terminateSimulation) {
+                    printf("model requested termination at t=%.16g\n", time);
+                    break; // success
+                }
+
+                // enter Continuous-Time Mode
+                fmu->enterContinuousTimeMode(c);
+            } // if event
+            outputRow(fmu, c, time, file, separator, fmi2False); // output values for this step
+            nSteps++;
+        } // while
+    }
+    // cleanup
+    fmu->terminate(c);
+    fmu->freeInstance(c);
+    fclose(file);
+    if (x != NULL) free(x);
+    if (xdot != NULL) free(xdot);
+    if (z != NULL) free(z);
+    if (prez != NULL) free(prez);
+
+    // print simulation summary
+    printf("Simulation from %g to %g terminated successful\n", tStart, tEnd);
+    printf("  steps ............ %d\n", nSteps);
+    printf("  fixed step size .. %g\n", h);
+    printf("  time events ...... %d\n", nTimeEvents);
+    printf("  state events ..... %d\n", nStateEvents);
+    printf("  step events ...... %d\n", nStepEvents);
+
+    return 1; // success
+}
+
+int main(int argc, char *argv[]) {
+    const char* fmuFileName;
+    int i;
+
+    // parse command line arguments and load the FMU
+    // default arguments value
+    double tEnd = 1.0;
+    double h=0.1;
+    int loggingOn = 0;
+    char csv_separator = ',';
+    char **categories = NULL;
+    int nCategories = 0;
+
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator, &nCategories, &categories);
+    loadFMU(fmuFileName);
+
+        // run the simulation
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c' ",
+            fmuFileName, tEnd, h, loggingOn, csv_separator);
+    printf("log categories={ ");
+    for (i = 0; i < nCategories; i++) printf("%s ", categories[i]);
+    printf("}\n");
+
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator, nCategories, categories);
+    printf("CSV file '%s' written\n", RESULT_FILE);
+
+    // release FMU
+#if WINDOWS
+    FreeLibrary(fmu.dllHandle);
+#else /* WINDOWS */
+    dlclose(fmu.dllHandle);
+#endif /* WINDOWS */
+    freeModelDescription(fmu.modelDescription);
+    if (categories) free(categories);
+
+    // delete temp files obtained by unzipping the FMU
+    deleteUnzippedFiles();
+
+    return EXIT_SUCCESS;
+}

+ 60 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/models/bouncingBall/modelDescription_me.xml

@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="bouncingBall"
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f003}"
+  numberOfEventIndicators="1">
+
+<ModelExchange
+  modelIdentifier="bouncingBall">
+  <SourceFiles>
+    <File name="bouncingBall.c"/>
+  </SourceFiles>
+</ModelExchange>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+<ModelVariables>
+  <ScalarVariable name="h" valueReference="0" description="height, used as state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(h)" valueReference="1" description="velocity of ball"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="v" valueReference="2" description="velocity of ball, used as state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="0" reinit="true"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(v)" valueReference="3" description="acceleration of ball"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="3"/>
+  </ScalarVariable>
+  <ScalarVariable name="g" valueReference="4" description="acceleration of gravity"
+                  causality="parameter" variability="fixed" initial="exact">
+    <Real start="9.81"/>
+  </ScalarVariable>
+  <ScalarVariable name="e" valueReference="5" description="dimensionless parameter"
+                  causality="parameter" variability="tunable" initial="exact">
+    <Real start="0.7" min="0.5" max="1"/>
+  </ScalarVariable>
+</ModelVariables>
+
+<ModelStructure>
+  <Derivatives>
+    <Unknown index="2" />
+    <Unknown index="4" />
+  </Derivatives>
+  <InitialUnknowns>
+    <Unknown index="2"/>
+    <Unknown index="4"/>
+  </InitialUnknowns>
+</ModelStructure>
+
+</fmiModelDescription>

+ 46 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/models/dq/modelDescription_me.xml

@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="dq"
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f000}"
+  numberOfEventIndicators="0">
+
+<ModelExchange
+  modelIdentifier="dq">
+  <SourceFiles>
+    <File name="dq.c"/>
+  </SourceFiles>
+</ModelExchange>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+<ModelVariables>
+  <ScalarVariable name="x" valueReference="0" description="the only state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(x)" valueReference="1"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="k" valueReference="2"
+                  causality="parameter" variability="fixed" initial="exact">
+    <Real start="1"/>
+  </ScalarVariable>
+</ModelVariables>
+
+<ModelStructure>
+  <Derivatives>
+    <Unknown index="2" />
+  </Derivatives>
+  <InitialUnknowns>
+    <Unknown index="2"/>
+  </InitialUnknowns>
+</ModelStructure>
+
+</fmiModelDescription>

+ 35 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/models/inc/modelDescription_me.xml

@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="inc"
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f008}"
+  numberOfEventIndicators="0">
+
+<ModelExchange
+  modelIdentifier="inc">
+  <SourceFiles>
+    <File name="inc.c"/>
+  </SourceFiles>
+</ModelExchange>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+<ModelVariables>
+  <ScalarVariable name="counter" valueReference="0" description="counts the seconds"
+                  causality="output" variability="discrete" initial="exact">
+     <Integer start="1"/>
+  </ScalarVariable>
+</ModelVariables>
+
+<ModelStructure>
+  <Outputs>
+    <Unknown index="1" />
+  </Outputs>
+</ModelStructure>
+
+</fmiModelDescription>

+ 71 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/models/values/modelDescription_me.xml

@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="values"
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f004}"
+  numberOfEventIndicators="0">
+
+<ModelExchange
+  modelIdentifier="values">
+  <SourceFiles>
+    <File name="values.c"/>
+  </SourceFiles>
+</ModelExchange>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+<ModelVariables>
+  <ScalarVariable name="x" valueReference="0" description="used as continuous state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(x)" valueReference="1" description="time derivative of x"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="1"/>
+  </ScalarVariable>
+  <ScalarVariable name="int_in" valueReference="0" description="integer input"
+                  causality="input" variability="discrete">
+    <Integer start="2"/>
+  </ScalarVariable>
+  <ScalarVariable name="int_out" valueReference="1" description="index in string array 'month'"
+                  causality="output" variability="discrete" initial="exact">
+    <Integer start="0"/>
+  </ScalarVariable>
+  <ScalarVariable name="bool_in" valueReference="0" description="boolean input"
+                  causality="input" variability="discrete">
+    <Boolean start="true"/>
+  </ScalarVariable>
+  <ScalarVariable name="bool_out" valueReference="1" description="boolean output"
+                  causality="output" variability="discrete" initial="exact">
+    <Boolean start="false"/>
+  </ScalarVariable>
+  <ScalarVariable name="string_in" valueReference="0" description="string input"
+                  causality="input" variability="discrete">
+    <String start="QTronic"/>
+  </ScalarVariable>
+  <ScalarVariable name="string_out" valueReference="1" description="the string month[int_out]"
+                  causality="output" variability="discrete" initial="exact">
+    <String start="jan"/>
+  </ScalarVariable>
+</ModelVariables>
+
+<ModelStructure>
+  <Outputs>
+    <Unknown index="4" />
+    <Unknown index="6" />
+    <Unknown index="8" />
+  </Outputs>
+  <Derivatives>
+    <Unknown index="2" />
+  </Derivatives>
+  <InitialUnknowns>
+    <Unknown index="2"/>
+  </InitialUnknowns>
+</ModelStructure>
+
+</fmiModelDescription>

+ 56 - 0
examples/mass_spring_damper/fmusdk/fmu20/src/models/vanDerPol/modelDescription_me.xml

@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="2.0"
+  modelName="van der Pol oscillator"
+  guid="{8c4e810f-3da3-4a00-8276-176fa3c9f000}"
+  numberOfEventIndicators="0">
+
+<ModelExchange
+  modelIdentifier="vanDerPol">
+  <SourceFiles>
+    <File name="vanDerPol.c"/>
+  </SourceFiles>
+</ModelExchange>
+
+<LogCategories>
+  <Category name="logAll"/>
+  <Category name="logError"/>
+  <Category name="logFmiCall"/>
+  <Category name="logEvent"/>
+</LogCategories>
+
+<ModelVariables>
+  <ScalarVariable name="x0" valueReference="0" description="the first state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="2"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(x0)" valueReference="1"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="1"/>
+  </ScalarVariable> 
+  <ScalarVariable name="x1" valueReference="2" description="the second state"
+                  causality="local" variability="continuous" initial="exact">
+    <Real start="0"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(x1)" valueReference="3"
+                  causality="local" variability="continuous" initial="calculated">
+    <Real derivative="3"/>
+  </ScalarVariable> 
+  <ScalarVariable name="mu" valueReference="4" causality="parameter"
+                  variability="fixed" initial="exact">
+    <Real start="1"/>
+  </ScalarVariable>
+</ModelVariables>
+
+<ModelStructure>
+  <Derivatives>
+    <Unknown index="2" />
+    <Unknown index="4" />
+  </Derivatives>
+  <InitialUnknowns>
+    <Unknown index="2"/>
+    <Unknown index="4"/>
+  </InitialUnknowns>
+</ModelStructure>
+
+</fmiModelDescription>