diff --git a/cmake/CompilerFlags.cmake b/cmake/CompilerFlags.cmake index 1ca7414653b..009e3c740f0 100644 --- a/cmake/CompilerFlags.cmake +++ b/cmake/CompilerFlags.cmake @@ -104,6 +104,7 @@ ELSEIF ( CMAKE_COMPILER_IS_GNUCXX OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" ADD_CXX_DEFINITIONS("-pipe") # Faster compiler processing ADD_CXX_DEFINITIONS("-pedantic") # Turn on warnings about constructs/situations that may be non-portable or outside of the standard ADD_CXX_DEFINITIONS("-Wall -Wextra") # Turn on warnings + ADD_CXX_DEFINITIONS("-Werror") # Treat warnings as errors ADD_CXX_DEFINITIONS("-Wno-unknown-pragmas") if (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 9.0) ADD_CXX_DEFINITIONS("-Wno-deprecated-copy") diff --git a/src/EnergyPlus/CMakeLists.txt b/src/EnergyPlus/CMakeLists.txt index c7568fe2f87..99d0409f604 100644 --- a/src/EnergyPlus/CMakeLists.txt +++ b/src/EnergyPlus/CMakeLists.txt @@ -794,6 +794,9 @@ if(BUILD_GROUND_PLOT) endif() if(UNIX AND NOT APPLE) target_link_libraries( energypluslib dl ) + if (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 9.0) + target_link_libraries( energypluslib util ) + endif() endif() if (WIN32) target_link_libraries( energypluslib Shlwapi ) diff --git a/src/EnergyPlus/InputProcessing/InputProcessor.cc b/src/EnergyPlus/InputProcessing/InputProcessor.cc index b34332162a8..406104e23cf 100644 --- a/src/EnergyPlus/InputProcessing/InputProcessor.cc +++ b/src/EnergyPlus/InputProcessing/InputProcessor.cc @@ -1233,7 +1233,7 @@ void InputProcessor::getObjectDefMaxArgs(EnergyPlusData &state, extension_key = key.value().get(); } - for (auto const obj : *objects) { + for (auto const &obj : *objects) { if (obj.find(extension_key) != obj.end()) { auto const size = obj[extension_key].size(); if (size > max_size) max_size = size; diff --git a/third_party/FMI/eplusModelFunctions.h b/third_party/FMI/eplusModelFunctions.h index 7938f194824..e902ebc3353 100644 --- a/third_party/FMI/eplusModelFunctions.h +++ b/third_party/FMI/eplusModelFunctions.h @@ -6,23 +6,24 @@ /// /// /// \author Thierry Stephane Nouidui, -/// Simulation Research Group, +/// Simulation Research Group, /// LBNL, /// TSNouidui@lbl.gov /// /// \date 2011-11-11 /// -/// This header file defines the energyplus functions +/// This header file defines the energyplus functions /// that mapped to fmiFunctions and will be exported /// in .dll /////////////////////////////////////////////////////// +#include "FMI/fmiModelFunctions.h" #include "fmiModelTypes.h" #include /* Export fmi functions on Windows */ #ifdef _MSC_VER -#define DllExport __declspec( dllexport ) -#define DllImport __declspec( dllexport ) +#define DllExport __declspec(dllexport) +#define DllImport __declspec(dllexport) #else #define DllExport @@ -30,7 +31,7 @@ /* make sure all compiler use the same alignment policies for structures */ #ifdef WIN32 -#pragma pack(push,8) +#pragma pack(push, 8) #endif /* Version number */ @@ -46,48 +47,46 @@ EnergyPlus Functions for FMI for Co-Simulation ****************************************************/ -DllExport fmiComponent fmiEPlusInstantiateSlave(char* fmuResFolder, - fmiInteger *sizefmuResFolder, fmiReal *timeOut, fmiInteger *visible, - fmiInteger *interactive, fmiInteger *loggingOn, fmiInteger *index); +DllExport fmiComponent fmiEPlusInstantiateSlave(char *fmuResFolder, + fmiInteger *sizefmuResFolder, + fmiReal *timeOut, + fmiInteger *visible, + fmiInteger *interactive, + fmiInteger *loggingOn, + fmiInteger *index); -DllExport fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, - fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index); +DllExport fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index); -DllExport fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef [], - fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index); +DllExport fmiStatus +fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index); -DllExport fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], - fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index); +DllExport fmiStatus +fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index); -DllExport fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, - fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index); +DllExport fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index); DllExport fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation); -fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index); +fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index); -DllExport fmiInteger fmiEPlusUnpack(char* fmuName, char* fmuOutputWorkingFolder, - fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder); +DllExport fmiInteger fmiEPlusUnpack(char *fmuName, char *fmuOutputWorkingFolder, fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder); -DllExport fmiInteger addLibPathCurrentWorkingFolder(char* trimfmuOutputWorkingFolder_wLiB, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *index); +DllExport fmiInteger addLibPathCurrentWorkingFolder(char *trimfmuOutputWorkingFolder_wLiB, + char *fmuWorkingFolder, + fmiInteger *sizefmuWorkingFolder, + fmiInteger *index); -DllExport fmiValueReference getValueReferenceByNameFMUInputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index); +DllExport fmiValueReference getValueReferenceByNameFMUInputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index); -DllExport fmiValueReference getValueReferenceByNameFMUOutputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index); +DllExport fmiValueReference getValueReferenceByNameFMUOutputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index); -DllExport fmiInteger model_ID_GUID(char* fmuInstanceName, char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, - fmiInteger *numOutputs); +DllExport fmiInteger +model_ID_GUID(char *fmuInstanceName, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, fmiInteger *numOutputs); -DllExport fmiInteger addFMURootFolderName(char* fmuOutputWorkingFolder, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder); +DllExport fmiInteger addFMURootFolderName(char *fmuOutputWorkingFolder, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder); -DllExport fmiInteger getfmiEPlusVersion(char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index); +DllExport fmiInteger getfmiEPlusVersion(char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index); -DllExport fmiInteger checkOperatingSystem(char* errorMessage); +DllExport fmiInteger checkOperatingSystem(char *errorMessage); #endif // eplusModelFunctions_h diff --git a/third_party/FMI/fmiFunctions.h b/third_party/FMI/fmiFunctions.h index addaef9396b..817c9b2bd11 100644 --- a/third_party/FMI/fmiFunctions.h +++ b/third_party/FMI/fmiFunctions.h @@ -61,7 +61,7 @@ /* Export fmi functions on Windows */ #ifdef _MSC_VER -#define DllExport __declspec( dllexport ) +#define DllExport __declspec(dllexport) #else #define DllExport #endif @@ -69,84 +69,87 @@ /* Macros to construct the real function name (prepend function name by MODEL_IDENTIFIER + "_") */ -#define fmiPaste(a,b) a ## b -#define fmiPasteB(a,b) fmiPaste(a,b) +#define fmiPaste(a, b) a##b +#define fmiPasteB(a, b) fmiPaste(a, b) #define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name) /*************************************************** Common Functions ****************************************************/ #define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform) -#define fmiGetVersion fmiFullName(_fmiGetVersion) -#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) +#define fmiGetVersion fmiFullName(_fmiGetVersion) +#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) /*Data Exchange*/ -#define fmiSetReal fmiFullName(_fmiSetReal) -#define fmiSetInteger fmiFullName(_fmiSetInteger) -#define fmiSetBoolean fmiFullName(_fmiSetBoolean) -#define fmiSetString fmiFullName(_fmiSetString) +#define fmiSetReal fmiFullName(_fmiSetReal) +#define fmiSetInteger fmiFullName(_fmiSetInteger) +#define fmiSetBoolean fmiFullName(_fmiSetBoolean) +#define fmiSetString fmiFullName(_fmiSetString) -#define fmiGetReal fmiFullName(_fmiGetReal) -#define fmiGetInteger fmiFullName(_fmiGetInteger) -#define fmiGetBoolean fmiFullName(_fmiGetBoolean) -#define fmiGetString fmiFullName(_fmiGetString) +#define fmiGetReal fmiFullName(_fmiGetReal) +#define fmiGetInteger fmiFullName(_fmiGetInteger) +#define fmiGetBoolean fmiFullName(_fmiGetBoolean) +#define fmiGetString fmiFullName(_fmiGetString) /*************************************************** Functions for FMI for Co-Simulation ****************************************************/ -#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) -#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) -#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) -#define fmiResetSlave fmiFullName(_fmiResetSlave) -#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) -#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives) +#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) +#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) +#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) +#define fmiResetSlave fmiFullName(_fmiResetSlave) +#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) +#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives) #define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives) -#define fmiDoStep fmiFullName(_fmiDoStep) -#define fmiCancelStep fmiFullName(_fmiCancelStep) -#define fmiGetStatus fmiFullName(_fmiGetStatus) -#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) -#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) -#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) -#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) +#define fmiDoStep fmiFullName(_fmiDoStep) +#define fmiCancelStep fmiFullName(_fmiCancelStep) +#define fmiGetStatus fmiFullName(_fmiGetStatus) +#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) +#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) +#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) +#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) /* Version number */ #define fmiVersion "1.0" /* make sure all compiler use the same alignment policies for structures */ #ifdef WIN32 -#pragma pack(push,8) +#pragma pack(push, 8) #endif - /* Type definitions */ - typedef enum {fmiOK, - fmiWarning, - fmiDiscard, - fmiError, - fmiFatal, - fmiPending} fmiStatus; - - typedef void (*fmiCallbackLogger) (fmiComponent c, fmiString instanceName, fmiStatus status, - fmiString category, fmiString message, ...); - typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size); - typedef void (*fmiCallbackFreeMemory) (void* obj); - typedef void (*fmiStepFinished) (fmiComponent c, fmiStatus status); - - typedef struct { - fmiCallbackLogger logger; - fmiCallbackAllocateMemory allocateMemory; - fmiCallbackFreeMemory freeMemory; - fmiStepFinished stepFinished; - } fmiCallbackFunctions; - - typedef struct { - fmiBoolean iterationConverged; - fmiBoolean stateValueReferencesChanged; - fmiBoolean stateValuesChanged; - fmiBoolean terminateSimulation; - fmiBoolean upcomingTimeEvent; - fmiReal nextEventTime; - } fmiEventInfo; +typedef enum +{ + fmiOK, + fmiWarning, + fmiDiscard, + fmiError, + fmiFatal, + fmiPending +} fmiStatus; + +typedef void (*fmiCallbackLogger)(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...); +typedef void *(*fmiCallbackAllocateMemory)(size_t nobj, size_t size); +typedef void (*fmiCallbackFreeMemory)(void *obj); +typedef void (*fmiStepFinished)(fmiComponent c, fmiStatus status); + +typedef struct +{ + fmiCallbackLogger logger; + fmiCallbackAllocateMemory allocateMemory; + fmiCallbackFreeMemory freeMemory; + fmiStepFinished stepFinished; +} fmiCallbackFunctions; + +typedef struct +{ + fmiBoolean iterationConverged; + fmiBoolean stateValueReferencesChanged; + fmiBoolean stateValuesChanged; + fmiBoolean terminateSimulation; + fmiBoolean upcomingTimeEvent; + fmiReal nextEventTime; +} fmiEventInfo; /* reset alignment policy to the one set before reading this file */ #ifdef WIN32 @@ -158,74 +161,62 @@ Common Functions ****************************************************/ /* Inquire version numbers of header files */ - DllExport const char* fmiGetTypesPlatform(); - DllExport const char* fmiGetVersion(); +DllExport const char *fmiGetTypesPlatform(); +DllExport const char *fmiGetVersion(); - DllExport fmiStatus fmiSetDebugLogging (fmiComponent c, fmiBoolean loggingOn); +DllExport fmiStatus fmiSetDebugLogging(fmiComponent c, fmiBoolean loggingOn); /* Data Exchange Functions*/ - DllExport fmiStatus fmiGetReal (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); - DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); - DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); - DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); +DllExport fmiStatus fmiGetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); +DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); +DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); +DllExport fmiStatus fmiGetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); - DllExport fmiStatus fmiSetReal (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); - DllExport fmiStatus fmiSetInteger (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); - DllExport fmiStatus fmiSetBoolean (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); - DllExport fmiStatus fmiSetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); +DllExport fmiStatus fmiSetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); +DllExport fmiStatus fmiSetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); +DllExport fmiStatus fmiSetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); +DllExport fmiStatus fmiSetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); /*************************************************** Functions for FMI for Co-Simulation ****************************************************/ /* Creation and destruction of slave instances and setting debug status */ - DllExport fmiComponent fmiInstantiateSlave(fmiString instanceName, - fmiString fmuGUID, - fmiString fmuLocation, - fmiString mimeType, - fmiReal timeout, - fmiBoolean visible, - fmiBoolean interactive, - fmiCallbackFunctions functions, - fmiBoolean loggingOn); - - DllExport fmiStatus fmiInitializeSlave(fmiComponent c, - fmiReal tStart, - fmiBoolean StopTimeDefined, - fmiReal tStop); - - DllExport fmiStatus fmiTerminateSlave (fmiComponent c); - DllExport fmiStatus fmiResetSlave (fmiComponent c); - DllExport void fmiFreeSlaveInstance(fmiComponent c); - - DllExport fmiStatus fmiSetRealInputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - const fmiReal value[]); - - DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - fmiReal value[]); - - DllExport fmiStatus fmiCancelStep(fmiComponent c); - DllExport fmiStatus fmiDoStep (fmiComponent c, - fmiReal currentCommunicationPoint, - fmiReal communicationStepSize, - fmiBoolean newStep); - - - typedef enum {fmiDoStepStatus, - fmiPendingStatus, - fmiLastSuccessfulTime} fmiStatusKind; - - DllExport fmiStatus fmiGetStatus (fmiComponent c, const fmiStatusKind s, fmiStatus* value); - DllExport fmiStatus fmiGetRealStatus (fmiComponent c, const fmiStatusKind s, fmiReal* value); - DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value); - DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value); - DllExport fmiStatus fmiGetStringStatus (fmiComponent c, const fmiStatusKind s, fmiString* value); - +DllExport fmiComponent fmiInstantiateSlave(fmiString instanceName, + fmiString fmuGUID, + fmiString fmuLocation, + fmiString mimeType, + fmiReal timeout, + fmiBoolean visible, + fmiBoolean interactive, + fmiCallbackFunctions functions, + fmiBoolean loggingOn); + +DllExport fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop); + +DllExport fmiStatus fmiTerminateSlave(fmiComponent c); +DllExport fmiStatus fmiResetSlave(fmiComponent c); +DllExport void fmiFreeSlaveInstance(fmiComponent c); + +DllExport fmiStatus +fmiSetRealInputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], const fmiReal value[]); + +DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], fmiReal value[]); + +DllExport fmiStatus fmiCancelStep(fmiComponent c); +DllExport fmiStatus fmiDoStep(fmiComponent c, fmiReal currentCommunicationPoint, fmiReal communicationStepSize, fmiBoolean newStep); + +typedef enum +{ + fmiDoStepStatus, + fmiPendingStatus, + fmiLastSuccessfulTime +} fmiStatusKind; + +DllExport fmiStatus fmiGetStatus(fmiComponent c, const fmiStatusKind s, fmiStatus *value); +DllExport fmiStatus fmiGetRealStatus(fmiComponent c, const fmiStatusKind s, fmiReal *value); +DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger *value); +DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean *value); +DllExport fmiStatus fmiGetStringStatus(fmiComponent c, const fmiStatusKind s, fmiString *value); #endif // fmiFunctions_h diff --git a/third_party/FMI/fmiModelFunctions.h b/third_party/FMI/fmiModelFunctions.h index 7847cac1200..7c3f00f27c9 100644 --- a/third_party/FMI/fmiModelFunctions.h +++ b/third_party/FMI/fmiModelFunctions.h @@ -88,7 +88,7 @@ /* Export fmi functions on Windows */ #ifdef _MSC_VER -#define DllExport __declspec( dllexport ) +#define DllExport __declspec(dllexport) #else #define DllExport #endif @@ -96,55 +96,55 @@ /* Macros to construct the real function name (prepend function name by MODEL_IDENTIFIER + "_") */ -#define fmiPaste(a,b) a ## b -#define fmiPasteB(a,b) fmiPaste(a,b) +#define fmiPaste(a, b) a##b +#define fmiPasteB(a, b) fmiPaste(a, b) #define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name) /*************************************************** Common Functions ****************************************************/ //#define fmiGetModelTypesPlatform fmiFullName(_fmiGetModelTypesPlatform) // Zuo: definition in model-ex V1.0 -#define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform) // Zuo: definition in co-sim V1.0 -#define fmiGetVersion fmiFullName(_fmiGetVersion) -#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) +#define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform) // Zuo: definition in co-sim V1.0 +#define fmiGetVersion fmiFullName(_fmiGetVersion) +#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) /*Data Exchange*/ -#define fmiSetReal fmiFullName(_fmiSetReal) -#define fmiSetInteger fmiFullName(_fmiSetInteger) -#define fmiSetBoolean fmiFullName(_fmiSetBoolean) -#define fmiSetString fmiFullName(_fmiSetString) +#define fmiSetReal fmiFullName(_fmiSetReal) +#define fmiSetInteger fmiFullName(_fmiSetInteger) +#define fmiSetBoolean fmiFullName(_fmiSetBoolean) +#define fmiSetString fmiFullName(_fmiSetString) -#define fmiGetReal fmiFullName(_fmiGetReal) -#define fmiGetInteger fmiFullName(_fmiGetInteger) -#define fmiGetBoolean fmiFullName(_fmiGetBoolean) -#define fmiGetString fmiFullName(_fmiGetString) +#define fmiGetReal fmiFullName(_fmiGetReal) +#define fmiGetInteger fmiFullName(_fmiGetInteger) +#define fmiGetBoolean fmiFullName(_fmiGetBoolean) +#define fmiGetString fmiFullName(_fmiGetString) /*************************************************** Functions for FMI for Co-Simulation ****************************************************/ //#define fmiInstantiateModel fmiFullName(_fmiInstantiateModel) // Zuo: definition in model-ex V1.0 -#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) // Zuo: definition in co-sim V1.0 +#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) // Zuo: definition in co-sim V1.0 //#define fmiInitialize fmiFullName(_fmiInitialize) // Zuo: definition in model-ex V1.0 -#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) // Zuo: definition in co-sim V1.0 +#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) // Zuo: definition in co-sim V1.0 //#define fmiTerminate fmiFullName(_fmiTerminate) // Zuo: defintion in modle-ex V1.0 -#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) // Zuo: defnition in co-sim V1.0 +#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) // Zuo: defnition in co-sim V1.0 //#define fmiFreeModelInstance fmiFullName(_fmiFreeModelInstance) // Zuo: definition in model-ex V1.0 -#define fmiResetSlave fmiFullName(_fmiResetSlave) // Zuo: definition in co-sim V1.0 -#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) // Zuo: definition in co-sim V1.0 -#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives)// Zuo: definition in co-sim V1.0 +#define fmiResetSlave fmiFullName(_fmiResetSlave) // Zuo: definition in co-sim V1.0 +#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) // Zuo: definition in co-sim V1.0 +#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives) // Zuo: definition in co-sim V1.0 //#define fmiGetDerivatives fmiFullName(_fmiGetDerivatives) // Zuo: definition in model-ex V1.0 -#define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives) // Zuo: definition in co-sim V1.0 -#define fmiDoStep fmiFullName(_fmiDoStep) // Zuo: definition in co-sim V1.0 -#define fmiCancelStep fmiFullName(_fmiCancelStep) // Zuo: definition in co-sim V1.0 -#define fmiGetStatus fmiFullName(_fmiGetStatus) // Zuo: definition in co-sim V1.0 -#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) // Zuo: definition in co-sim V1.0 -#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) // Zuo: definition in co-sim V1.0 -#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) // Zuo: definition in co-sim V1.0 -#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) // Zuo: definition in co-sim V1.0 - -//#define fmiSetTime fmiFullName(_fmiSetTime) // Zuo: not in co-sim V1.0 -//#define fmiSetContinuousStates fmiFullName(_fmiSetContinuousStates) // Zuo: not in co-sim V1.0 -//#define fmiCompletedIntegratorStep fmiFullName(_fmiCompletedIntegratorStep) // Zuo: not in co-sim V1.0 +#define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives) // Zuo: definition in co-sim V1.0 +#define fmiDoStep fmiFullName(_fmiDoStep) // Zuo: definition in co-sim V1.0 +#define fmiCancelStep fmiFullName(_fmiCancelStep) // Zuo: definition in co-sim V1.0 +#define fmiGetStatus fmiFullName(_fmiGetStatus) // Zuo: definition in co-sim V1.0 +#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) // Zuo: definition in co-sim V1.0 +#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) // Zuo: definition in co-sim V1.0 +#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) // Zuo: definition in co-sim V1.0 +#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) // Zuo: definition in co-sim V1.0 + +//#define fmiSetTime fmiFullName(_fmiSetTime) // Zuo: not in co-sim V1.0 +//#define fmiSetContinuousStates fmiFullName(_fmiSetContinuousStates) // Zuo: not in co-sim V1.0 +//#define fmiCompletedIntegratorStep fmiFullName(_fmiCompletedIntegratorStep) // Zuo: not in co-sim V1.0 //#define fmiGetEventIndicators fmiFullName(_fmiGetEventIndicators) // Zuo: not in co-sim V1.0 //#define fmiEventUpdate fmiFullName(_fmiEventUpdate) // Zuo: not in co-sim V1.0 //#define fmiGetContinuousStates fmiFullName(_fmiGetContinuousStates) // Zuo: not in co-sim V1.0 @@ -153,43 +153,45 @@ Functions for FMI for Co-Simulation /* make sure all compiler use the same alignment policies for structures */ #ifdef WIN32 -#pragma pack(push,8) +#pragma pack(push, 8) #endif /* Version number */ #define fmiVersion "1.0" /* Type definitions */ - typedef enum {fmiOK, - fmiWarning, - fmiDiscard, - fmiError, - //fmiFatal // Zuo: definition in model-ex V1.0 - fmiPending // Zuo: definition in co-sim V1.0 - } fmiStatus; - - typedef void (*fmiCallbackLogger) (fmiComponent c, fmiString instanceName, fmiStatus status, - fmiString category, fmiString message, ...); - typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size); - typedef void (*fmiCallbackFreeMemory) (void* obj); - typedef void (*fmiStepFinished) (fmiComponent c, fmiStatus status); // Zuo: definition in co-sim V1.0 - - typedef struct { - fmiCallbackLogger logger; - fmiCallbackAllocateMemory allocateMemory; - fmiCallbackFreeMemory freeMemory; - fmiStepFinished stepFinished; // Zuo: definition in co-sim V1.0 - } fmiCallbackFunctions; - - typedef struct { - fmiBoolean iterationConverged; - fmiBoolean stateValueReferencesChanged; - fmiBoolean stateValuesChanged; - fmiBoolean terminateSimulation; - fmiBoolean upcomingTimeEvent; - fmiReal nextEventTime; - } fmiEventInfo; - +typedef enum +{ + fmiOK, + fmiWarning, + fmiDiscard, + fmiError, + // fmiFatal // Zuo: definition in model-ex V1.0 + fmiPending // Zuo: definition in co-sim V1.0 +} fmiStatus; + +typedef void (*fmiCallbackLogger)(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...); +typedef void *(*fmiCallbackAllocateMemory)(size_t nobj, size_t size); +typedef void (*fmiCallbackFreeMemory)(void *obj); +typedef void (*fmiStepFinished)(fmiComponent c, fmiStatus status); // Zuo: definition in co-sim V1.0 + +typedef struct +{ + fmiCallbackLogger logger; + fmiCallbackAllocateMemory allocateMemory; + fmiCallbackFreeMemory freeMemory; + fmiStepFinished stepFinished; // Zuo: definition in co-sim V1.0 +} fmiCallbackFunctions; + +typedef struct +{ + fmiBoolean iterationConverged; + fmiBoolean stateValueReferencesChanged; + fmiBoolean stateValuesChanged; + fmiBoolean terminateSimulation; + fmiBoolean upcomingTimeEvent; + fmiReal nextEventTime; +} fmiEventInfo; /* reset alignment policy to the one set before reading this file */ #ifdef WIN32 @@ -200,13 +202,12 @@ Functions for FMI for Co-Simulation Common Functions ****************************************************/ /* Inquire version numbers of header files */ - /* Inquire version numbers of header files */ - //DllExport const char* fmiGetModelTypesPlatform(); //Zuo: definition in model-ex V1.0 - DllExport const char* fmiGetTypesPlatform(); //Zuo: definition in co-sim V1.0 - DllExport const char* fmiGetVersion(); - - DllExport fmiStatus fmiSetDebugLogging (fmiComponent c, fmiBoolean loggingOn); //Zuo: definition in co-sim V1.0 +/* Inquire version numbers of header files */ +// DllExport const char* fmiGetModelTypesPlatform(); //Zuo: definition in model-ex V1.0 +DllExport const char *fmiGetTypesPlatform(); // Zuo: definition in co-sim V1.0 +DllExport const char *fmiGetVersion(); +DllExport fmiStatus fmiSetDebugLogging(fmiComponent c, fmiBoolean loggingOn); // Zuo: definition in co-sim V1.0 /*************************************************** @@ -214,82 +215,72 @@ Functions for FMI for Co-Simulation ****************************************************/ /* Creation and destruction of model instances and setting debug status */ - // Zuo: definition in model-ex V1.0 - /*DllExport fmiComponent fmiInstantiateModel (fmiString instanceName, - fmiString GUID, - fmiCallbackFunctions functions, - fmiBoolean loggingOn); */ - // Zuo: definition in co-sim V1.0 - DllExport fmiComponent fmiInstantiateSlave (fmiString instanceName, - fmiString GUID, - fmiString fmuLocation, - fmiString mimeType, - fmiReal timeout, - fmiBoolean visible, - fmiBoolean interactive, - fmiCallbackFunctions functions, - fmiBoolean loggingOn); - // Zuo: definition in model-ex V1.0 - //DllExport fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled, - //fmiReal relativeTolerance, fmiEventInfo* eventInfo); - // Zuo: definition in co-sim V1.0 - DllExport fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, - fmiBoolean StopTimeDefined, fmiReal tStop); - - DllExport fmiStatus fmiTerminateSlave (fmiComponent c); // Zuo: definition in co-sim V1.0 - DllExport fmiStatus fmiResetSlave (fmiComponent c); // Zuo: definition in co-sim V1.0 - //DllExport void fmiFreeModelInstance(fmiComponent c); // Zuo: definition in model-ex V1.0 - DllExport void fmiFreeSlaveInstance(fmiComponent c); // Zuo: definition in co-sim V1.0 - - // Zuo: definition in co-sim V1.0 - DllExport fmiStatus fmiSetRealInputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - const fmiReal value[]); - - // Zuo: definition in co-sim V1.0 - DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - fmiReal value[]); - - - DllExport fmiStatus fmiCancelStep(fmiComponent c); - - DllExport fmiStatus fmiDoStep (fmiComponent c, - fmiReal currentCommunicationPoint, - fmiReal communicationStepSize, - fmiBoolean newStep); - - //DllExport fmiStatus fmiSetDebugLogging (fmiComponent c, fmiBoolean loggingOn); // Zuo definition in model-ex V1.0 - - typedef enum {fmiDoStepStatus, - fmiPendingStatus, - fmiLastSuccessfulTime} fmiStatusKind; +// Zuo: definition in model-ex V1.0 +/*DllExport fmiComponent fmiInstantiateModel (fmiString instanceName, + fmiString GUID, + fmiCallbackFunctions functions, + fmiBoolean loggingOn); */ +// Zuo: definition in co-sim V1.0 +DllExport fmiComponent fmiInstantiateSlave(fmiString instanceName, + fmiString GUID, + fmiString fmuLocation, + fmiString mimeType, + fmiReal timeout, + fmiBoolean visible, + fmiBoolean interactive, + fmiCallbackFunctions functions, + fmiBoolean loggingOn); +// Zuo: definition in model-ex V1.0 +// DllExport fmiStatus fmiInitialize(fmiComponent c, fmiBoolean toleranceControlled, +// fmiReal relativeTolerance, fmiEventInfo* eventInfo); +// Zuo: definition in co-sim V1.0 +DllExport fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop); + +DllExport fmiStatus fmiTerminateSlave(fmiComponent c); // Zuo: definition in co-sim V1.0 +DllExport fmiStatus fmiResetSlave(fmiComponent c); // Zuo: definition in co-sim V1.0 +// DllExport void fmiFreeModelInstance(fmiComponent c); // Zuo: definition in model-ex V1.0 +DllExport void fmiFreeSlaveInstance(fmiComponent c); // Zuo: definition in co-sim V1.0 + +// Zuo: definition in co-sim V1.0 +DllExport fmiStatus +fmiSetRealInputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], const fmiReal value[]); + +// Zuo: definition in co-sim V1.0 +DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], fmiReal value[]); + +DllExport fmiStatus fmiCancelStep(fmiComponent c); + +DllExport fmiStatus fmiDoStep(fmiComponent c, fmiReal currentCommunicationPoint, fmiReal communicationStepSize, fmiBoolean newStep); + +// DllExport fmiStatus fmiSetDebugLogging (fmiComponent c, fmiBoolean loggingOn); // Zuo definition in model-ex V1.0 + +typedef enum +{ + fmiDoStepStatus, + fmiPendingStatus, + fmiLastSuccessfulTime +} fmiStatusKind; /* Providing independent variables and re-initialization of caching */ - //DllExport fmiStatus fmiSetTime (fmiComponent c, fmiReal time); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiSetContinuousStates (fmiComponent c, const fmiReal x[], size_t nx); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate); // Zuo: not in co-sim V1.0 - DllExport fmiStatus fmiSetReal (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); - DllExport fmiStatus fmiSetInteger (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); - DllExport fmiStatus fmiSetBoolean (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); - DllExport fmiStatus fmiSetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); - +// DllExport fmiStatus fmiSetTime (fmiComponent c, fmiReal time); // Zuo: not in co-sim V1.0 +// DllExport fmiStatus fmiSetContinuousStates (fmiComponent c, const fmiReal x[], size_t nx); // Zuo: not in co-sim V1.0 +// DllExport fmiStatus fmiCompletedIntegratorStep(fmiComponent c, fmiBoolean* callEventUpdate); // Zuo: not in co-sim V1.0 +DllExport fmiStatus fmiSetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); +DllExport fmiStatus fmiSetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); +DllExport fmiStatus fmiSetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); +DllExport fmiStatus fmiSetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); /* Evaluation of the model equations */ - - - //DllExport fmiStatus fmiGetDerivatives (fmiComponent c, fmiReal derivatives[] , size_t nx); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni); // Zuo: not in cos-im V1.0 - //DllExport fmiStatus fmiEventUpdate (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiGetContinuousStates (fmiComponent c, fmiReal states[], size_t nx); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiGetStateValueReferences (fmiComponent c, fmiValueReference vrx[], size_t nx); // Zuo: not in co-sim V1.0 - //DllExport fmiStatus fmiTerminate (fmiComponent c); // Zuo: not in co-sim V1.0 - - + +// DllExport fmiStatus fmiGetDerivatives (fmiComponent c, fmiReal derivatives[] , size_t nx); // Zuo: not in co-sim V1.0 +// DllExport fmiStatus fmiGetEventIndicators(fmiComponent c, fmiReal eventIndicators[], size_t ni); // Zuo: not in cos-im V1.0 +// DllExport fmiStatus fmiEventUpdate (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo); // Zuo: not in co-sim +// V1.0 +// DllExport fmiStatus fmiGetContinuousStates (fmiComponent c, fmiReal states[], size_t nx); // Zuo: +// not in co-sim V1.0 DllExport fmiStatus fmiGetNominalContinuousStates(fmiComponent c, fmiReal x_nominal[], size_t nx); +// // Zuo: not in co-sim V1.0 DllExport fmiStatus fmiGetStateValueReferences (fmiComponent c, fmiValueReference vrx[], size_t nx); +// // Zuo: not in co-sim V1.0 +// DllExport fmiStatus fmiTerminate (fmiComponent c); +// // Zuo: not in co-sim V1.0 #endif // fmiModelFunctions_h diff --git a/third_party/FMI/fmiModelTypes.h b/third_party/FMI/fmiModelTypes.h index f920b33987c..d966ceadb66 100644 --- a/third_party/FMI/fmiModelTypes.h +++ b/third_party/FMI/fmiModelTypes.h @@ -77,15 +77,15 @@ // mwetter: added ifndef #ifndef fmiPlatformTypes_h - typedef void* fmiComponent; - typedef unsigned int fmiValueReference; - typedef double fmiReal ; - typedef int fmiInteger; - typedef char fmiBoolean; - typedef const char* fmiString ; +typedef void *fmiComponent; +typedef unsigned int fmiValueReference; +typedef double fmiReal; +typedef int fmiInteger; +typedef char fmiBoolean; +typedef const char *fmiString; /* Values for fmiBoolean */ -#define fmiTrue 1 +#define fmiTrue 1 #define fmiFalse 0 /* Undefined value for fmiValueReference (largest unsigned int value) */ diff --git a/third_party/FMI/fmiPlatformTypes.h b/third_party/FMI/fmiPlatformTypes.h index c216beae13e..1836466a3d8 100644 --- a/third_party/FMI/fmiPlatformTypes.h +++ b/third_party/FMI/fmiPlatformTypes.h @@ -58,15 +58,15 @@ */ // mwetter: added ifndef #ifndef fmiModelTypes_h - typedef void* fmiComponent; - typedef unsigned int fmiValueReference; - typedef double fmiReal ; - typedef int fmiInteger; - typedef char fmiBoolean; - typedef const char* fmiString ; +typedef void *fmiComponent; +typedef unsigned int fmiValueReference; +typedef double fmiReal; +typedef int fmiInteger; +typedef char fmiBoolean; +typedef const char *fmiString; /* Values for fmiBoolean */ -#define fmiTrue 1 +#define fmiTrue 1 #define fmiFalse 0 /* Undefined value for fmiValueReference (largest unsigned int value) */ diff --git a/third_party/FMI/fmumini.c b/third_party/FMI/fmumini.c index 570da11893a..ac6bf75e0b2 100644 --- a/third_party/FMI/fmumini.c +++ b/third_party/FMI/fmumini.c @@ -31,46 +31,45 @@ */ #ifndef _WIN32 - #ifndef __USE_FILE_OFFSET64 - #define __USE_FILE_OFFSET64 - #endif - #ifndef __USE_LARGEFILE64 - #define __USE_LARGEFILE64 - #endif - #ifndef _LARGEFILE64_SOURCE - #define _LARGEFILE64_SOURCE - #endif - #ifndef _FILE_OFFSET_BIT - #define _FILE_OFFSET_BIT 64 - #endif +#ifndef __USE_FILE_OFFSET64 +#define __USE_FILE_OFFSET64 +#endif +#ifndef __USE_LARGEFILE64 +#define __USE_LARGEFILE64 +#endif +#ifndef _LARGEFILE64_SOURCE +#define _LARGEFILE64_SOURCE +#endif +#ifndef _FILE_OFFSET_BIT +#define _FILE_OFFSET_BIT 64 +#endif #endif // fopen is 64 bit by default on apple so fopen is fopen64 // linker errors occur by using fopen64 #ifdef __APPLE__ -# define off64_t off_t -# define fopen64 fopen +#define off64_t off_t +#define fopen64 fopen #endif +#include +#include #include #include #include -#include -#include -#include #include +#include #ifdef _WIN32 -# include -# include +#include +#include #else -# include -# include +#include +#include #endif -#include #include "util.h" - +#include #define CASESENSITIVITY (0) #define WRITEBUFFERSIZE (8192) @@ -92,120 +91,108 @@ if it exists */ - /* change_file_date : change the date/time of a file filename : the filename of the file where date/time must be modified dosdate : the new date at the MSDos format (4 bytes) tmu_date : the SAME new date at the tm_unz format */ -void change_file_date(filename,dosdate,tmu_date) - const char *filename; - uLong dosdate; - tm_unz tmu_date; +void change_file_date(filename, dosdate, tmu_date) const char *filename; +uLong dosdate; +tm_unz tmu_date; { #ifdef _WIN32 - HANDLE hFile; - FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; - - hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, - 0,NULL,OPEN_EXISTING,0,NULL); - GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); - DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); - LocalFileTimeToFileTime(&ftLocal,&ftm); - SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); - CloseHandle(hFile); + HANDLE hFile; + FILETIME ftm, ftLocal, ftCreate, ftLastAcc, ftLastWrite; + + hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GetFileTime(hFile, &ftCreate, &ftLastAcc, &ftLastWrite); + DosDateTimeToFileTime((WORD)(dosdate >> 16), (WORD)dosdate, &ftLocal); + LocalFileTimeToFileTime(&ftLocal, &ftm); + SetFileTime(hFile, &ftm, &ftLastAcc, &ftm); + CloseHandle(hFile); #else #ifdef unix - struct utimbuf ut; - struct tm newdate; - newdate.tm_sec = tmu_date.tm_sec; - newdate.tm_min=tmu_date.tm_min; - newdate.tm_hour=tmu_date.tm_hour; - newdate.tm_mday=tmu_date.tm_mday; - newdate.tm_mon=tmu_date.tm_mon; - if (tmu_date.tm_year > 1900) - newdate.tm_year=tmu_date.tm_year - 1900; - else - newdate.tm_year=tmu_date.tm_year ; - newdate.tm_isdst=-1; - - ut.actime=ut.modtime=mktime(&newdate); - utime(filename,&ut); + struct utimbuf ut; + struct tm newdate; + newdate.tm_sec = tmu_date.tm_sec; + newdate.tm_min = tmu_date.tm_min; + newdate.tm_hour = tmu_date.tm_hour; + newdate.tm_mday = tmu_date.tm_mday; + newdate.tm_mon = tmu_date.tm_mon; + if (tmu_date.tm_year > 1900) + newdate.tm_year = tmu_date.tm_year - 1900; + else + newdate.tm_year = tmu_date.tm_year; + newdate.tm_isdst = -1; + + ut.actime = ut.modtime = mktime(&newdate); + utime(filename, &ut); #else - (void)filename; - (void)dosdate; - (void)tmu_date; + (void)filename; + (void)dosdate; + (void)tmu_date; #endif #endif } - /* mymkdir and change_file_date are not 100 % portable As I don't know well Unix, I wait feedback for the unix portion */ -int mymkdir(dirname) - const char* dirname; +int mymkdir(dirname) const char *dirname; { - int ret=0; + int ret = 0; #ifdef _WIN32 ret = _mkdir(dirname); #else #ifdef unix - ret = mkdir (dirname,0775); + ret = mkdir(dirname, 0775); #else - (void)dirname; + (void)dirname; #endif #endif return ret; } -int makedir (newdir) - const char *newdir; +int makedir(newdir) const char *newdir; { - char *buffer ; - char *p; - int len = (int)strlen(newdir); - - if (len <= 0) - return 0; + char *buffer; + char *p; + int len = (int)strlen(newdir); - buffer = (char*)malloc(len+1); - if (buffer==NULL) - { - printf("Error allocating memory\n"); - return UNZ_INTERNALERROR; - } - strcpy(buffer,newdir); + if (len <= 0) return 0; - if (buffer[len-1] == '/') { - buffer[len-1] = '\0'; - } - if (mymkdir(buffer) == 0) - { - free(buffer); - return 1; + buffer = (char *)malloc(len + 1); + if (buffer == NULL) { + printf("Error allocating memory\n"); + return UNZ_INTERNALERROR; } + strcpy(buffer, newdir); - p = buffer+1; - while (1) - { - char hold; + if (buffer[len - 1] == '/') { + buffer[len - 1] = '\0'; + } + if (mymkdir(buffer) == 0) { + free(buffer); + return 1; + } - while(*p && *p != '\\' && *p != '/') - p++; - hold = *p; - *p = 0; - if ((mymkdir(buffer) == -1) && (errno == ENOENT)) - { - printf("couldn't create directory %s\n",buffer); - free(buffer); - return 0; + p = buffer + 1; + while (1) { + char hold; + + while (*p && *p != '\\' && *p != '/') + p++; + hold = *p; + *p = 0; + if ((mymkdir(buffer) == -1) && (errno == ENOENT)) { + printf("couldn't create directory %s\n", buffer); + free(buffer); + return 0; } - if (hold == 0) - break; - *p++ = hold; + if (hold == 0) break; + *p++ = hold; } - free(buffer); - return 1; + free(buffer); + return 1; } void do_banner() @@ -216,113 +203,98 @@ void do_banner() void do_help() { - printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ - " -e Extract without pathname (junk paths)\n" \ - " -x Extract with pathname\n" \ - " -v list files\n" \ - " -l list files\n" \ - " -d directory to extract into\n" \ - " -o overwrite files without prompting\n" \ + printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" + " -e Extract without pathname (junk paths)\n" + " -x Extract with pathname\n" + " -v list files\n" + " -l list files\n" + " -d directory to extract into\n" + " -o overwrite files without prompting\n" " -p extract crypted file using password\n\n"); } void Display64BitsSize(ZPOS64_T n, int size_char) { - /* to avoid compatibility problem , we do here the conversion */ - char number[21]; - int offset=19; - int pos_string = 19; - number[20]=0; - for (;;) { - number[offset]=(char)((n%10)+'0'); - if (number[offset] != '0') - pos_string=offset; - n/=10; - if (offset==0) - break; - offset--; - } - { - int size_display_string = 19-pos_string; - while (size_char > size_display_string) - { - size_char--; - printf(" "); - } - } - - printf("%s",&number[pos_string]); + /* to avoid compatibility problem , we do here the conversion */ + char number[21]; + int offset = 19; + int pos_string = 19; + number[20] = 0; + for (;;) { + number[offset] = (char)((n % 10) + '0'); + if (number[offset] != '0') pos_string = offset; + n /= 10; + if (offset == 0) break; + offset--; + } + { + int size_display_string = 19 - pos_string; + while (size_char > size_display_string) { + size_char--; + printf(" "); + } + } + + printf("%s", &number[pos_string]); } -int do_list(uf) - unzFile uf; +int do_list(uf) unzFile uf; { uLong i; unz_global_info64 gi; int err; - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); + err = unzGetGlobalInfo64(uf, &gi); + if (err != UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n", err); printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); - for (i=0;i0) - ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); + if (file_info.uncompressed_size > 0) ratio = (uLong)((file_info.compressed_size * 100) / file_info.uncompressed_size); /* display a '*' if the file is crypted */ - if ((file_info.flag & 1) != 0) - charCrypt='*'; - - if (file_info.compression_method==0) - string_method="Stored"; - else - if (file_info.compression_method==Z_DEFLATED) - { - uInt iLevel=(uInt)((file_info.flag & 0x6)/2); - if (iLevel==0) - string_method="Defl:N"; - else if (iLevel==1) - string_method="Defl:X"; - else if ((iLevel==2) || (iLevel==3)) - string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ - } - else - if (file_info.compression_method==Z_BZIP2ED) - { - string_method="BZip2 "; - } - else - string_method="Unkn. "; - - Display64BitsSize(file_info.uncompressed_size,7); - printf(" %6s%c",string_method,charCrypt); - Display64BitsSize(file_info.compressed_size,7); + if ((file_info.flag & 1) != 0) charCrypt = '*'; + + if (file_info.compression_method == 0) + string_method = "Stored"; + else if (file_info.compression_method == Z_DEFLATED) { + uInt iLevel = (uInt)((file_info.flag & 0x6) / 2); + if (iLevel == 0) + string_method = "Defl:N"; + else if (iLevel == 1) + string_method = "Defl:X"; + else if ((iLevel == 2) || (iLevel == 3)) + string_method = "Defl:F"; /* 2:fast , 3 : extra fast*/ + } else if (file_info.compression_method == Z_BZIP2ED) { + string_method = "BZip2 "; + } else + string_method = "Unkn. "; + + Display64BitsSize(file_info.uncompressed_size, 7); + printf(" %6s%c", string_method, charCrypt); + Display64BitsSize(file_info.compressed_size, 7); printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", - ratio, - (uLong)file_info.tmu_date.tm_mon + 1, - (uLong)file_info.tmu_date.tm_mday, - (uLong)file_info.tmu_date.tm_year % 100, - (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, - (uLong)file_info.crc,filename_inzip); - if ((i+1)='a') && (rep<='z')) - rep -= 0x20; - } - while ((rep!='Y') && (rep!='N') && (rep!='A')); + rep = answer[0]; + if ((rep >= 'a') && (rep <= 'z')) rep -= 0x20; + } while ((rep != 'Y') && (rep != 'N') && (rep != 'A')); } - if (rep == 'N') - skip = 1; + if (rep == 'N') skip = 1; - if (rep == 'A') - *popt_overwrite=1; + if (rep == 'A') *popt_overwrite = 1; } - if ((skip==0) && (err==UNZ_OK)) - { - fout=fopen64(write_filename,"wb"); + if ((skip == 0) && (err == UNZ_OK)) { + fout = fopen64(write_filename, "wb"); /* some zipfile don't contain directory alone before file */ - if ((fout==NULL) && ((*popt_extract_without_path)==0) && - (filename_withoutpath!=(char*)filename_inzip)) - { - char c=*(filename_withoutpath-1); - *(filename_withoutpath-1)='\0'; + if ((fout == NULL) && ((*popt_extract_without_path) == 0) && (filename_withoutpath != (char *)filename_inzip)) { + char c = *(filename_withoutpath - 1); + *(filename_withoutpath - 1) = '\0'; makedir(write_filename); - *(filename_withoutpath-1)=c; - fout=fopen64(write_filename,"wb"); + *(filename_withoutpath - 1) = c; + fout = fopen64(write_filename, "wb"); } - if (fout==NULL) - { - printf("error opening %s\n",write_filename); + if (fout == NULL) { + printf("error opening %s\n", write_filename); } } - if (fout!=NULL) - { - //printf(" extracting: %s\n",write_filename); + if (fout != NULL) { + // printf(" extracting: %s\n",write_filename); - do - { - err = unzReadCurrentFile(uf,buf,size_buf); - if (err<0) - { - printf("error %d with zipfile in unzReadCurrentFile\n",err); + do { + err = unzReadCurrentFile(uf, buf, size_buf); + if (err < 0) { + printf("error %d with zipfile in unzReadCurrentFile\n", err); break; } - if (err>0) - if (fwrite(buf,err,1,fout)!=1) - { + if (err > 0) + if (fwrite(buf, err, 1, fout) != 1) { printf("error in writing extracted file\n"); - err=UNZ_ERRNO; + err = UNZ_ERRNO; break; } - } - while (err>0); - if (fout) - fclose(fout); + } while (err > 0); + if (fout) fclose(fout); - if (err==0) - change_file_date(write_filename,file_info.dosDate, - file_info.tmu_date); + if (err == 0) change_file_date(write_filename, file_info.dosDate, file_info.tmu_date); } - if (err==UNZ_OK) - { - err = unzCloseCurrentFile (uf); - if (err!=UNZ_OK) - { - printf("error %d with zipfile in unzCloseCurrentFile\n",err); + if (err == UNZ_OK) { + err = unzCloseCurrentFile(uf); + if (err != UNZ_OK) { + printf("error %d with zipfile in unzCloseCurrentFile\n", err); } - } - else + } else unzCloseCurrentFile(uf); /* don't lose the error */ } @@ -494,34 +432,25 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password) return err; } - -int do_extract(uf,opt_extract_without_path,opt_overwrite,password) - unzFile uf; - int opt_extract_without_path; - int opt_overwrite; - const char* password; +int do_extract(uf, opt_extract_without_path, opt_overwrite, password) unzFile uf; +int opt_extract_without_path; +int opt_overwrite; +const char *password; { uLong i; unz_global_info64 gi; int err; - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); + err = unzGetGlobalInfo64(uf, &gi); + if (err != UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n", err); - for (i=0;i -#include -#include -#include #include "main.h" +#include "util.h" #include #include -#include "util.h" +#include +#include +#include +#include #include #define BUFSIZE 4096 #define PATHLEN 1024 #ifdef _MSC_VER -#define LIB_EXT ".dll" -#define LIB_PATH "%s%s%s.dll" +#define LIB_EXT ".dll" +#define LIB_PATH "%s%s%s.dll" #define FMU_ROOT_DIR "tmp-fmus\\" #define XML_FILE "\\modelDescription.xml" #define BIN_WIN "\\binaries\\winxx\\" @@ -52,11 +52,11 @@ #define OperSys 1 #endif #elif __linux__ -#include -#include #include -#define LIB_EXT ".so" -#define LIB_PATH "%s%s%s.so" +#include +#include +#define LIB_EXT ".so" +#define LIB_PATH "%s%s%s.so" #define FMU_ROOT_DIR "tmp-fmus/" #define XML_FILE "/modelDescription.xml" #define BIN_LIN "/binaries/linuxxx/" @@ -65,15 +65,15 @@ //#define OperSys 3 //#if defined(__LP32__) //#define OperSys 3 -# if defined(__LP64__) || defined(__x86_64__) || defined(__ia64__) || defined(__amd64__) || defined(__ppc64__) +#if defined(__LP64__) || defined(__x86_64__) || defined(__ia64__) || defined(__amd64__) || defined(__ppc64__) #define OperSys 4 #else #define OperSys 3 #endif #elif __APPLE__ #include -#define LIB_EXT ".dylib" -#define LIB_PATH "%s%s%s.dylib" +#define LIB_EXT ".dylib" +#define LIB_PATH "%s%s%s.dylib" #define FMU_ROOT_DIR "tmp-fmus/" #define XML_FILE "/modelDescription.xml" #define BIN_MAC "/binaries/darwinxx/" @@ -95,7 +95,7 @@ FMU **fmuInstances; fmiComponent c; -FMU* _c; +FMU *_c; /////////////////////////////////////////////////////////////////////////////// /// This function checks the operating system and returns an error message @@ -103,13 +103,14 @@ FMU* _c; /// ///\param name Error message /////////////////////////////////////////////////////////////////////////////// -fmiInteger checkOperatingSystem(char* errorMessage){ +fmiInteger checkOperatingSystem(char *errorMessage) +{ #ifdef __APPLE__ - char* msg = "FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."; - strncpy(errorMessage, msg, strlen(msg)); - return -1; + char *msg = "FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."; + strncpy(errorMessage, msg, strlen(msg)); + return -1; #endif - return 0; + return 0; } #if defined _MSC_VER || defined __linux__ @@ -129,13 +130,14 @@ static int fmuLocDecoun = 0; ///\return The index of matched string in the \c array[]. /// Otherwise, return -1 to indicate error /////////////////////////////////////////////////////////////////////////////// -static int checkName2(const char* name, const char* kind, const char* array[], int n){ - int i; - for (i=0; idllHandle, name); + fp = GetProcAddress(fmu->dllHandle, name); #else - fp = dlsym(fmu->dllHandle, name); + fp = dlsym(fmu->dllHandle, name); #endif - if (!fp) { - printf ("Error: Function %s not found in FMI functions library.\n", name); - } - return fp; + if (!fp) { + printf("Error: Function %s not found in FMI functions library.\n", name); + } + return fp; } - //////////////////////////////////////////////////////////////////////////////////// /// Create a list of pointer to FMUs /// ///\param s The Pointer to FMU. //////////////////////////////////////////////////////////////////////////////////// -static void addfmuInstances(FMU* s){ - FMU **temp; - if(fmuLocCoun == arrsize){ - temp = (FMU**)malloc(sizeof(FMU*) * (DELTA + arrsize)); - arrsize += DELTA; - memcpy(temp, fmuInstances, sizeof(FMU*) * fmuLocCoun); - free(fmuInstances); - fmuInstances = temp; - } - fmuInstances[fmuLocCoun++] = s; +static void addfmuInstances(FMU *s) +{ + FMU **temp; + if (fmuLocCoun == arrsize) { + temp = (FMU **)malloc(sizeof(FMU *) * (DELTA + arrsize)); + arrsize += DELTA; + memcpy(temp, fmuInstances, sizeof(FMU *) * fmuLocCoun); + free(fmuInstances); + fmuInstances = temp; + } + fmuInstances[fmuLocCoun++] = s; } - - /////////////////////////////////////////////////////////////////////////////// /// Load the given dll and set function pointers in fmu. /// It changes the names of the standard FMI functions by adding @@ -202,109 +204,116 @@ static void addfmuInstances(FMU* s){ ///\param fmu FMU instance ///\return 0 if there is no error occurred /////////////////////////////////////////////////////////////////////////////// -static int loadLib(const char* libPath, const char* modelID, FMU *fmu) { +static int loadLib(const char *libPath, const char *modelID, FMU *fmu) +{ #ifdef _MSC_VER - HINSTANCE h; + HINSTANCE h; #else - void *h; + void *h; #endif #ifdef _MSC_VER - h = LoadLibrary(libPath); - if (h == NULL) { - printf("Error: unable to load FMI functions library.\n"); - return -1; - } - if (!h) { - printf("Error: unable to load FMI functions library.\n"); - return -1; - } + h = LoadLibrary(libPath); + if (h == NULL) { + printf("Error: unable to load FMI functions library.\n"); + return -1; + } + if (!h) { + printf("Error: unable to load FMI functions library.\n"); + return -1; + } #else - h = dlopen(libPath, RTLD_LAZY); - if (h == NULL) { - printf("Error: unable to load FMI functions library.\n"); - return -1; - } - if (!h) { - printf("Error: unable to load FMI functions library.\n"); - return -1; - } + h = dlopen(libPath, RTLD_LAZY); + if (h == NULL) { + printf("Error: unable to load FMI functions library.\n"); + return -1; + } + if (!h) { + printf("Error: unable to load FMI functions library.\n"); + return -1; + } #endif - fmu->dllHandle = h; - fmu->getVersion = (fGetVersion)getAdr(fmu, modelID, "fmiGetVersion"); - if (!(fmu->getVersion)) { - return -1; - } - fmu->instantiateSlave = (fInstantiateSlave)getAdr(fmu, modelID, "fmiInstantiateSlave"); - if (!(fmu->instantiateSlave)) { - return -1; - } - fmu->freeSlaveInstance = (fFreeSlaveInstance)getAdr(fmu, modelID, "fmiFreeSlaveInstance"); - if (!(fmu->freeSlaveInstance)) { - return -1; - } - fmu->resetSlaveInstance = (fResetSlaveInstance)getAdr(fmu, modelID, "fmiResetSlave"); - if (!(fmu->resetSlaveInstance)) { - return -1; - } - fmu->setDebugLogging = (fSetDebugLogging)getAdr(fmu, modelID, "fmiSetDebugLogging"); - if (!(fmu->setDebugLogging)) { - return -1; - } - fmu->setReal = (fSetReal) getAdr(fmu, modelID, "fmiSetReal"); - if (!(fmu->setReal)) { - return -1; - } - fmu->setInteger = (fSetInteger)getAdr(fmu, modelID, "fmiSetInteger"); - if (!(fmu->setInteger)) { - return -1; - } - fmu->setBoolean = (fSetBoolean)getAdr(fmu, modelID, "fmiSetBoolean"); - if (!(fmu->setBoolean)) { - return -1; - } - fmu->setString = (fSetString)getAdr(fmu, modelID, "fmiSetString"); - if (!(fmu->setString)) { - return -1; - } - fmu->initializeSlave = (fInitializeSlave)getAdr(fmu, modelID, "fmiInitializeSlave"); - if (!(fmu->initializeSlave)) { - return -1; - } - fmu->getReal = (fGetReal)getAdr(fmu, modelID, "fmiGetReal"); - if (!(fmu->getReal)) { - return -1; - } - fmu->getInteger = (fGetInteger)getAdr(fmu, modelID, "fmiGetInteger"); - if (!(fmu->getInteger)) { - return -1; - } - fmu->getBoolean = (fGetBoolean)getAdr(fmu, modelID, "fmiGetBoolean"); - if (!(fmu->getBoolean)) { - return -1; - } - fmu->getString = (fGetString)getAdr(fmu, modelID, "fmiGetString"); - if (!(fmu->getString)) { - return -1; - } - fmu->doStep = (fDoStep)getAdr(fmu, modelID, "fmiDoStep"); - if (!(fmu->doStep)) { - return -1; - } - return 0; //success - + fmu->dllHandle = h; + fmu->getVersion = (fGetVersion)getAdr(fmu, modelID, "fmiGetVersion"); + if (!(fmu->getVersion)) { + return -1; + } + fmu->instantiateSlave = (fInstantiateSlave)getAdr(fmu, modelID, "fmiInstantiateSlave"); + if (!(fmu->instantiateSlave)) { + return -1; + } + fmu->freeSlaveInstance = (fFreeSlaveInstance)getAdr(fmu, modelID, "fmiFreeSlaveInstance"); + if (!(fmu->freeSlaveInstance)) { + return -1; + } + fmu->resetSlaveInstance = (fResetSlaveInstance)getAdr(fmu, modelID, "fmiResetSlave"); + if (!(fmu->resetSlaveInstance)) { + return -1; + } + fmu->setDebugLogging = (fSetDebugLogging)getAdr(fmu, modelID, "fmiSetDebugLogging"); + if (!(fmu->setDebugLogging)) { + return -1; + } + fmu->setReal = (fSetReal)getAdr(fmu, modelID, "fmiSetReal"); + if (!(fmu->setReal)) { + return -1; + } + fmu->setInteger = (fSetInteger)getAdr(fmu, modelID, "fmiSetInteger"); + if (!(fmu->setInteger)) { + return -1; + } + fmu->setBoolean = (fSetBoolean)getAdr(fmu, modelID, "fmiSetBoolean"); + if (!(fmu->setBoolean)) { + return -1; + } + fmu->setString = (fSetString)getAdr(fmu, modelID, "fmiSetString"); + if (!(fmu->setString)) { + return -1; + } + fmu->initializeSlave = (fInitializeSlave)getAdr(fmu, modelID, "fmiInitializeSlave"); + if (!(fmu->initializeSlave)) { + return -1; + } + fmu->getReal = (fGetReal)getAdr(fmu, modelID, "fmiGetReal"); + if (!(fmu->getReal)) { + return -1; + } + fmu->getInteger = (fGetInteger)getAdr(fmu, modelID, "fmiGetInteger"); + if (!(fmu->getInteger)) { + return -1; + } + fmu->getBoolean = (fGetBoolean)getAdr(fmu, modelID, "fmiGetBoolean"); + if (!(fmu->getBoolean)) { + return -1; + } + fmu->getString = (fGetString)getAdr(fmu, modelID, "fmiGetString"); + if (!(fmu->getString)) { + return -1; + } + fmu->doStep = (fDoStep)getAdr(fmu, modelID, "fmiDoStep"); + if (!(fmu->doStep)) { + return -1; + } + return 0; // success } -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 fmiPending: return "pending"; - default: return "?"; - } +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 fmiPending: + return "pending"; + default: + return "?"; + } } #define MAX_MSG_SIZE 1000 @@ -316,23 +325,31 @@ static const char* fmiStatusToString(fmiStatus status){ ///\param vr FMI value reference ///\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; - } - for (i=0; vars[i]; i++) { - ScalarVariable* sv = vars[i]; - if (vr==getValueReference(sv) && tp==sv->typeSpec->type) - return sv; - } - return NULL; +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; + } + for (i = 0; vars[i]; i++) { + ScalarVariable *sv = vars[i]; + if (vr == getValueReference(sv) && tp == sv->typeSpec->type) return sv; + } + return NULL; } /////////////////////////////////////////////////////////////////////////////// @@ -345,54 +362,52 @@ static ScalarVariable* getSV(FMU* fmu, char type, fmiValueReference vr) { ///\param nBuffer The size of the buffer ///\param fmu FMU The FMU instance /////////////////////////////////////////////////////////////////////////////// -static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU* fmu){ - size_t i=0; // position in msg - size_t k=0; // position in buffer - size_t n; - char c = msg[i]; - while (c!='\0' && k < nBuffer) { - if (c!='#') { - 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", (int)i+2, msg); - buffer[k++]='#'; - break; - } - } - } - } // while - buffer[k] = '\0'; +static void replaceRefsInMessage(const char *msg, char *buffer, int nBuffer, FMU *fmu) +{ + size_t i = 0; // position in msg + size_t k = 0; // position in buffer + size_t n; + char c = msg[i]; + while (c != '\0' && k < nBuffer) { + if (c != '#') { + 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", (int)i + 2, msg); + buffer[k++] = '#'; + break; + } + } + } + } // while + buffer[k] = '\0'; } /////////////////////////////////////////////////////////////////////////////// @@ -404,32 +419,32 @@ static void replaceRefsInMessage(const char* msg, char* buffer, int nBuffer, FMU ///\param category FMI string ///\param message Message to be recorded /////////////////////////////////////////////////////////////////////////////// -static void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, - fmiString category, fmiString message, ...) { - char msg[MAX_MSG_SIZE]; - char* copy; - va_list argp; - FMU fmu; - - // Replace C format strings - va_start(argp, message); - vsprintf(msg, message, 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); +static void fmuLogger(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...) +{ + char msg[MAX_MSG_SIZE]; + char *copy; + va_list argp; + FMU fmu; + + // Replace C format strings + va_start(argp, message); + vsprintf(msg, message, 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); } - -static int error(const char* message){ - printf("%s\n", message); - return -1; +static int error(const char *message) +{ + printf("%s\n", message); + return -1; } //////////////////////////////////////////////////////////////// @@ -441,38 +456,38 @@ static int error(const char* message){ ///\param sizemodelID Size of FMU modelID ///\param fmiVersionNumber FMI version number //////////////////////////////////////////////////////////////// -fmiInteger getfmiEPlusVersion(char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index){ - - char *trimfmuWorkingFolder; - fmiString verID; - //char* trimmodelID; - char* err_msg = "Check FMU binaries folder and see whether libraries " - "exist for the system architecture of the EnergyPlus version used. Also check whether the FMU has " - "been exported for Co-Simulation. FMU for Model Exchange is not supported yet."; - - // allocate memory for the FMU-working folder trimmed - trimfmuWorkingFolder = (char*)calloc(sizeof(char),*sizefmuWorkingFolder + 1); - //write fmuWorkingFolder withouth blanks - strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); - - // get index value - _c->index = *index; - - //load lib by specifying path to the binaries - if (loadLib(trimfmuWorkingFolder, fmuInstances[_c->index]->modelID, fmuInstances[_c->index])) { - strncpy(fmiVersionNumber, err_msg, strlen(err_msg)); - return -1; - } - - // free trimmed working folder - free (trimfmuWorkingFolder); - - // get the modelID of the FMU - verID = fmuInstances[_c->index]->getVersion(); - strncpy(fmiVersionNumber, verID, strlen (verID)+ 1); - - return 0; +fmiInteger getfmiEPlusVersion(char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index) +{ + + char *trimfmuWorkingFolder; + fmiString verID; + // char* trimmodelID; + char *err_msg = "Check FMU binaries folder and see whether libraries " + "exist for the system architecture of the EnergyPlus version used. Also check whether the FMU has " + "been exported for Co-Simulation. FMU for Model Exchange is not supported yet."; + + // allocate memory for the FMU-working folder trimmed + trimfmuWorkingFolder = (char *)calloc(*sizefmuWorkingFolder + 1, sizeof(char)); + // write fmuWorkingFolder withouth blanks + strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); + + // get index value + _c->index = *index; + + // load lib by specifying path to the binaries + if (loadLib(trimfmuWorkingFolder, fmuInstances[_c->index]->modelID, fmuInstances[_c->index])) { + memcpy(fmiVersionNumber, err_msg, strlen(err_msg)); + return -1; + } + + // free trimmed working folder + free(trimfmuWorkingFolder); + + // get the modelID of the FMU + verID = fmuInstances[_c->index]->getVersion(); + memcpy(fmiVersionNumber, verID, strlen(verID) + 1); + + return 0; } //////////////////////////////////////////////////////////////// @@ -488,63 +503,71 @@ fmiInteger getfmiEPlusVersion(char* fmuWorkingFolder, ///\param loggingOn Flag to enable or disable debug ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiComponent fmiEPlusInstantiateSlave(char* fmuResFolder, - fmiInteger *sizefmuResFolder, - fmiReal *timeOut, fmiInteger *visible, - fmiInteger *interactive, - fmiInteger *loggingOn, - fmiInteger *index) { - - char* trimfmuResFolder; - - fmiBoolean visiBoolean; - fmiBoolean interactBoolean; - fmiBoolean loggOnBoolean; - fmiComponent fmuInstance; - - // define callbacks functions - fmiCallbackFunctions callbacks; - callbacks.allocateMemory = calloc; - callbacks.freeMemory = free; - callbacks.logger = fmuLogger; - - // allocate memory for fmu resources folder - trimfmuResFolder = (char*)calloc(sizeof(char),*sizefmuResFolder + 1); - - // write fmuResFolder without blanks - strncpy(trimfmuResFolder, fmuResFolder, *sizefmuResFolder); - - // get index value - _c->index = *index; - - // map input to fmiBoolean variables - if (*visible == 0) - visiBoolean = fmiFalse; - else - visiBoolean = fmiTrue; - - if (*interactive == 0) - interactBoolean = fmiFalse; - else - interactBoolean = fmiTrue; - - if (*loggingOn == 0) - loggOnBoolean = fmiFalse; - else - loggOnBoolean = fmiTrue; - - // instantiate FMU - fmuInstance = fmuInstances[_c->index]->instantiateSlave(fmuInstances[_c->index]->instanceName, - fmuInstances[_c->index]->modelGUID, trimfmuResFolder, "", *timeOut, visiBoolean, - interactBoolean, callbacks, loggOnBoolean); - if (!fmuInstance) { - printf("Error: failed to instantiate slave in fmiEPlusInstantiateSlave.\n"); - return NULL; - } - - // free trimfmuResFolder - free (trimfmuResFolder); - return fmuInstance; +fmiComponent fmiEPlusInstantiateSlave(char *fmuResFolder, + fmiInteger *sizefmuResFolder, + fmiReal *timeOut, + fmiInteger *visible, + fmiInteger *interactive, + fmiInteger *loggingOn, + fmiInteger *index) +{ + + char *trimfmuResFolder; + + fmiBoolean visiBoolean; + fmiBoolean interactBoolean; + fmiBoolean loggOnBoolean; + fmiComponent fmuInstance; + + // define callbacks functions + fmiCallbackFunctions callbacks; + callbacks.allocateMemory = calloc; + callbacks.freeMemory = free; + callbacks.logger = fmuLogger; + + // allocate memory for fmu resources folder + trimfmuResFolder = (char *)calloc(*sizefmuResFolder + 1, sizeof(char)); + + // write fmuResFolder without blanks + strncpy(trimfmuResFolder, fmuResFolder, *sizefmuResFolder); + + // get index value + _c->index = *index; + + // map input to fmiBoolean variables + if (*visible == 0) + visiBoolean = fmiFalse; + else + visiBoolean = fmiTrue; + + if (*interactive == 0) + interactBoolean = fmiFalse; + else + interactBoolean = fmiTrue; + + if (*loggingOn == 0) + loggOnBoolean = fmiFalse; + else + loggOnBoolean = fmiTrue; + + // instantiate FMU + fmuInstance = fmuInstances[_c->index]->instantiateSlave(fmuInstances[_c->index]->instanceName, + fmuInstances[_c->index]->modelGUID, + trimfmuResFolder, + "", + *timeOut, + visiBoolean, + interactBoolean, + callbacks, + loggOnBoolean); + if (!fmuInstance) { + printf("Error: failed to instantiate slave in fmiEPlusInstantiateSlave.\n"); + return NULL; + } + + // free trimfmuResFolder + free(trimfmuResFolder); + return fmuInstance; } //////////////////////////////////////////////////////////////// @@ -559,28 +582,28 @@ fmiComponent fmiEPlusInstantiateSlave(char* fmuResFolder, ///\param tStop Simulation endtime ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, - fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index) { - - fmiStatus fmiFlag; - fmiBoolean newStepBoolean; - - //map the newStep to fmiBoolean value - if (*newStep == 0) - newStepBoolean = fmiFalse; - else - newStepBoolean = fmiTrue; - - // get index value - _c->index = *index; - - //initialize fmu; - fmiFlag = fmuInstances[_c->index]->initializeSlave(*fmuInstance, *tStart, newStepBoolean, *tStop); - if (fmiFlag > fmiWarning) { - printf("Error: failed to initialize slave in fmiEPlusInitializeSlave!\n"); - return fmiError; - } - return fmiFlag; +fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index) +{ + + fmiStatus fmiFlag; + fmiBoolean newStepBoolean; + + // map the newStep to fmiBoolean value + if (*newStep == 0) + newStepBoolean = fmiFalse; + else + newStepBoolean = fmiTrue; + + // get index value + _c->index = *index; + + // initialize fmu; + fmiFlag = fmuInstances[_c->index]->initializeSlave(*fmuInstance, *tStart, newStepBoolean, *tStop); + if (fmiFlag > fmiWarning) { + printf("Error: failed to initialize slave in fmiEPlusInitializeSlave!\n"); + return fmiError; + } + return fmiFlag; } //////////////////////////////////////////////////////////////// @@ -594,21 +617,21 @@ fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef [], - fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index) { +fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index) +{ - fmiStatus fmiFlag; + fmiStatus fmiFlag; - // get index value - _c->index = *index; + // get index value + _c->index = *index; - fmiFlag = fmuInstances[_c->index]->getReal(*fmuInstance, valRef, *numOutputs, outValue); - if (fmiFlag > fmiWarning) { - printf("Error: failed to get all outputs in fmiEPlusGetReal.\n"); - return fmiError; - } + fmiFlag = fmuInstances[_c->index]->getReal(*fmuInstance, valRef, *numOutputs, outValue); + if (fmiFlag > fmiWarning) { + printf("Error: failed to get all outputs in fmiEPlusGetReal.\n"); + return fmiError; + } - return fmiFlag; + return fmiFlag; } //////////////////////////////////////////////////////////////// @@ -623,20 +646,20 @@ fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference val ///\param numOutputs Number of FMU inputs ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], - fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index) { +fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index) +{ - fmiStatus fmiFlag; + fmiStatus fmiFlag; - // get index value - _c->index = *index; + // get index value + _c->index = *index; - fmiFlag = fmuInstances[_c->index]->setReal(*fmuInstance, valRef, *numInputs, inpVal); - if (fmiFlag > fmiWarning) { - printf("Error: failed to set all inputs in fmiEPlusSetReal.\n"); - return fmiError; - } - return fmiFlag; + fmiFlag = fmuInstances[_c->index]->setReal(*fmuInstance, valRef, *numInputs, inpVal); + if (fmiFlag > fmiWarning) { + printf("Error: failed to set all inputs in fmiEPlusSetReal.\n"); + return fmiError; + } + return fmiFlag; } //////////////////////////////////////////////////////////////// @@ -650,30 +673,29 @@ fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference val ///\param commStepSize Size of communication timestep ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, - fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index) { - - fmiBoolean newStepBoolean; - fmiStatus fmiFlag; - - // map the newStep to the fmiBoolean value - if (*newStep == 0) - newStepBoolean = fmiFalse; - else - newStepBoolean = fmiTrue; - - // get index value - _c->index = *index; - - fmiFlag = fmuInstances[_c->index]->doStep(*fmuInstance, *curCommPoint, *commStepSize, newStepBoolean); - if (fmiFlag > fmiWarning) { - printf("Error: failed to do Step in fmiEPlusDoStep.\n"); - return fmiError; - } - return fmiFlag; +fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index) +{ + + fmiBoolean newStepBoolean; + fmiStatus fmiFlag; + + // map the newStep to the fmiBoolean value + if (*newStep == 0) + newStepBoolean = fmiFalse; + else + newStepBoolean = fmiTrue; + + // get index value + _c->index = *index; + + fmiFlag = fmuInstances[_c->index]->doStep(*fmuInstance, *curCommPoint, *commStepSize, newStepBoolean); + if (fmiFlag > fmiWarning) { + printf("Error: failed to do Step in fmiEPlusDoStep.\n"); + return fmiError; + } + return fmiFlag; } - //////////////////////////////////////////////////////////////// /// This method is an interface to the function in Fortran /// needed to free FMU. It returns an integer @@ -684,25 +706,25 @@ fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, ///\param fmiEndSimulation Parameter to indicate end of simulation //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation) { - - // get index value - _c->index = *index; - - // free slave in fmu - // Freeing doesn't work with Dymola. - fmuInstances[_c->index]->freeSlaveInstance(*fmuInstance); - if (*fmiEndSimulation == 1 && fmuInstances != NULL){ - if (fmuLocDecoun == fmuLocCoun){ - // Deallocate memory when simulation terminates - free(fmuInstances); - } - fmuLocDecoun++; - } - return 0; +fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation) +{ + + // get index value + _c->index = *index; + + // free slave in fmu + // Freeing doesn't work with Dymola. + fmuInstances[_c->index]->freeSlaveInstance(*fmuInstance); + if (*fmiEndSimulation == 1 && fmuInstances != NULL) { + if (fmuLocDecoun == fmuLocCoun) { + // Deallocate memory when simulation terminates + free(fmuInstances); + } + fmuLocDecoun++; + } + return 0; } - //////////////////////////////////////////////////////////////// /// This method is an interface to the function in Fortran /// needed to reset FMU. It returns an integer @@ -711,20 +733,21 @@ fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInt ///\param fmuInstance FMU instance ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index) { +fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index) +{ - fmiStatus fmiFlag; + fmiStatus fmiFlag; - // get index value - _c->index = *index; + // get index value + _c->index = *index; - // reset slave in fmu - fmiFlag = fmuInstances[_c->index]->resetSlaveInstance (*fmuInstance); - if (fmiFlag > fmiWarning) { - printf("Error: failed to reset FMU instance in fmiEPlusResetSlave.\n"); - return fmiWarning; - } - return fmiFlag; + // reset slave in fmu + fmiFlag = fmuInstances[_c->index]->resetSlaveInstance(*fmuInstance); + if (fmiFlag > fmiWarning) { + printf("Error: failed to reset FMU instance in fmiEPlusResetSlave.\n"); + return fmiWarning; + } + return fmiFlag; } //////////////////////////////////////////////////////////////// @@ -736,47 +759,43 @@ fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index) { ///\param sizeVariableName Size of FMU-variable name ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiValueReference getValueReferenceByNameFMUInputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index) { - - char *trimVariableName; - fmiValueReference valueRef; - - // allocate memory for the FMU-variable trimmed - trimVariableName = (char*)calloc(sizeof(char),*sizeVariableName + 1); - - // write FMU-variable withouth blanks - strncpy(trimVariableName, variableName, *sizeVariableName); - - // get index value - _c->index = *index; - - // check whether the variable exists in the FMU - if (getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)== NULL){ - printf("Error: get variable by name failed in fmigetValueReferenceByName. " - "Please check input variables and modelDescription file again."); - return -1; - } - else - { - valueRef = getValueReference(getVariableByName(fmuInstances[_c->index]->modelDescription, - trimVariableName)); - if (!valueRef) { - printf("Error: could not get value by reference in fmigetValueReferenceByName. " - "Please check input variables and modelDescription file again."); - return -999; - } - if (getCausality(getVariableByName(fmuInstances[_c->index]->modelDescription, - trimVariableName)) != enu_input) { - printf("Error: This is not an FMU input variable. " - "Please check input variables and modelDescription file again."); - return -1; - } - } - - // deallocate memory FMU-variable name trimmed - free(trimVariableName); - return valueRef; +fmiValueReference getValueReferenceByNameFMUInputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index) +{ + + char *trimVariableName; + fmiValueReference valueRef; + + // allocate memory for the FMU-variable trimmed + trimVariableName = (char *)calloc(*sizeVariableName + 1, sizeof(char)); + + // write FMU-variable withouth blanks + strncpy(trimVariableName, variableName, *sizeVariableName); + + // get index value + _c->index = *index; + + // check whether the variable exists in the FMU + if (getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName) == NULL) { + printf("Error: get variable by name failed in fmigetValueReferenceByName. " + "Please check input variables and modelDescription file again."); + return -1; + } else { + valueRef = getValueReference(getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)); + if (!valueRef) { + printf("Error: could not get value by reference in fmigetValueReferenceByName. " + "Please check input variables and modelDescription file again."); + return -999; + } + if (getCausality(getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)) != enu_input) { + printf("Error: This is not an FMU input variable. " + "Please check input variables and modelDescription file again."); + return -1; + } + } + + // deallocate memory FMU-variable name trimmed + free(trimVariableName); + return valueRef; } //////////////////////////////////////////////////////////////// @@ -788,46 +807,42 @@ fmiValueReference getValueReferenceByNameFMUInputVariables(char* variableName, ///\param sizeVariableName Size of FMU-variable name ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiValueReference getValueReferenceByNameFMUOutputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index) { - - char *trimVariableName; - fmiValueReference valueRef; - - // allocate memory for the FMU-variable trimmed - trimVariableName = (char*)calloc(sizeof(char),*sizeVariableName + 1); - - //write FMU-variable withouth blanks - strncpy(trimVariableName, variableName, *sizeVariableName); - - // get index value - _c->index = *index; - - if (getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)== NULL){ - printf("Error: get variable by name failed in fmigetValueReferenceByName. " - "Please check output variables and modelDescription file again."); - return -1; - } - else - { - valueRef = getValueReference(getVariableByName(fmuInstances[_c->index]->modelDescription, - trimVariableName)); - if (!valueRef) { - printf("Error: could not get value by reference in fmigetValueReferenceByName. " - "Please check output variables and modelDescription file again."); - return -999; - } - if (getCausality(getVariableByName(fmuInstances[_c->index]->modelDescription, - trimVariableName)) != enu_output) { - printf("Error: This is not an FMU output variable. " - "Please check output variables and modelDescription file again."); - return -1; - } - } - - // deallocate memory FMU-variable name trimmed - free(trimVariableName); - return valueRef; +fmiValueReference getValueReferenceByNameFMUOutputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index) +{ + + char *trimVariableName; + fmiValueReference valueRef; + + // allocate memory for the FMU-variable trimmed + trimVariableName = (char *)calloc(*sizeVariableName + 1, sizeof(char)); + + // write FMU-variable withouth blanks + strncpy(trimVariableName, variableName, *sizeVariableName); + + // get index value + _c->index = *index; + + if (getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName) == NULL) { + printf("Error: get variable by name failed in fmigetValueReferenceByName. " + "Please check output variables and modelDescription file again."); + return -1; + } else { + valueRef = getValueReference(getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)); + if (!valueRef) { + printf("Error: could not get value by reference in fmigetValueReferenceByName. " + "Please check output variables and modelDescription file again."); + return -999; + } + if (getCausality(getVariableByName(fmuInstances[_c->index]->modelDescription, trimVariableName)) != enu_output) { + printf("Error: This is not an FMU output variable. " + "Please check output variables and modelDescription file again."); + return -1; + } + } + + // deallocate memory FMU-variable name trimmed + free(trimVariableName); + return valueRef; } //////////////////////////////////////////////////////////////// @@ -841,28 +856,28 @@ fmiValueReference getValueReferenceByNameFMUOutputVariables(char* variableName, ///\param sizefmuWorkingFolder Size of FMU working folder //////////////////////////////////////////////////////////////// -fmiInteger addFMURootFolderName(char* fmuOutputWorkingFolder, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder) { - char *trimfmuWorkingFolder; - char * trimfmuWorkingFolderWithRoot; +fmiInteger addFMURootFolderName(char *fmuOutputWorkingFolder, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder) +{ + char *trimfmuWorkingFolder; + char *trimfmuWorkingFolderWithRoot; - // allocate memory for the FMU-working folder trimmed - trimfmuWorkingFolder = (char*)calloc(sizeof(char),*sizefmuWorkingFolder + 1); + // allocate memory for the FMU-working folder trimmed + trimfmuWorkingFolder = (char *)calloc(*sizefmuWorkingFolder + 1, sizeof(char)); - //write fmuWorkingFolder withouth blanks - strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); + // write fmuWorkingFolder withouth blanks + strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); - trimfmuWorkingFolderWithRoot = (char*)calloc(sizeof(char),*sizefmuWorkingFolder + strlen (FMU_ROOT_DIR) + 1); - sprintf(trimfmuWorkingFolderWithRoot, "%s%s", trimfmuWorkingFolder, FMU_ROOT_DIR); + trimfmuWorkingFolderWithRoot = (char *)calloc(*sizefmuWorkingFolder + strlen(FMU_ROOT_DIR) + 1, sizeof(char)); + sprintf(trimfmuWorkingFolderWithRoot, "%s%s", trimfmuWorkingFolder, FMU_ROOT_DIR); - //write fmuOutputWorkingFolder - strncpy(fmuOutputWorkingFolder, trimfmuWorkingFolderWithRoot, *sizefmuWorkingFolder + strlen (FMU_ROOT_DIR) + 1); + // write fmuOutputWorkingFolder + strncpy(fmuOutputWorkingFolder, trimfmuWorkingFolderWithRoot, *sizefmuWorkingFolder + strlen(FMU_ROOT_DIR) + 1); - // deallocate memory FMU-working folder trimmed - free(trimfmuWorkingFolder); - // deallocate memory FMU-working folder with root - free(trimfmuWorkingFolderWithRoot); - return 0; + // deallocate memory FMU-working folder trimmed + free(trimfmuWorkingFolder); + // deallocate memory FMU-working folder with root + free(trimfmuWorkingFolderWithRoot); + return 0; } //////////////////////////////////////////////////////////////// @@ -878,136 +893,128 @@ fmiInteger addFMURootFolderName(char* fmuOutputWorkingFolder, ///\param index Index of FMU //////////////////////////////////////////////////////////////// -fmiInteger addLibPathCurrentWorkingFolder( - char* trimfmuOutputWorkingFolder_wLiB, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, - fmiInteger *index) { - char *trimfmuWorkingFolder; - char * librPath_w32; - char * librPath_w64; - struct stat st; - fmiInteger len_LibPath; - fmiBoolean bRes_w32; - fmiBoolean bRes_w64; +fmiInteger +addLibPathCurrentWorkingFolder(char *trimfmuOutputWorkingFolder_wLiB, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *index) +{ + char *trimfmuWorkingFolder; + char *librPath_w32; + char *librPath_w64; + struct stat st; + fmiInteger len_LibPath; + fmiBoolean bRes_w32; + fmiBoolean bRes_w64; #if __linux__ - char * librPath_l32; - char * librPath_l64; - fmiBoolean bRes_l32; - fmiBoolean bRes_l64; + char *librPath_l32; + char *librPath_l64; + fmiBoolean bRes_l32; + fmiBoolean bRes_l64; #endif - // allocate memory for the FMU-working folder trimmed - trimfmuWorkingFolder = (char*)calloc(sizeof(char),*sizefmuWorkingFolder + 1); + // allocate memory for the FMU-working folder trimmed + trimfmuWorkingFolder = (char *)calloc(*sizefmuWorkingFolder + 1, sizeof(char)); - //write fmuWorkingFolder withouth blanks - strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); + // write fmuWorkingFolder withouth blanks + memcpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); - // get index value - _c->index = *index; + // get index value + _c->index = *index; #ifdef _MSC_VER - len_LibPath = (fmiInteger)(strlen(trimfmuWorkingFolder) + strlen(BIN_WIN) + strlen (fmuInstances[_c->index]->modelID) - + strlen (LIB_EXT)); - librPath_w32 = (char*)calloc(sizeof(char), len_LibPath + 1); - - // write the path to the binaries for Windows 32 bit - sprintf(librPath_w32, "%s%s%s%s", trimfmuWorkingFolder, BIN_WIN32, fmuInstances[_c->index]->modelID, LIB_EXT); - // check whether the dlls for Windows 32 bit exist in the binaries folder - bRes_w32 = (stat(librPath_w32, &st) == 0); - - // write the path to the binaries for Windows 64 bit - librPath_w64 = (char*)calloc(sizeof(char), len_LibPath + 1); - sprintf(librPath_w64, "%s%s%s%s", trimfmuWorkingFolder, BIN_WIN64, fmuInstances[_c->index]->modelID, LIB_EXT); - // check whether the dlls for Windows 32 bit exist in the binaries folder - bRes_w64 = (stat(librPath_w64, &st) == 0); - - // check whether we have folders for Windows 32 and Windows 64 bit - if (bRes_w32 && bRes_w64) { - if (OperSys == 1){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_w32, strlen(librPath_w32)); - } - else - { - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_w64, strlen(librPath_w64)); - } - } - // check whether we just have folder for Windows 32 bit - else if (bRes_w32 && !bRes_w64){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_w32, strlen(librPath_w32)); - } - // check whether we just have folder for Windows 64 bit - else if (!bRes_w32 && bRes_w64){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_w64, strlen(librPath_w64)); - } - else { - printf("Error: FMU does not contain binaries folder for this operating system."); - free(trimfmuWorkingFolder); - free(librPath_w32); - free(librPath_w64); - return -1; - } + len_LibPath = (fmiInteger)(strlen(trimfmuWorkingFolder) + strlen(BIN_WIN) + strlen(fmuInstances[_c->index]->modelID) + strlen(LIB_EXT)); + librPath_w32 = (char *)calloc(len_LibPath + 1, sizeof(char)); + + // write the path to the binaries for Windows 32 bit + sprintf(librPath_w32, "%s%s%s%s", trimfmuWorkingFolder, BIN_WIN32, fmuInstances[_c->index]->modelID, LIB_EXT); + // check whether the dlls for Windows 32 bit exist in the binaries folder + bRes_w32 = (stat(librPath_w32, &st) == 0); + + // write the path to the binaries for Windows 64 bit + librPath_w64 = (char *)calloc(len_LibPath + 1, sizeof(char)); + sprintf(librPath_w64, "%s%s%s%s", trimfmuWorkingFolder, BIN_WIN64, fmuInstances[_c->index]->modelID, LIB_EXT); + // check whether the dlls for Windows 32 bit exist in the binaries folder + bRes_w64 = (stat(librPath_w64, &st) == 0); + + // check whether we have folders for Windows 32 and Windows 64 bit + if (bRes_w32 && bRes_w64) { + if (OperSys == 1) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_w32, strlen(librPath_w32)); + } else { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_w64, strlen(librPath_w64)); + } + } + // check whether we just have folder for Windows 32 bit + else if (bRes_w32 && !bRes_w64) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_w32, strlen(librPath_w32)); + } + // check whether we just have folder for Windows 64 bit + else if (!bRes_w32 && bRes_w64) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_w64, strlen(librPath_w64)); + } else { + printf("Error: FMU does not contain binaries folder for this operating system."); + free(trimfmuWorkingFolder); + free(librPath_w32); + free(librPath_w64); + return -1; + } #endif #if __linux__ - len_LibPath = strlen(trimfmuWorkingFolder) + strlen(BIN_LIN) + strlen (fmuInstances[_c->index]->modelID) + strlen (LIB_EXT); - librPath_l32 = (char*)calloc(sizeof(char), len_LibPath + 10); - - // write the path to the binaries for Windows 32 bit - sprintf(librPath_l32, "%s%s%s%s", trimfmuWorkingFolder, BIN_LIN32,fmuInstances[_c->index]->modelID, LIB_EXT); - // check whether the so for Linux 32 bit exist in the binaries folder - bRes_l32 = (stat(librPath_l32, &st) == 0); - - // write the path to the binaries for Windows 64 bit - librPath_l64 = (char*)calloc(sizeof(char), len_LibPath + 10); - sprintf(librPath_l64, "%s%s%s%s", trimfmuWorkingFolder, BIN_LIN64,fmuInstances[_c->index]->modelID, LIB_EXT); - // check whether the so for Linux 64 bit exist in the binaries folder - bRes_l64 = (stat(librPath_l64, &st) == 0); - - // check whether we have folders for Linux 32 and Linux 64 bit - if (bRes_l32 && bRes_l64) { - if (OperSys == 3){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_l32, strlen(librPath_l32)); - } - else - { - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_l64, strlen(librPath_l64)); - } - } - // check whether we just have folder for Linux 32 bit - else if (bRes_l32 && !bRes_l64){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_l32, strlen(librPath_l32)); - } - // check whether we just have folder for Linux 64 bit - else if (!bRes_l32 && bRes_l64){ - strncpy(trimfmuOutputWorkingFolder_wLiB, librPath_l64, strlen(librPath_l64)); - } - else { - printf("Error: FMU does not contain binaries folder for this operating system."); - free(trimfmuWorkingFolder); - free(librPath_l32); - free(librPath_l64); - return -1; - } + len_LibPath = strlen(trimfmuWorkingFolder) + strlen(BIN_LIN) + strlen(fmuInstances[_c->index]->modelID) + strlen(LIB_EXT); + librPath_l32 = (char *)calloc(len_LibPath + 10, sizeof(char)); + + // write the path to the binaries for Windows 32 bit + sprintf(librPath_l32, "%s%s%s%s", trimfmuWorkingFolder, BIN_LIN32, fmuInstances[_c->index]->modelID, LIB_EXT); + // check whether the so for Linux 32 bit exist in the binaries folder + bRes_l32 = (stat(librPath_l32, &st) == 0); + + // write the path to the binaries for Windows 64 bit + librPath_l64 = (char *)calloc(len_LibPath + 10, sizeof(char)); + sprintf(librPath_l64, "%s%s%s%s", trimfmuWorkingFolder, BIN_LIN64, fmuInstances[_c->index]->modelID, LIB_EXT); + // check whether the so for Linux 64 bit exist in the binaries folder + bRes_l64 = (stat(librPath_l64, &st) == 0); + + // check whether we have folders for Linux 32 and Linux 64 bit + if (bRes_l32 && bRes_l64) { + if (OperSys == 3) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_l32, strlen(librPath_l32)); + } else { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_l64, strlen(librPath_l64)); + } + } + // check whether we just have folder for Linux 32 bit + else if (bRes_l32 && !bRes_l64) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_l32, strlen(librPath_l32)); + } + // check whether we just have folder for Linux 64 bit + else if (!bRes_l32 && bRes_l64) { + memcpy(trimfmuOutputWorkingFolder_wLiB, librPath_l64, strlen(librPath_l64)); + } else { + printf("Error: FMU does not contain binaries folder for this operating system."); + free(trimfmuWorkingFolder); + free(librPath_l32); + free(librPath_l64); + return -1; + } #endif - // deallocate memory FMU-working folder trimmed - free(trimfmuWorkingFolder); + // deallocate memory FMU-working folder trimmed + free(trimfmuWorkingFolder); - if (WINDOWS) { - // deallocate memory for path for binaries for windows 32 bit - free(librPath_w32); - // deallocate memory for path for binaries for windows 64 bit - free(librPath_w64); - } + if (WINDOWS) { + // deallocate memory for path for binaries for windows 32 bit + free(librPath_w32); + // deallocate memory for path for binaries for windows 64 bit + free(librPath_w64); + } #if __linux__ - // deallocate memory for path for binaries for windows 32 bit - free(librPath_l32); - // deallocate memory for path for binaries for windows 64 bit - free(librPath_l64); + // deallocate memory for path for binaries for windows 32 bit + free(librPath_l32); + // deallocate memory for path for binaries for windows 64 bit + free(librPath_l64); #endif - return 0; + return 0; } //////////////////////////////////////////////////////////////// @@ -1025,107 +1032,102 @@ fmiInteger addLibPathCurrentWorkingFolder( ///\param numOutputs Number of FMU outputs //////////////////////////////////////////////////////////////// -fmiInteger model_ID_GUID(char* fmuInstanceName, char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, - fmiInteger *numOutputs) { - - char* xmlPath; - char * trimfmuWorkingFolder; - void **list; - int num_input = 0; - int num_output = 0; - int i,j; - - c = (fmiComponent)calloc(1, sizeof(struct FMU)); - _c = (FMU*)c; - - _c->index = insNum; - addfmuInstances (_c); - insNum++; - //retValIns=insNum; - - // allocate memory for the FMU-working folder trimmed - trimfmuWorkingFolder = (char*)calloc(sizeof(char),*sizefmuWorkingFolder + 1); - //write fmuWorkingFolder withouth blanks - strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); - - // allocate memory for xmlPath - xmlPath = (char*)calloc(sizeof(char), strlen(trimfmuWorkingFolder) + strlen(XML_FILE) + 1); - // write path to the FMU - sprintf(xmlPath, "%s%s", trimfmuWorkingFolder, XML_FILE); - - // parse the xml-file and getModelDescription - fmuInstances[_c->index]->modelDescription = parse(xmlPath); - - // Initialize instance Name - fmuInstances[_c->index]->instanceName = (char*)calloc(sizeof(char), *fmuInstanceName + 1); - - // write fmu instance Name - strncpy(fmuInstances[_c->index]->instanceName, fmuInstanceName, strlen(fmuInstanceName)); - - // check whether modelDescription exists or not - if (!fmuInstances[_c->index]->modelDescription) { - printf("Error: failed to get the modelDescription in fmiGetModelID.\n"); - free(trimfmuWorkingFolder); - return -1; - } - // get the modelID of the FMU - fmuInstances[_c->index]->modelID = getModelIdentifier(fmuInstances[_c->index]->modelDescription); - - if (!fmuInstances[_c->index]->modelID) { - printf("Error: failed to get modelID in fmiGetModelID.\n"); - free(trimfmuWorkingFolder); - return -1; - } - - // get the model GUID of the FMU - fmuInstances[_c->index]->modelGUID = getString(fmuInstances[_c->index]->modelDescription, att_guid); - - if (!fmuInstances[_c->index]->modelGUID) { - printf("Error: failed to get modelGUID in fmiGetModelGUID.\n"); - free(trimfmuWorkingFolder); - return -1; - } - - for(i=0; iindex]->modelDescription->n; i+=2) - if(!strcmp(fmuInstances[_c->index]->modelDescription ->attributes[i], "modelIdentifier")); - - list = (void **)fmuInstances[_c->index]->modelDescription->modelVariables; - if (list) - for(j=0; list[j]; j++) - { - Element* e = (Element*)list[j]; - Enu val = enu_none; - - for(i=0; in; i+=2) - { - if(!strcmp(e->attributes[i], "causality")) - val = checkEnumValue2(e->attributes[i+1]); - } - - // get number of input variables - if(val == enu_input) - { - num_input = num_input + 1; - } - else if (val == enu_output){ - num_output = num_output + 1; - } - } - - // assign number of inputs found - *numInputs = num_input; - // assign number of output founds - *numOutputs = num_output; - - // deallocate xmlPath - free (xmlPath); - // free trimmed working folder - free (trimfmuWorkingFolder); - return insNum-1; +fmiInteger +model_ID_GUID(char *fmuInstanceName, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, fmiInteger *numOutputs) +{ + + char *xmlPath; + char *trimfmuWorkingFolder; + void **list; + int num_input = 0; + int num_output = 0; + int i, j; + + c = (fmiComponent)calloc(1, sizeof(struct FMU)); + _c = (FMU *)c; + + _c->index = insNum; + addfmuInstances(_c); + insNum++; + // retValIns=insNum; + + // allocate memory for the FMU-working folder trimmed + trimfmuWorkingFolder = (char *)calloc(*sizefmuWorkingFolder + 1, sizeof(char)); + // write fmuWorkingFolder withouth blanks + strncpy(trimfmuWorkingFolder, fmuWorkingFolder, *sizefmuWorkingFolder); + + // allocate memory for xmlPath + xmlPath = (char *)calloc(sizeof(char), strlen(trimfmuWorkingFolder) + strlen(XML_FILE) + 1); + // write path to the FMU + sprintf(xmlPath, "%s%s", trimfmuWorkingFolder, XML_FILE); + + // parse the xml-file and getModelDescription + fmuInstances[_c->index]->modelDescription = parse(xmlPath); + + // Initialize instance Name + fmuInstances[_c->index]->instanceName = (char *)calloc(strlen(fmuInstanceName) + 1, sizeof(char)); + + // write fmu instance Name + strcpy(fmuInstances[_c->index]->instanceName, fmuInstanceName); + + // check whether modelDescription exists or not + if (!fmuInstances[_c->index]->modelDescription) { + printf("Error: failed to get the modelDescription in fmiGetModelID.\n"); + free(trimfmuWorkingFolder); + return -1; + } + // get the modelID of the FMU + fmuInstances[_c->index]->modelID = getModelIdentifier(fmuInstances[_c->index]->modelDescription); + + if (!fmuInstances[_c->index]->modelID) { + printf("Error: failed to get modelID in fmiGetModelID.\n"); + free(trimfmuWorkingFolder); + return -1; + } + + // get the model GUID of the FMU + fmuInstances[_c->index]->modelGUID = getString(fmuInstances[_c->index]->modelDescription, att_guid); + + if (!fmuInstances[_c->index]->modelGUID) { + printf("Error: failed to get modelGUID in fmiGetModelGUID.\n"); + free(trimfmuWorkingFolder); + return -1; + } + + for (i = 0; i < fmuInstances[_c->index]->modelDescription->n; i += 2) + if (!strcmp(fmuInstances[_c->index]->modelDescription->attributes[i], "modelIdentifier")) + ; + + list = (void **)fmuInstances[_c->index]->modelDescription->modelVariables; + if (list) + for (j = 0; list[j]; j++) { + Element *e = (Element *)list[j]; + Enu val = enu_none; + + for (i = 0; i < e->n; i += 2) { + if (!strcmp(e->attributes[i], "causality")) val = checkEnumValue2(e->attributes[i + 1]); + } + + // get number of input variables + if (val == enu_input) { + num_input = num_input + 1; + } else if (val == enu_output) { + num_output = num_output + 1; + } + } + + // assign number of inputs found + *numInputs = num_input; + // assign number of output founds + *numOutputs = num_output; + + // deallocate xmlPath + free(xmlPath); + // free trimmed working folder + free(trimfmuWorkingFolder); + return insNum - 1; } - // This function is an interface to the function in Fortran that is used to parse the FMU //////////////////////////////////////////////////////////////// /// This method is an interface to the function in Fortran @@ -1137,190 +1139,194 @@ fmiInteger model_ID_GUID(char* fmuInstanceName, char* fmuWorkingFolder, ///\param sizefmuName Size of FMU name trimmed ///\param sizefmuOutputWorkingFolder Size of FMU working folder trimmed //////////////////////////////////////////////////////////////// -fmiInteger fmiEPlusUnpack(char* fmuName, - char* fmuOutputWorkingFolder, - fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder) { +fmiInteger fmiEPlusUnpack(char *fmuName, char *fmuOutputWorkingFolder, fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder) +{ - char * trimfmuOutputWorkingFolder; - char * trimfmuName; - int retVal; + char *trimfmuOutputWorkingFolder; + char *trimfmuName; + int retVal; - // allocate memory for the FMU-Name trimmed - trimfmuName = (char*)calloc(sizeof(char),*sizefmuName + 1); + // allocate memory for the FMU-Name trimmed + trimfmuName = (char *)calloc(*sizefmuName + 1, sizeof(char)); - // allocate memory for the FMU-working folder trimmed - trimfmuOutputWorkingFolder = (char*)calloc(sizeof(char),*sizefmuOutputWorkingFolder + 1); + // allocate memory for the FMU-working folder trimmed + trimfmuOutputWorkingFolder = (char *)calloc(*sizefmuOutputWorkingFolder + 1, sizeof(char)); - //write fmuName withouth blanks - strncpy(trimfmuName, fmuName, *sizefmuName); + // write fmuName withouth blanks + strncpy(trimfmuName, fmuName, *sizefmuName); - //write fmuWorkingFolder withouth blanks - strncpy(trimfmuOutputWorkingFolder, fmuOutputWorkingFolder, *sizefmuOutputWorkingFolder); + // write fmuWorkingFolder withouth blanks + strncpy(trimfmuOutputWorkingFolder, fmuOutputWorkingFolder, *sizefmuOutputWorkingFolder); - // unpack FMU in the working folder - retVal = unpackminizip (trimfmuName, trimfmuOutputWorkingFolder); + // unpack FMU in the working folder + retVal = unpackminizip(trimfmuName, trimfmuOutputWorkingFolder); - if (retVal != 0) { - printf("Error: failed to unpack FMU in fmiEPlusUnpack.\n"); - return -1; - } + if (retVal != 0) { + printf("Error: failed to unpack FMU in fmiEPlusUnpack.\n"); + return -1; + } - // deallocate memory FMU-Name - free(trimfmuName); - // deallocate memory FMU-working folder - free(trimfmuOutputWorkingFolder); - return 0; + // deallocate memory FMU-Name + free(trimfmuName); + // deallocate memory FMU-working folder + free(trimfmuOutputWorkingFolder); + return 0; } #else -fmiComponent fmiEPlusInstantiateSlave(char* fmuResFolder, - fmiInteger *sizefmuResFolder, - fmiReal *timeOut, fmiInteger *visible, - fmiInteger *interactive, fmiInteger *loggingOn, fmiInteger *index) { - (void)fmuResFolder; - (void)sizefmuResFolder; - (void)timeOut; - (void)visible; - (void)interactive; - (void)loggingOn; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiComponent fmiEPlusInstantiateSlave(char *fmuResFolder, + fmiInteger *sizefmuResFolder, + fmiReal *timeOut, + fmiInteger *visible, + fmiInteger *interactive, + fmiInteger *loggingOn, + fmiInteger *index) +{ + (void)fmuResFolder; + (void)sizefmuResFolder; + (void)timeOut; + (void)visible; + (void)interactive; + (void)loggingOn; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, - fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index){ - (void)fmuInstance; - (void)tStart; - (void)newStep; - (void)tStop; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index) +{ + (void)fmuInstance; + (void)tStart; + (void)newStep; + (void)tStop; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef [], - fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index){ - (void)fmuInstance; - (void)valRef; - (void)outValue; - (void)numOutputs; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index) +{ + (void)fmuInstance; + (void)valRef; + (void)outValue; + (void)numOutputs; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } - -fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], - fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index){ - (void)fmuInstance; - (void)valRef; - (void)inpVal; - (void)numInputs; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index) +{ + (void)fmuInstance; + (void)valRef; + (void)inpVal; + (void)numInputs; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, - fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index){ - (void)fmuInstance; - (void)curCommPoint; - (void)commStepSize; - (void)newStep; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index) +{ + (void)fmuInstance; + (void)curCommPoint; + (void)commStepSize; + (void)newStep; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation){ - (void)fmuInstance; - (void)index; - (void)fmiEndSimulation; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation) +{ + (void)fmuInstance; + (void)index; + (void)fmiEndSimulation; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index){ - (void)fmuInstance; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index) +{ + (void)fmuInstance; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiInteger fmiEPlusUnpack(char* fmuName, char* fmuOutputWorkingFolder, - fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder){ - (void)fmuName; - (void)fmuOutputWorkingFolder; - (void)sizefmuName; - (void)sizefmuOutputWorkingFolder; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiInteger fmiEPlusUnpack(char *fmuName, char *fmuOutputWorkingFolder, fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder) +{ + (void)fmuName; + (void)fmuOutputWorkingFolder; + (void)sizefmuName; + (void)sizefmuOutputWorkingFolder; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiValueReference getValueReferenceByNameFMUInputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index){ - (void)variableName; - (void)sizeVariableName; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiValueReference getValueReferenceByNameFMUInputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index) +{ + (void)variableName; + (void)sizeVariableName; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiValueReference getValueReferenceByNameFMUOutputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index){ - (void)variableName; - (void)sizeVariableName; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiValueReference getValueReferenceByNameFMUOutputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index) +{ + (void)variableName; + (void)sizeVariableName; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiInteger model_ID_GUID(char* fmuInstanceName, char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, - fmiInteger *numOutputs){ - (void)fmuInstanceName; - (void)fmuWorkingFolder; - (void)sizefmuWorkingFolder; - (void)numInputs; - (void)numOutputs; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiInteger +model_ID_GUID(char *fmuInstanceName, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, fmiInteger *numOutputs) +{ + (void)fmuInstanceName; + (void)fmuWorkingFolder; + (void)sizefmuWorkingFolder; + (void)numInputs; + (void)numOutputs; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiInteger addFMURootFolderName(char* fmuOutputWorkingFolder, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder){ - (void)fmuOutputWorkingFolder; - (void)fmuWorkingFolder; - (void)sizefmuWorkingFolder; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiInteger addFMURootFolderName(char *fmuOutputWorkingFolder, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder) +{ + (void)fmuOutputWorkingFolder; + (void)fmuWorkingFolder; + (void)sizefmuWorkingFolder; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiInteger getfmiEPlusVersion(char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index){ - (void)fmuWorkingFolder; - (void)sizefmuWorkingFolder; - (void)fmiVersionNumber; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiInteger getfmiEPlusVersion(char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index) +{ + (void)fmuWorkingFolder; + (void)sizefmuWorkingFolder; + (void)fmiVersionNumber; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } -fmiInteger addLibPathCurrentWorkingFolder(char* trimfmuOutputWorkingFolder_wLiB, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, - fmiInteger *index){ - (void)trimfmuOutputWorkingFolder_wLiB; - (void)fmuWorkingFolder; - (void)sizefmuWorkingFolder; - (void)index; - printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); - exit(EXIT_FAILURE); +fmiInteger +addLibPathCurrentWorkingFolder(char *trimfmuOutputWorkingFolder_wLiB, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *index) +{ + (void)trimfmuOutputWorkingFolder_wLiB; + (void)fmuWorkingFolder; + (void)sizefmuWorkingFolder; + (void)index; + printf("Error: FunctionalMock-up Unit for co-simulation is currently only supported on Windows and Linux."); + exit(EXIT_FAILURE); } #endif // -//int main () +// int main () //{ // fmiInteger len1 = 8; // fmiInteger len2 = 10; diff --git a/third_party/FMI/main.h b/third_party/FMI/main.h index 4ba863e122a..82941f9448b 100644 --- a/third_party/FMI/main.h +++ b/third_party/FMI/main.h @@ -34,103 +34,103 @@ #include // for creating dirs on Linux #endif +#include "eplusModelFunctions.h" #include "fmiModelFunctions.h" #include "xml_parser_cosim.h" -#include "eplusModelFunctions.h" -typedef const char* (*fGetTypesPlatform)(); -typedef const char* (*fGetVersion)(); -typedef fmiComponent (*fInstantiateSlave)(fmiString instanceName, fmiString GUID, - fmiString fmuLocation, fmiString mimeType, fmiReal timeout, - fmiBoolean visible, fmiBoolean interactive, - fmiCallbackFunctions functions, fmiBoolean loggingOn); -typedef void (*fFreeSlaveInstance) (fmiComponent c); -typedef fmiStatus (*fResetSlaveInstance) (fmiComponent c); -typedef fmiStatus (*fSetDebugLogging) (fmiComponent c, fmiBoolean loggingOn); -typedef fmiStatus (*fSetReal) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); +typedef const char *(*fGetTypesPlatform)(); +typedef const char *(*fGetVersion)(); +typedef fmiComponent (*fInstantiateSlave)(fmiString instanceName, + fmiString GUID, + fmiString fmuLocation, + fmiString mimeType, + fmiReal timeout, + fmiBoolean visible, + fmiBoolean interactive, + fmiCallbackFunctions functions, + fmiBoolean loggingOn); +typedef void (*fFreeSlaveInstance)(fmiComponent c); +typedef fmiStatus (*fResetSlaveInstance)(fmiComponent c); +typedef fmiStatus (*fSetDebugLogging)(fmiComponent c, fmiBoolean loggingOn); +typedef fmiStatus (*fSetReal)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); -typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); +typedef fmiStatus (*fSetString)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); typedef fmiStatus (*fInitializeSlave)(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop); -typedef fmiStatus (*fGetReal) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); +typedef fmiStatus (*fGetReal)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); -typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); - -typedef fmiStatus (*fDoStep) (fmiComponent c, fmiReal currentCommunicationPoint, fmiReal communicationStepSize, - fmiBoolean newStep); // Zuo: add for co-sim - -typedef struct FMU{ - int index; - char* instanceName; - fmiString modelID; - fmiString modelGUID; - ModelDescription* modelDescription; - HANDLE dllHandle; - fGetTypesPlatform getTypesPlatform; - fGetVersion getVersion; - fInstantiateSlave instantiateSlave; - fFreeSlaveInstance freeSlaveInstance; - fResetSlaveInstance resetSlaveInstance; - fSetDebugLogging setDebugLogging; - fSetReal setReal; - fSetInteger setInteger; - fSetBoolean setBoolean; - fSetString setString; - fInitializeSlave initializeSlave; - fGetReal getReal; - fGetInteger getInteger; - fGetBoolean getBoolean; - fGetString getString; - fDoStep doStep; +typedef fmiStatus (*fGetString)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); + +typedef fmiStatus (*fDoStep)(fmiComponent c, + fmiReal currentCommunicationPoint, + fmiReal communicationStepSize, + fmiBoolean newStep); // Zuo: add for co-sim + +typedef struct FMU +{ + int index; + char *instanceName; + fmiString modelID; + fmiString modelGUID; + ModelDescription *modelDescription; + HANDLE dllHandle; + fGetTypesPlatform getTypesPlatform; + fGetVersion getVersion; + fInstantiateSlave instantiateSlave; + fFreeSlaveInstance freeSlaveInstance; + fResetSlaveInstance resetSlaveInstance; + fSetDebugLogging setDebugLogging; + fSetReal setReal; + fSetInteger setInteger; + fSetBoolean setBoolean; + fSetString setString; + fInitializeSlave initializeSlave; + fGetReal getReal; + fGetInteger getInteger; + fGetBoolean getBoolean; + fGetString getString; + fDoStep doStep; } FMU; -fmiComponent fmiEPlusInstantiateSlave(char* fmuResFolder, - fmiInteger *sizefmuResFolder, fmiReal *timeOut, fmiInteger *visible, - fmiInteger *interactive, fmiInteger *loggingOn, fmiInteger *index); +fmiComponent fmiEPlusInstantiateSlave(char *fmuResFolder, + fmiInteger *sizefmuResFolder, + fmiReal *timeOut, + fmiInteger *visible, + fmiInteger *interactive, + fmiInteger *loggingOn, + fmiInteger *index); -fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, - fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index); +fmiStatus fmiEPlusInitializeSlave(fmiComponent *fmuInstance, fmiReal *tStart, fmiInteger *newStep, fmiReal *tStop, fmiInteger *index); -fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef [], - fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index); +fmiStatus fmiEPlusGetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal outValue[], fmiInteger *numOutputs, fmiInteger *index); -fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], - fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index); +fmiStatus fmiEPlusSetReal(fmiComponent *fmuInstance, const fmiValueReference valRef[], fmiReal inpVal[], fmiInteger *numInputs, fmiInteger *index); -fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, - fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index); +fmiStatus fmiEPlusDoStep(fmiComponent *fmuInstance, fmiReal *curCommPoint, fmiReal *commStepSize, fmiInteger *newStep, fmiInteger *index); fmiStatus fmiEPlusFreeSlave(fmiComponent *fmuInstance, fmiInteger *index, fmiInteger *fmiEndSimulation); fmiStatus fmiEPlusResetSlave(fmiComponent *fmuInstance, fmiInteger *index); -fmiInteger fmiEPlusUnpack(char* fmuName, char* fmuOutputWorkingFolder, - fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder); +fmiInteger fmiEPlusUnpack(char *fmuName, char *fmuOutputWorkingFolder, fmiInteger *sizefmuName, fmiInteger *sizefmuOutputWorkingFolder); -fmiInteger addLibPathCurrentWorkingFolder(char* trimfmuOutputWorkingFolder_wLiB, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, - fmiInteger *index); +fmiInteger +addLibPathCurrentWorkingFolder(char *trimfmuOutputWorkingFolder_wLiB, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *index); -fmiValueReference getValueReferenceByNameFMUInputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index); +fmiValueReference getValueReferenceByNameFMUInputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index); -fmiValueReference getValueReferenceByNameFMUOutputVariables(char* variableName, - fmiInteger *sizeVariableName, fmiInteger *index); +fmiValueReference getValueReferenceByNameFMUOutputVariables(char *variableName, fmiInteger *sizeVariableName, fmiInteger *index); -fmiInteger model_ID_GUID(char* fmuInstanceName, char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, - fmiInteger *numOutputs); +fmiInteger +model_ID_GUID(char *fmuInstanceName, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, fmiInteger *numInputs, fmiInteger *numOutputs); -fmiInteger addFMURootFolderName(char* fmuOutputWorkingFolder, - char* fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder); +fmiInteger addFMURootFolderName(char *fmuOutputWorkingFolder, char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder); -fmiInteger getfmiEPlusVersion(char* fmuWorkingFolder, - fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index); +fmiInteger getfmiEPlusVersion(char *fmuWorkingFolder, fmiInteger *sizefmuWorkingFolder, char *fmiVersionNumber, fmiInteger *index); -fmiInteger checkOperatingSystem(char* errorMessage); +fmiInteger checkOperatingSystem(char *errorMessage); #endif // main_h - diff --git a/third_party/FMI/stack.c b/third_party/FMI/stack.c index ab84cce2e90..eea55636357 100644 --- a/third_party/FMI/stack.c +++ b/third_party/FMI/stack.c @@ -4,13 +4,14 @@ * Copyright 2010 QTronic GmbH. All rights reserved. * -------------------------------------------------------------------------*/ -#include -#include #include "stack.h" +#include +#include #include -Stack* stackNew(int initialSize, int inc){ - Stack* s = (Stack*)malloc(sizeof(Stack)); +Stack *stackNew(int initialSize, int inc) +{ + Stack *s = (Stack *)malloc(sizeof(Stack)); s->stack = NULL; s->stackSize = 0; s->stackPos = -1; @@ -19,17 +20,19 @@ Stack* stackNew(int initialSize, int inc){ return s; } -int stackIsEmpty(Stack* s) { +int stackIsEmpty(Stack *s) +{ return s->stackPos == -1; } // add an element to stack and grow stack if required // returns 1 to indicate success and 0 for error -int stackPushFMI(Stack *s, void *e) { +int stackPushFMI(Stack *s, void *e) +{ s->stackPos++; - if (s->stackPos==s->stackSize){ - s->stackSize += (s->stack ? s->inc: s->initialSize); - s->stack = (void**) realloc(s->stack, s->stackSize * sizeof(void*)); + if (s->stackPos == s->stackSize) { + s->stackSize += (s->stack ? s->inc : s->initialSize); + s->stack = (void **)realloc(s->stack, s->stackSize * sizeof(void *)); if (!s->stack) return 0; // error; } s->stack[s->stackPos] = e; @@ -38,48 +41,51 @@ int stackPushFMI(Stack *s, void *e) { // return top element (possibly NULL), if stack not empty // runtime error if stack is empty -void* stackPeek(Stack* s){ +void *stackPeek(Stack *s) +{ assert(!stackIsEmpty(s)); return s->stack[s->stackPos]; } // remove top element (possibly NULL) from stack and return it // runtime error if stack is empty -void* stackPopFMI(Stack *s){ +void *stackPopFMI(Stack *s) +{ assert(!stackIsEmpty(s)); return s->stack[s->stackPos--]; } // return the last n elements as null terminated array, // or NULL if memory allocation fails -void** stackLastPopedAsArray0(Stack* s, int n){ +void **stackLastPopedAsArray0(Stack *s, int n) +{ int i; - void** array = (void**)malloc((n + 1)*sizeof(void*)); - if (! array) return NULL; // failure - for (i=0; istack[i+ s->stackPos + 1]; + void **array = (void **)malloc((n + 1) * sizeof(void *)); + if (!array) return NULL; // failure + for (i = 0; i < n; i++) { + array[i] = s->stack[i + s->stackPos + 1]; } - array[n]=NULL; // terminating NULL + array[n] = NULL; // terminating NULL return array; } // return stack as possibly empty array, or NULL if memory allocation fails // On sucessful return, the stack is empty. -void** stackPopAllAsArray(Stack* s, int *size) { +void **stackPopAllAsArray(Stack *s, int *size) +{ int i; - void** array = (void**)malloc((s->stackPos + 1)*sizeof(void*)); - if (! array) return NULL; // failure + void **array = (void **)malloc((s->stackPos + 1) * sizeof(void *)); + if (!array) return NULL; // failure *size = s->stackPos + 1; - for (i=0; i<*size; i++) + for (i = 0; i < *size; i++) array[i] = s->stack[i]; s->stackPos = -1; return array; } // release the given stack -void stackFree(Stack* s){ +void stackFree(Stack *s) +{ if (s->stack) free(s->stack); free(s); } - - diff --git a/third_party/FMI/stack.h b/third_party/FMI/stack.h index 64e23a508a9..22688005e43 100644 --- a/third_party/FMI/stack.h +++ b/third_party/FMI/stack.h @@ -7,22 +7,22 @@ #ifndef STACK_H #define STACK_H -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 +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); +Stack *stackNew(int initialSize, int inc); +int stackIsEmpty(Stack *s); int stackPushFMI(Stack *s, void *e); -void* stackPeek(Stack* s); -void* stackPopFMI(Stack *s); -void** stackPopAllAsArray(Stack* s, int *size); -void** stackLastPopedAsArray0(Stack* s, int n); -void stackFree(Stack* s); +void *stackPeek(Stack *s); +void *stackPopFMI(Stack *s); +void **stackPopAllAsArray(Stack *s, int *size); +void **stackLastPopedAsArray0(Stack *s, int n); +void stackFree(Stack *s); #endif // STACK_H - diff --git a/third_party/FMI/util.c b/third_party/FMI/util.c index 2dfff3bcfa4..4681e737ee4 100644 --- a/third_party/FMI/util.c +++ b/third_party/FMI/util.c @@ -19,14 +19,14 @@ /// All rights reserved. /////////////////////////////////////////////////////// +#include "util.h" +#include "fmumini.h" #include #include #include #include -#include "util.h" -#include "fmumini.h" -int debug = 0; // Control for debug information +int debug = 0; // Control for debug information /////////////////////////////////////////////////////////////////////////////// /// Translate the double variable to string variable. @@ -34,8 +34,9 @@ int debug = 0; // Control for debug information ///\param buffer String variable. ///\param r Double variable. /////////////////////////////////////////////////////////////////////////////// -void doubleToCommaString(char* buffer, double r){ - char* comma; +void doubleToCommaString(char *buffer, double r) +{ + char *comma; sprintf(buffer, "%.16g", r); comma = strchr(buffer, '.'); if (comma) *comma = ','; @@ -47,38 +48,38 @@ void doubleToCommaString(char* buffer, double r){ ///\param tmpPat The path of the temporary folder ///\return 0 if no error occurred ///////////////////////////////////////////////////////////////////////// -int delete(char* tmpPat){ - char* cmd; - struct stat st; - - // Ceck if the folder present - if(stat(tmpPat,&st) != 0){ - printfError("Folder \"%s\" is not existing.\n", tmpPat); - return -1; - } - - cmd = calloc(sizeof(char), strlen(tmpPat) +18); - if (cmd == NULL){ - printfError("Fail to allocate memory for cmd.\n", tmpPat); - return -1; - } - - if (IS_WINDOWS) - sprintf(cmd, "rd %s /S/Q", tmpPat); // Command in windows - else - sprintf(cmd, "rm -r %s", tmpPat); // Command in Linux - - - printfDebug("Generated cmd: \"%s\".\n", cmd); - if ( system(cmd) != 0 ){ - //if(rmdir(tmpPat) != 0) - printError("Fail to delete the temporary files"); - free(cmd); - return -1; - } - printDebug("Deleted temporary files"); - free(cmd); - return 0; +int delete (char *tmpPat) +{ + char *cmd; + struct stat st; + + // Ceck if the folder present + if (stat(tmpPat, &st) != 0) { + printfError("Folder \"%s\" is not existing.\n", tmpPat); + return -1; + } + + cmd = calloc(strlen(tmpPat) + 18, sizeof(char)); + if (cmd == NULL) { + printfError("Fail to allocate memory for cmd.\n", tmpPat); + return -1; + } + + if (IS_WINDOWS) + sprintf(cmd, "rd %s /S/Q", tmpPat); // Command in windows + else + sprintf(cmd, "rm -r %s", tmpPat); // Command in Linux + + printfDebug("Generated cmd: \"%s\".\n", cmd); + if (system(cmd) != 0) { + // if(rmdir(tmpPat) != 0) + printError("Fail to delete the temporary files"); + free(cmd); + return -1; + } + printDebug("Deleted temporary files"); + free(cmd); + return 0; } ////////////////////////////////////////////////////////////////////////////// @@ -90,31 +91,31 @@ int delete(char* tmpPat){ ///////////////////////////////////////////////////////////////////////////// char *getTmpPath(const char *nam, size_t length) { - char *tmpPat; - - tmpPat = calloc(sizeof(char), length+2); - - // Define the temporary folder - if(strncpy(tmpPat, nam, length) == NULL){ - printError("Fail to allocate memory for temp dir.\n"); - free(tmpPat); - return NULL; - } - if(IS_WINDOWS) strcat(tmpPat, "\\"); - else strcat(tmpPat, "/"); - - return tmpPat; + char *tmpPat; + + tmpPat = calloc(length + 2, sizeof(char)); + + // Define the temporary folder + if (strncpy(tmpPat, nam, length) == NULL) { + printError("Fail to allocate memory for temp dir.\n"); + free(tmpPat); + return NULL; + } + if (IS_WINDOWS) + strcat(tmpPat, "\\"); + else + strcat(tmpPat, "/"); + + return tmpPat; } - - ////////////////////////////////////////////////////////////////////////////// /// Set the mode in debug so that the debug information will be printed /// ////////////////////////////////////////////////////////////////////////////// -void setDebug( ) +void setDebug() { - debug = 1; + debug = 1; } ////////////////////////////////////////////////////////////////////////////// @@ -122,12 +123,12 @@ void setDebug( ) /// ///\param msg Message to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printDebug(const char* msg){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, "%s\n", msg); - } +void printDebug(const char *msg) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, "%s\n", msg); + } } ////////////////////////////////////////////////////////////////////////////// @@ -136,12 +137,12 @@ void printDebug(const char* msg){ ///\param str1 Message to be printed for debugging ///\param str2 String variable to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printfDebug(const char* str1, const char* str2){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, str1, str2); - } +void printfDebug(const char *str1, const char *str2) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, str1, str2); + } } ////////////////////////////////////////////////////////////////////////////// @@ -150,12 +151,12 @@ void printfDebug(const char* str1, const char* str2){ ///\param str1 Message to be printed for debugging ///\param integer Integer variable to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printfIntDebug(const char* str1, const int integer){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, str1, integer); - } +void printfIntDebug(const char *str1, const int integer) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, str1, integer); + } } ////////////////////////////////////////////////////////////////////////////// @@ -163,9 +164,10 @@ void printfIntDebug(const char* str1, const int integer){ /// ///\param msg Error message to be printed ////////////////////////////////////////////////////////////////////////////// -void printError(const char* msg){ - fprintf(stderr, "*** Error: "); - fprintf(stderr, "%s\n", msg); +void printError(const char *msg) +{ + fprintf(stderr, "*** Error: "); + fprintf(stderr, "%s\n", msg); } ////////////////////////////////////////////////////////////////////////////// @@ -174,9 +176,10 @@ void printError(const char* msg){ ///\param str1 Error message to be printed ///\param str2 String variable to be printed ////////////////////////////////////////////////////////////////////////////// -void printfError(const char* str1, const char* str2){ - fprintf(stderr, "*** Error: "); - fprintf(stderr, str1, str2); +void printfError(const char *str1, const char *str2) +{ + fprintf(stderr, "*** Error: "); + fprintf(stderr, str1, str2); } ////////////////////////////////////////////////////////////////////////////// @@ -186,7 +189,7 @@ void printfError(const char* str1, const char* str2){ ///\param tmpPat Temporary path of the output file ///\return 0 if no error occurred ///////////////////////////////////////////////////////////////////////////// -int unpackminizip(const char* fmuFilNam, char* tmpPat){ - return unpackmz(fmuFilNam, tmpPat); +int unpackminizip(const char *fmuFilNam, char *tmpPat) +{ + return unpackmz(fmuFilNam, tmpPat); } - diff --git a/third_party/FMI/util.h b/third_party/FMI/util.h index aaee644399a..15f31fb7360 100644 --- a/third_party/FMI/util.h +++ b/third_party/FMI/util.h @@ -23,27 +23,28 @@ #define HANDLE void * /* See http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html */ #include // for creating dirs on Linux +#include // defines size_t #endif -//static char* getfmuPat(const char* fmuFilNam); -int delete(char* tmpPat); +// static char* getfmuPat(const char* fmuFilNam); +int delete (char *tmpPat); -void doubleToCommaString(char* buffer, double r); +void doubleToCommaString(char *buffer, double r); char *getTmpPath(const char *nam, size_t length); -void printDebug(const char* msg); +void printDebug(const char *msg); -void printfDebug(const char* str1, const char* str2); +void printfDebug(const char *str1, const char *str2); -void printfIntDebug(const char* str1, const int integer); +void printfIntDebug(const char *str1, const int integer); -void printError(const char* msg); +void printError(const char *msg); -void printfError(const char* str1, const char* str2); +void printfError(const char *str1, const char *str2); void setDebug(); -int unpack(const char* fmuFilNam, const char* tmpPat); +int unpack(const char *fmuFilNam, const char *tmpPat); -int unpackminizip(const char* fmuFilNam, char* tmpPat); +int unpackminizip(const char *fmuFilNam, char *tmpPat); diff --git a/third_party/FMI/xml_parser_cosim.c b/third_party/FMI/xml_parser_cosim.c index 28268d12581..edb6b3ebf68 100644 --- a/third_party/FMI/xml_parser_cosim.c +++ b/third_party/FMI/xml_parser_cosim.c @@ -45,86 +45,173 @@ * Copyright 2010 QTronic GmbH. All rights reserved. * -------------------------------------------------------------------------*/ -#include -#include -#include -#include #include "xml_parser_cosim.h" #include "util.h" +#include +#include +#include +#include -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" -}; +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 ANY_TYPE -1 #define XMLBUFSIZE 1024 -char text[XMLBUFSIZE]; // XML file is parsed in chunks of length XMLBUFZIZE +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 recordig content +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 recordig 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; +const char *getString(void *element, Att a) +{ + Element *e = (Element *)element; + const char **attr = e->attributes; int i; - for (i=0; in; i+=2) - if (attr[i]==attNames[a]) return attr[i+1]; + 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 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; + 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 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; + 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 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; + 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; }; +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; @@ -132,28 +219,34 @@ char getBoolean(void* element, Att a, ValueStatus* vs){ return 0; } -static int checkEnumValue(const char* enu); +static int 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 -1 or a globally unique id for the value such that // enuNames[id] is the string representation of the enum value. -int getEnumValue(void* element, Att a, ValueStatus* vs) { - const char* value = getString(element, a); +int getEnumValue(void *element, Att a, ValueStatus *vs) +{ + const char *value = getString(element, a); int id /*= 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 -1; + 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 -1; } } id = checkEnumValue(value); - if (id==-1) *vs = valueIllegal; + if (id == -1) *vs = valueIllegal; return id; } @@ -161,50 +254,57 @@ int getEnumValue(void* element, Att a, ValueStatus* vs) { // Convenience methods for accessing the model description. // Use is only safe after the ast has been successfuly validated. -const char* getModelIdentifier(ModelDescription* md) { - const char* modelId = getString(md, att_modelIdentifier); +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) { +int getNumberOfStates(ModelDescription *md) +{ ValueStatus vs; int n = getUInt(md, att_numberOfContinuousStates, &vs); - assert(vs==valueDefined); // this is a required attribute + assert(vs == valueDefined); // this is a required attribute return n; } -int getNumberOfEventIndicators(ModelDescription* md) { +int getNumberOfEventIndicators(ModelDescription *md) +{ ValueStatus vs; int n = getInt(md, att_numberOfEventIndicators, &vs); - assert(vs==valueDefined); // this is a required attribute + 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); +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) { +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) { +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) { +Enu getAlias(void *scalarVariable) +{ ValueStatus vs; return getEnumValue(scalarVariable, att_alias, &vs); } @@ -212,58 +312,61 @@ Enu getAlias(void* scalarVariable) { // 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) { +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 reqired attribute + assert(((Element *)scalarVariable)->type == elm_ScalarVariable); + assert(vs == valueDefined); // this is a reqired attribute return vr; } // the name is unique within a fmu -ScalarVariable* getVariableByName(ModelDescription* md, const char* name) { +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; - } + 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); +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 -ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){ +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; - } + 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; } -Type* getDeclaredType(ModelDescription* md, const char* declaredType){ +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; - } + for (i = 0; md->typeDefinitions[i]; i++) { + Type *tp = (Type *)md->typeDefinitions[i]; + if (!strcmp(declaredType, getName(tp))) return tp; + } return NULL; } -const char* getString2(ModelDescription* md, void* tp, Att a) { - Type* type; - const char* value = getString(tp, a); +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)); @@ -271,9 +374,10 @@ const char* getString2(ModelDescription* md, void* tp, Att a) { } // 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; +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)); @@ -282,11 +386,11 @@ const char * getDescription(ModelDescription* md, ScalarVariable* sv) { // 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); +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 @@ -297,29 +401,34 @@ const char * getVariableAttributeString(ModelDescription* md, // 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 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; + 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){ +double getNominal(ModelDescription *md, fmiValueReference vr) +{ ValueStatus vs; double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs); - return vs==valueDefined ? nominal : 1.0; + 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) { +static int checkPointer(const void *ptr) +{ + if (!ptr) { printf("Out of memory\n"); if (parser) XML_StopParser(parser, XML_FALSE); return 0; // error @@ -327,9 +436,10 @@ static int checkPointer(const void* ptr){ return 1; // success } -static int checkName(const char* name, const char* kind, const char* array[], int n){ +static int checkName(const char *name, const char *kind, const char *array[], int n) +{ int i; - for (i=0; itype == e) return 1; // success logFatalTypeError(elmNames[e], elm->type); return 0; // error @@ -370,26 +484,33 @@ static int checkElementType(void* element, Elm e) { // Returns 0 to indicate error // Verify that the next stack element exists and is of the given type // If e==ANY_TYPE, the type check is ommited -static int checkPeek(int e) { - if (stackIsEmpty(stack)){ - printf("Illegal document structure, expected %s\n", elmNames[e]); +static int checkPeek(int e) +{ + if (stackIsEmpty(stack)) { + if (e == ANY_TYPE) { + printf("Illegal document structure, expected ANY_TYPE (-1)\n"); + } else { + printf("Illegal document structure, expected %s\n", elmNames[e]); + } XML_StopParser(parser, XML_FALSE); return 0; // error } - return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e); + return e == ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e); } // Returns NULL to indicate error // Get the next stack element, it is of the given type. // If e==ANY_TYPE, the type check is ommited -static void* checkPop(Elm e){ +static void *checkPop(Elm e) +{ return checkPeek(e) ? stackPopFMI(stack) : NULL; } // ------------------------------------------------------------------------- // Helper -AstNodeType getAstNodeType(Elm e){ +AstNodeType getAstNodeType(Elm e) +{ switch (e) { case elm_fmiModelDescription: return astModelDescription; @@ -419,21 +540,23 @@ AstNodeType getAstNodeType(Elm e){ // 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 addAttributes(Element *el, const char **attr) +{ int n, a; - const char** att = NULL; - for (n=0; attr[n]; n+=2); - if (n>0) { - att = calloc(n, sizeof(char*)); + const char **att = NULL; + for (n = 0; attr[n]; n += 2) + ; + if (n > 0) { + att = calloc(n, sizeof(char *)); if (!checkPointer(att)) return 0; } - for (n=0; attr[n]; n+=2) { - char* value = strdup(attr[n+1]); + for (n = 0; attr[n]; n += 2) { + char *value = strdup(attr[n + 1]); if (!checkPointer(value)) return 0; a = checkAttribute(attr[n]); if (a == -1) return 0; // illegal attribute error - att[n ] = attNames[a]; // no heap memory - att[n+1] = value; // heap memory + att[n] = attNames[a]; // no heap memory + att[n + 1] = value; // heap memory } el->attributes = att; // NULL if n=0 el->n = n; @@ -441,12 +564,13 @@ int addAttributes(Element* el, const char** attr) { } // Returns NULL to indicate error -Element* newElement(Elm type, int size, const char** attr) { - Element* e = (Element*)calloc(1, size); +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; + e->n = 0; if (!addAttributes(e, attr)) return NULL; return e; } @@ -455,22 +579,36 @@ Element* newElement(Elm type, int size, const char** attr) { // 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) { +static void XMLCALL startElement(void *context, const char *elm, const char **attr) +{ (void)context; int el; - void* e; + void *e; int size; el = checkElement(elm); - if (el==-1) return; // error + if (el == -1) 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); + 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); checkPointer(e); @@ -480,199 +618,213 @@ default: assert(0); // 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) { +static void popList(Elm e) +{ int n = 0; - Element** array; - Element* elm = stackPopFMI(stack); + Element **array; + Element *elm = stackPopFMI(stack); while (elm->type == e) { elm = stackPopFMI(stack); n++; } - stackPushFMI(stack, elm); // push ListElement back to stack - array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list - if (getAstNodeType(elm->type)!=astListElement) return; // failure - ((ListElement*)elm)->list = array; + stackPushFMI(stack, elm); // push ListElement back to stack + array = (Element **)stackLastPopedAsArray0(stack, n); // NULL terminated list + if (getAstNodeType(elm->type) != astListElement) 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) { +static void XMLCALL endElement(void *context, const char *elm) +{ (void)context; int el; 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 = checkPop(ANY_TYPE); - if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) { - cs = (CoSimulation*)child; - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_ModelVariables){ - mv = (ScalarVariable**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_VendorAnnotations){ - va = (ListElement**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_DefaultExperiment){ - de = (Element*)child; - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_TypeDefinitions){ - td = (Type**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_UnitDefinitions){ - ud = (ListElement**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location - if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) { - cs = (CoSimulation*)child; - child = checkPop(ANY_TYPE); - 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; - stackPushFMI(stack, md); - break; - } - case elm_Implementation: - { - // replace Implementation element - void* cs = checkPop(ANY_TYPE); - void* im = checkPop(elm_Implementation); - stackPushFMI(stack, cs); - free(im); - el = ((Element*)cs)->type; - break; - } - case elm_CoSimulation_StandAlone: - { - Element* ca = checkPop(elm_Capabilities); - CoSimulation* cs = checkPop(elm_CoSimulation_StandAlone); - if (!ca || !cs) return; - cs->capabilities = ca; - stackPushFMI(stack, cs); - break; - } - case elm_CoSimulation_Tool: - { - ListElement* mo = checkPop(elm_Model); - Element* ca = checkPop(elm_Capabilities); - CoSimulation* cs = checkPop(elm_CoSimulation_Tool); - if (!ca || !mo || !cs) return; - cs->capabilities = ca; - cs->model = mo; - stackPushFMI(stack, cs); - break; - } - case elm_Type: - { - Type* tp; - Element* ts = checkPop(ANY_TYPE); - 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 = checkPop(ANY_TYPE); - if (!child) return; - if (child->type==elm_DirectDependency){ - list = ((ListElement*)child)->list; - free(child); - child = checkPop(ANY_TYPE); - 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 = checkPop(elm_Name); - if (!name) return; - name->n = 2; - name->attributes = malloc(2*sizeof(char*)); - name->attributes[0] = attNames[att_input]; - name->attributes[1] = data; - data = NULL; - skipData = 1; // stop recording element content - stackPushFMI(stack, name); - break; - } - case -1: return; // illegal element error - default: // must be a leaf Element - assert(getAstNodeType(el)==astElement); - break; + 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 = checkPop(ANY_TYPE); + if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) { + cs = (CoSimulation *)child; + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_ModelVariables) { + mv = (ScalarVariable **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_VendorAnnotations) { + va = (ListElement **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_DefaultExperiment) { + de = (Element *)child; + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_TypeDefinitions) { + td = (Type **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_UnitDefinitions) { + ud = (ListElement **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location + if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) { + cs = (CoSimulation *)child; + child = checkPop(ANY_TYPE); + 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; + stackPushFMI(stack, md); + break; + } + case elm_Implementation: { + // replace Implementation element + void *cs = checkPop(ANY_TYPE); + void *im = checkPop(elm_Implementation); + stackPushFMI(stack, cs); + free(im); + el = ((Element *)cs)->type; + break; + } + case elm_CoSimulation_StandAlone: { + Element *ca = checkPop(elm_Capabilities); + CoSimulation *cs = checkPop(elm_CoSimulation_StandAlone); + if (!ca || !cs) return; + cs->capabilities = ca; + stackPushFMI(stack, cs); + break; + } + case elm_CoSimulation_Tool: { + ListElement *mo = checkPop(elm_Model); + Element *ca = checkPop(elm_Capabilities); + CoSimulation *cs = checkPop(elm_CoSimulation_Tool); + if (!ca || !mo || !cs) return; + cs->capabilities = ca; + cs->model = mo; + stackPushFMI(stack, cs); + break; + } + case elm_Type: { + Type *tp; + Element *ts = checkPop(ANY_TYPE); + 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 = checkPop(ANY_TYPE); + if (!child) return; + if (child->type == elm_DirectDependency) { + list = ((ListElement *)child)->list; + free(child); + child = checkPop(ANY_TYPE); + 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 = checkPop(elm_Name); + if (!name) return; + name->n = 2; + name->attributes = malloc(2 * sizeof(char *)); + name->attributes[0] = attNames[att_input]; + name->attributes[1] = data; + data = NULL; + skipData = 1; // stop recording element content + stackPushFMI(stack, name); + break; + } + case -1: + 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. @@ -685,7 +837,8 @@ static void XMLCALL endElement(void *context, const char *elm) { // For some reason, if the element data is the empty string (Eg. ) // 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) { +void XMLCALL handleData(void *context, const XML_Char *s, int len) +{ (void)context; size_t n; if (skipData) return; @@ -698,17 +851,16 @@ void XMLCALL handleData(void *context, const XML_Char *s, int len) { strncpy(data, s, len); data[len] = '\0'; } - } - else { + } else { // continue existing string n = strlen(data) + len; - char* tmpData; - tmpData = realloc(data, n+1); + char *tmpData; + tmpData = realloc(data, n + 1); if (!tmpData) { - printf("Couldnt allocate memory in xml_parser_cosim::handleData\n"); - return; - } - data = tmpData; + printf("Couldnt allocate memory in xml_parser_cosim::handleData\n"); + return; + } + data = tmpData; strncat(data, s, len); data[n] = '\0'; } @@ -718,57 +870,61 @@ void XMLCALL handleData(void *context, const XML_Char *s, int len) { // ------------------------------------------------------------------------- // printing -static void printList(int indent, void** list); +static void printList(int indent, void **list); -void printElement(int indent, void* element){ +void printElement(int indent, void *element) +{ int i; - Element* e = (Element*)element; + Element *e = (Element *)element; if (!e) return; // print attributes - for (i=0; itype]); - for (i=0; in; i+=2) - printf(" %s=%s", e->attributes[i], e->attributes[i+1]); + 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: - printElement(indent, (void**)(Element*)e); - 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; - } + case astElement: + printElement(indent, (void **)(Element *)e); + 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){ +static void printList(int indent, void **list) +{ int i; - if (list) for (i=0; list[i]; i++) - printElement(indent, list[i]); + if (list) + for (i = 0; list[i]; i++) + printElement(indent, list[i]); } //////////////////////////////////////////////////////////////////////////////////// @@ -776,146 +932,141 @@ static void printList(int indent, void** list){ /// ///\param md The model description //////////////////////////////////////////////////////////////////////////////////// -void printidf(const char* fmuFilNam, ModelDescription* md) -{ - FILE *fp; - - int i, j, varname, vardes=-1; - void **list; - - fp = fopen("tmp.idf", "w"); - - if (fp == NULL) { - printf("Can't create temporary idf file!\n"); - exit(42); // STL error code: File not open. - } - - ///////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface - fprintf(fp, "ExternalInterface,\n"); - fprintf(fp, " FunctionalMockupUnitImport;\t\t!- Name of External Interface\n"); - - //////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface:FunctionalMockupUnit - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport,\n"); - - fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); - //fprintf(fp, " ,\t\t!- FMU Model Name\n"); - fprintf(fp, " ,\t\t!- FMU Timeout in milli-seconds\n"); - //fprintf(fp, " ,\t\t!- FMU Visible Value\n"); - //fprintf(fp, " ,\t\t!- FMU Interactive Value\n"); - fprintf(fp, " ;\t\t!- FMU LoggingOn\n"); - - list = (void **)md->modelVariables; - if (list) - for(j=0; list[j]; j++) - { - Element* e = (Element*)list[j]; - Enu val = enu_none; - - for(i=0; in; i+=2) - { - if(!strcmp(e->attributes[i], "name")) - varname = i+1; - else if(!strcmp(e->attributes[i], "causality")) - val = checkEnumValue(e->attributes[i+1]); - else if(!strcmp(e->attributes[i], "description")) - vardes = i+1; - } - - ///////////////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface:FunctionalMockupUnitImport:From:Variable - // Define part of ExternalInterface:FunctionalMockupUnitImport:To, - if(val == enu_input || val == enu_output) - { - switch (val) - { - case enu_input: - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:From:Variable,\n"); - fprintf(fp, " ,\t\t!- Output:Variable Index Key Name\n"); - fprintf(fp, " ,\t\t!- Output:Variable Name\n"); - break; - case enu_output: - // User should manually define the To type: Schedule, Actuator, Variable - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:To:,\n"); - fprintf(fp, " ,\t\t!- Name\n"); - break; - default: - break; - } - fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); - fprintf(fp, " ,\t\t!- FMU Instance Name\n"); - switch (val) - { - case enu_input: - fprintf(fp, " %s;\t\t!- FMU Variable Name\n", e->attributes[varname]); - break; - case enu_output: - fprintf(fp, " %s,\t\t!- FMU Variable Name\n", e->attributes[varname]); - break; - default: - break; - } - } - - if(val==enu_output) fprintf(fp, " ;\t\t!- Initial Value\n"); - - - } - fclose(fp); -} - -static void freeList(void** list); - -void freeElement(void* element){ +void printidf(const char *fmuFilNam, ModelDescription *md) +{ + FILE *fp; + + int i, j, varname, vardes = -1; + void **list; + + fp = fopen("tmp.idf", "w"); + + if (fp == NULL) { + printf("Can't create temporary idf file!\n"); + exit(42); // STL error code: File not open. + } + + ///////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface + fprintf(fp, "ExternalInterface,\n"); + fprintf(fp, " FunctionalMockupUnitImport;\t\t!- Name of External Interface\n"); + + //////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface:FunctionalMockupUnit + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport,\n"); + + fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); + // fprintf(fp, " ,\t\t!- FMU Model Name\n"); + fprintf(fp, " ,\t\t!- FMU Timeout in milli-seconds\n"); + // fprintf(fp, " ,\t\t!- FMU Visible Value\n"); + // fprintf(fp, " ,\t\t!- FMU Interactive Value\n"); + fprintf(fp, " ;\t\t!- FMU LoggingOn\n"); + + list = (void **)md->modelVariables; + if (list) + for (j = 0; list[j]; j++) { + Element *e = (Element *)list[j]; + Enu val = enu_none; + + for (i = 0; i < e->n; i += 2) { + if (!strcmp(e->attributes[i], "name")) + varname = i + 1; + else if (!strcmp(e->attributes[i], "causality")) + val = checkEnumValue(e->attributes[i + 1]); + else if (!strcmp(e->attributes[i], "description")) + vardes = i + 1; + } + + ///////////////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface:FunctionalMockupUnitImport:From:Variable + // Define part of ExternalInterface:FunctionalMockupUnitImport:To, + if (val == enu_input || val == enu_output) { + switch (val) { + case enu_input: + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:From:Variable,\n"); + fprintf(fp, " ,\t\t!- Output:Variable Index Key Name\n"); + fprintf(fp, " ,\t\t!- Output:Variable Name\n"); + break; + case enu_output: + // User should manually define the To type: Schedule, Actuator, Variable + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:To:,\n"); + fprintf(fp, " ,\t\t!- Name\n"); + break; + default: + break; + } + fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); + fprintf(fp, " ,\t\t!- FMU Instance Name\n"); + switch (val) { + case enu_input: + fprintf(fp, " %s;\t\t!- FMU Variable Name\n", e->attributes[varname]); + break; + case enu_output: + fprintf(fp, " %s,\t\t!- FMU Variable Name\n", e->attributes[varname]); + break; + default: + break; + } + } + + if (val == enu_output) fprintf(fp, " ;\t\t!- Initial Value\n"); + } + fclose(fp); +} + +static void freeList(void **list); + +void freeElement(void *element) +{ int i; - Element* e = (Element*)element; + Element *e = (Element *)element; if (!e) return; // free attributes - for (i=0; in; i+=2) - free((void*)e->attributes[i+1]); - if (e->attributes) free((void*)e->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: -// Add an empty case here to avoid warnings from -Wall -// The element e gets freed elsewhere, if we free it -// here, we get warnings -//freeElement((void**)(Element*)e); - 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; - } + case astElement: + // Add an empty case here to avoid warnings from -Wall + // The element e gets freed elsewhere, if we free it + // here, we get warnings + // freeElement((void**)(Element*)e); + 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){ +static void freeList(void **list) +{ int i; if (!list) return; - for (i=0; list[i]; i++) + for (i = 0; list[i]; i++) freeElement(list[i]); free(list); } @@ -923,19 +1074,20 @@ static void freeList(void** list){ // ------------------------------------------------------------------------- // Validation - done after parsing to report all errors -ModelDescription* validate(ModelDescription* md) { +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) { - printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv)); - error++; + 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) { + printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv)); + error++; + } } - } if (error) { printf("Error: Found %d error in modelDescription.xml\n", error); return NULL; @@ -946,7 +1098,8 @@ ModelDescription* validate(ModelDescription* md) { // ------------------------------------------------------------------------- // Entry function parse() of the XML parser -static void cleanup(FILE *file) { +static void cleanup(FILE *file) +{ stackFree(stack); stack = NULL; XML_ParserFree(parser); @@ -957,8 +1110,9 @@ static void cleanup(FILE *file) { // 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) { - ModelDescription* md = NULL; +ModelDescription *parse(const char *xmlPath) +{ + ModelDescription *md = NULL; FILE *file; int done = 0; stack = stackNew(100, 10); @@ -967,31 +1121,30 @@ ModelDescription* parse(const char* xmlPath) { if (!checkPointer(parser)) return NULL; // failure XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, handleData); - file = fopen(xmlPath, "rb"); -if (file == NULL) { + file = fopen(xmlPath, "rb"); + if (file == NULL) { printf("Cannot open file '%s'\n", xmlPath); - XML_ParserFree(parser); + XML_ParserFree(parser); return NULL; // failure } while (!done) { size_t n = fread(text, sizeof(char), XMLBUFSIZE, file); -if (n != XMLBUFSIZE) done = 1; - if (!XML_Parse(parser, text, (int)n, done)){ - printf("Parse error in file %s at line %d:\n%s\n", - xmlPath, - (int)XML_GetCurrentLineNumber(parser), - XML_ErrorString(XML_GetErrorCode(parser))); - while (! stackIsEmpty(stack)) md = stackPopFMI(stack); - if (md) freeElement(md); - cleanup(file); - return NULL; // failure + if (n != XMLBUFSIZE) done = 1; + if (!XML_Parse(parser, text, (int)n, done)) { + printf("Parse error in file %s at line %d:\n%s\n", + xmlPath, + (int)XML_GetCurrentLineNumber(parser), + XML_ErrorString(XML_GetErrorCode(parser))); + while (!stackIsEmpty(stack)) + md = stackPopFMI(stack); + if (md) freeElement(md); + cleanup(file); + return NULL; // failure } } md = stackPopFMI(stack); assert(stackIsEmpty(stack)); cleanup(file); - //printElement(1, md); // debug + // printElement(1, md); // debug return validate(md); // success if all refs are valid } - - diff --git a/third_party/FMI/xml_parser_cosim.h b/third_party/FMI/xml_parser_cosim.h index 3a22ed13096..b96e6180f07 100644 --- a/third_party/FMI/xml_parser_cosim.h +++ b/third_party/FMI/xml_parser_cosim.h @@ -37,91 +37,176 @@ extern const char *attNames[SIZEOF_ATT]; extern const char *enuNames[SIZEOF_ENU]; // Elements -typedef enum { - 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 +typedef enum +{ + 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_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 +typedef enum +{ + 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_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 +typedef enum +{ + 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 +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 +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. +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 +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 } 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 +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 +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 { +typedef enum +{ astElement, astListElement, astType, @@ -131,39 +216,39 @@ typedef enum { } AstNodeType; // Possible results when retrieving an attribute value from an element -typedef enum { +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); -int getEnumValue (void* element, Att a, ValueStatus* vs); -void freeElement (void* element); +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); +int getEnumValue(void *element, Att a, ValueStatus *vs); +void freeElement(void *element); // Convenience methods for AST access. To be used afer 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); -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, fmiValueReference vr); +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); +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, fmiValueReference vr); #endif // xml_parser_cosim_h - diff --git a/third_party/FMUParser/fmiFunctions.h b/third_party/FMUParser/fmiFunctions.h index addaef9396b..817c9b2bd11 100644 --- a/third_party/FMUParser/fmiFunctions.h +++ b/third_party/FMUParser/fmiFunctions.h @@ -61,7 +61,7 @@ /* Export fmi functions on Windows */ #ifdef _MSC_VER -#define DllExport __declspec( dllexport ) +#define DllExport __declspec(dllexport) #else #define DllExport #endif @@ -69,84 +69,87 @@ /* Macros to construct the real function name (prepend function name by MODEL_IDENTIFIER + "_") */ -#define fmiPaste(a,b) a ## b -#define fmiPasteB(a,b) fmiPaste(a,b) +#define fmiPaste(a, b) a##b +#define fmiPasteB(a, b) fmiPaste(a, b) #define fmiFullName(name) fmiPasteB(MODEL_IDENTIFIER, name) /*************************************************** Common Functions ****************************************************/ #define fmiGetTypesPlatform fmiFullName(_fmiGetTypesPlatform) -#define fmiGetVersion fmiFullName(_fmiGetVersion) -#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) +#define fmiGetVersion fmiFullName(_fmiGetVersion) +#define fmiSetDebugLogging fmiFullName(_fmiSetDebugLogging) /*Data Exchange*/ -#define fmiSetReal fmiFullName(_fmiSetReal) -#define fmiSetInteger fmiFullName(_fmiSetInteger) -#define fmiSetBoolean fmiFullName(_fmiSetBoolean) -#define fmiSetString fmiFullName(_fmiSetString) +#define fmiSetReal fmiFullName(_fmiSetReal) +#define fmiSetInteger fmiFullName(_fmiSetInteger) +#define fmiSetBoolean fmiFullName(_fmiSetBoolean) +#define fmiSetString fmiFullName(_fmiSetString) -#define fmiGetReal fmiFullName(_fmiGetReal) -#define fmiGetInteger fmiFullName(_fmiGetInteger) -#define fmiGetBoolean fmiFullName(_fmiGetBoolean) -#define fmiGetString fmiFullName(_fmiGetString) +#define fmiGetReal fmiFullName(_fmiGetReal) +#define fmiGetInteger fmiFullName(_fmiGetInteger) +#define fmiGetBoolean fmiFullName(_fmiGetBoolean) +#define fmiGetString fmiFullName(_fmiGetString) /*************************************************** Functions for FMI for Co-Simulation ****************************************************/ -#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) -#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) -#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) -#define fmiResetSlave fmiFullName(_fmiResetSlave) -#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) -#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives) +#define fmiInstantiateSlave fmiFullName(_fmiInstantiateSlave) +#define fmiInitializeSlave fmiFullName(_fmiInitializeSlave) +#define fmiTerminateSlave fmiFullName(_fmiTerminateSlave) +#define fmiResetSlave fmiFullName(_fmiResetSlave) +#define fmiFreeSlaveInstance fmiFullName(_fmiFreeSlaveInstance) +#define fmiSetRealInputDerivatives fmiFullName(_fmiSetRealInputDerivatives) #define fmiGetRealOutputDerivatives fmiFullName(_fmiGetRealOutputDerivatives) -#define fmiDoStep fmiFullName(_fmiDoStep) -#define fmiCancelStep fmiFullName(_fmiCancelStep) -#define fmiGetStatus fmiFullName(_fmiGetStatus) -#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) -#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) -#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) -#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) +#define fmiDoStep fmiFullName(_fmiDoStep) +#define fmiCancelStep fmiFullName(_fmiCancelStep) +#define fmiGetStatus fmiFullName(_fmiGetStatus) +#define fmiGetRealStatus fmiFullName(_fmiGetRealStatus) +#define fmiGetIntegerStatus fmiFullName(_fmiGetIntegerStatus) +#define fmiGetBooleanStatus fmiFullName(_fmiGetBooleanStatus) +#define fmiGetStringStatus fmiFullName(_fmiGetStringStatus) /* Version number */ #define fmiVersion "1.0" /* make sure all compiler use the same alignment policies for structures */ #ifdef WIN32 -#pragma pack(push,8) +#pragma pack(push, 8) #endif - /* Type definitions */ - typedef enum {fmiOK, - fmiWarning, - fmiDiscard, - fmiError, - fmiFatal, - fmiPending} fmiStatus; - - typedef void (*fmiCallbackLogger) (fmiComponent c, fmiString instanceName, fmiStatus status, - fmiString category, fmiString message, ...); - typedef void* (*fmiCallbackAllocateMemory)(size_t nobj, size_t size); - typedef void (*fmiCallbackFreeMemory) (void* obj); - typedef void (*fmiStepFinished) (fmiComponent c, fmiStatus status); - - typedef struct { - fmiCallbackLogger logger; - fmiCallbackAllocateMemory allocateMemory; - fmiCallbackFreeMemory freeMemory; - fmiStepFinished stepFinished; - } fmiCallbackFunctions; - - typedef struct { - fmiBoolean iterationConverged; - fmiBoolean stateValueReferencesChanged; - fmiBoolean stateValuesChanged; - fmiBoolean terminateSimulation; - fmiBoolean upcomingTimeEvent; - fmiReal nextEventTime; - } fmiEventInfo; +typedef enum +{ + fmiOK, + fmiWarning, + fmiDiscard, + fmiError, + fmiFatal, + fmiPending +} fmiStatus; + +typedef void (*fmiCallbackLogger)(fmiComponent c, fmiString instanceName, fmiStatus status, fmiString category, fmiString message, ...); +typedef void *(*fmiCallbackAllocateMemory)(size_t nobj, size_t size); +typedef void (*fmiCallbackFreeMemory)(void *obj); +typedef void (*fmiStepFinished)(fmiComponent c, fmiStatus status); + +typedef struct +{ + fmiCallbackLogger logger; + fmiCallbackAllocateMemory allocateMemory; + fmiCallbackFreeMemory freeMemory; + fmiStepFinished stepFinished; +} fmiCallbackFunctions; + +typedef struct +{ + fmiBoolean iterationConverged; + fmiBoolean stateValueReferencesChanged; + fmiBoolean stateValuesChanged; + fmiBoolean terminateSimulation; + fmiBoolean upcomingTimeEvent; + fmiReal nextEventTime; +} fmiEventInfo; /* reset alignment policy to the one set before reading this file */ #ifdef WIN32 @@ -158,74 +161,62 @@ Common Functions ****************************************************/ /* Inquire version numbers of header files */ - DllExport const char* fmiGetTypesPlatform(); - DllExport const char* fmiGetVersion(); +DllExport const char *fmiGetTypesPlatform(); +DllExport const char *fmiGetVersion(); - DllExport fmiStatus fmiSetDebugLogging (fmiComponent c, fmiBoolean loggingOn); +DllExport fmiStatus fmiSetDebugLogging(fmiComponent c, fmiBoolean loggingOn); /* Data Exchange Functions*/ - DllExport fmiStatus fmiGetReal (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); - DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); - DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); - DllExport fmiStatus fmiGetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); +DllExport fmiStatus fmiGetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); +DllExport fmiStatus fmiGetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); +DllExport fmiStatus fmiGetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); +DllExport fmiStatus fmiGetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); - DllExport fmiStatus fmiSetReal (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); - DllExport fmiStatus fmiSetInteger (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); - DllExport fmiStatus fmiSetBoolean (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); - DllExport fmiStatus fmiSetString (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); +DllExport fmiStatus fmiSetReal(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); +DllExport fmiStatus fmiSetInteger(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); +DllExport fmiStatus fmiSetBoolean(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); +DllExport fmiStatus fmiSetString(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); /*************************************************** Functions for FMI for Co-Simulation ****************************************************/ /* Creation and destruction of slave instances and setting debug status */ - DllExport fmiComponent fmiInstantiateSlave(fmiString instanceName, - fmiString fmuGUID, - fmiString fmuLocation, - fmiString mimeType, - fmiReal timeout, - fmiBoolean visible, - fmiBoolean interactive, - fmiCallbackFunctions functions, - fmiBoolean loggingOn); - - DllExport fmiStatus fmiInitializeSlave(fmiComponent c, - fmiReal tStart, - fmiBoolean StopTimeDefined, - fmiReal tStop); - - DllExport fmiStatus fmiTerminateSlave (fmiComponent c); - DllExport fmiStatus fmiResetSlave (fmiComponent c); - DllExport void fmiFreeSlaveInstance(fmiComponent c); - - DllExport fmiStatus fmiSetRealInputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - const fmiReal value[]); - - DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, - const fmiValueReference vr[], - size_t nvr, - const fmiInteger order[], - fmiReal value[]); - - DllExport fmiStatus fmiCancelStep(fmiComponent c); - DllExport fmiStatus fmiDoStep (fmiComponent c, - fmiReal currentCommunicationPoint, - fmiReal communicationStepSize, - fmiBoolean newStep); - - - typedef enum {fmiDoStepStatus, - fmiPendingStatus, - fmiLastSuccessfulTime} fmiStatusKind; - - DllExport fmiStatus fmiGetStatus (fmiComponent c, const fmiStatusKind s, fmiStatus* value); - DllExport fmiStatus fmiGetRealStatus (fmiComponent c, const fmiStatusKind s, fmiReal* value); - DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger* value); - DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean* value); - DllExport fmiStatus fmiGetStringStatus (fmiComponent c, const fmiStatusKind s, fmiString* value); - +DllExport fmiComponent fmiInstantiateSlave(fmiString instanceName, + fmiString fmuGUID, + fmiString fmuLocation, + fmiString mimeType, + fmiReal timeout, + fmiBoolean visible, + fmiBoolean interactive, + fmiCallbackFunctions functions, + fmiBoolean loggingOn); + +DllExport fmiStatus fmiInitializeSlave(fmiComponent c, fmiReal tStart, fmiBoolean StopTimeDefined, fmiReal tStop); + +DllExport fmiStatus fmiTerminateSlave(fmiComponent c); +DllExport fmiStatus fmiResetSlave(fmiComponent c); +DllExport void fmiFreeSlaveInstance(fmiComponent c); + +DllExport fmiStatus +fmiSetRealInputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], const fmiReal value[]); + +DllExport fmiStatus fmiGetRealOutputDerivatives(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger order[], fmiReal value[]); + +DllExport fmiStatus fmiCancelStep(fmiComponent c); +DllExport fmiStatus fmiDoStep(fmiComponent c, fmiReal currentCommunicationPoint, fmiReal communicationStepSize, fmiBoolean newStep); + +typedef enum +{ + fmiDoStepStatus, + fmiPendingStatus, + fmiLastSuccessfulTime +} fmiStatusKind; + +DllExport fmiStatus fmiGetStatus(fmiComponent c, const fmiStatusKind s, fmiStatus *value); +DllExport fmiStatus fmiGetRealStatus(fmiComponent c, const fmiStatusKind s, fmiReal *value); +DllExport fmiStatus fmiGetIntegerStatus(fmiComponent c, const fmiStatusKind s, fmiInteger *value); +DllExport fmiStatus fmiGetBooleanStatus(fmiComponent c, const fmiStatusKind s, fmiBoolean *value); +DllExport fmiStatus fmiGetStringStatus(fmiComponent c, const fmiStatusKind s, fmiString *value); #endif // fmiFunctions_h diff --git a/third_party/FMUParser/fmiModelTypes.h b/third_party/FMUParser/fmiModelTypes.h index f920b33987c..d966ceadb66 100644 --- a/third_party/FMUParser/fmiModelTypes.h +++ b/third_party/FMUParser/fmiModelTypes.h @@ -77,15 +77,15 @@ // mwetter: added ifndef #ifndef fmiPlatformTypes_h - typedef void* fmiComponent; - typedef unsigned int fmiValueReference; - typedef double fmiReal ; - typedef int fmiInteger; - typedef char fmiBoolean; - typedef const char* fmiString ; +typedef void *fmiComponent; +typedef unsigned int fmiValueReference; +typedef double fmiReal; +typedef int fmiInteger; +typedef char fmiBoolean; +typedef const char *fmiString; /* Values for fmiBoolean */ -#define fmiTrue 1 +#define fmiTrue 1 #define fmiFalse 0 /* Undefined value for fmiValueReference (largest unsigned int value) */ diff --git a/third_party/FMUParser/fmiPlatformTypes.h b/third_party/FMUParser/fmiPlatformTypes.h index c216beae13e..1836466a3d8 100644 --- a/third_party/FMUParser/fmiPlatformTypes.h +++ b/third_party/FMUParser/fmiPlatformTypes.h @@ -58,15 +58,15 @@ */ // mwetter: added ifndef #ifndef fmiModelTypes_h - typedef void* fmiComponent; - typedef unsigned int fmiValueReference; - typedef double fmiReal ; - typedef int fmiInteger; - typedef char fmiBoolean; - typedef const char* fmiString ; +typedef void *fmiComponent; +typedef unsigned int fmiValueReference; +typedef double fmiReal; +typedef int fmiInteger; +typedef char fmiBoolean; +typedef const char *fmiString; /* Values for fmiBoolean */ -#define fmiTrue 1 +#define fmiTrue 1 #define fmiFalse 0 /* Undefined value for fmiValueReference (largest unsigned int value) */ diff --git a/third_party/FMUParser/fmumini.c b/third_party/FMUParser/fmumini.c index 06eb1db804a..871cbd451df 100644 --- a/third_party/FMUParser/fmumini.c +++ b/third_party/FMUParser/fmumini.c @@ -31,38 +31,38 @@ */ #ifndef _WIN32 - #ifndef __USE_FILE_OFFSET64 - #define __USE_FILE_OFFSET64 - #endif - #ifndef __USE_LARGEFILE64 - #define __USE_LARGEFILE64 - #endif - #ifndef _LARGEFILE64_SOURCE - #define _LARGEFILE64_SOURCE - #endif - #ifndef _FILE_OFFSET_BIT - #define _FILE_OFFSET_BIT 64 - #endif +#ifndef __USE_FILE_OFFSET64 +#define __USE_FILE_OFFSET64 +#endif +#ifndef __USE_LARGEFILE64 +#define __USE_LARGEFILE64 +#endif +#ifndef _LARGEFILE64_SOURCE +#define _LARGEFILE64_SOURCE +#endif +#ifndef _FILE_OFFSET_BIT +#define _FILE_OFFSET_BIT 64 +#endif #endif +#include +#include #include #include #include -#include -#include -#include #include +#include #ifdef unix -# include -# include +#include +#include #else -# include -# include +#include +#include #endif -#include #include "util.h" +#include #define CASESENSITIVITY (0) #define WRITEBUFFERSIZE (8192) @@ -84,114 +84,102 @@ if it exists */ - /* change_file_date : change the date/time of a file filename : the filename of the file where date/time must be modified dosdate : the new date at the MSDos format (4 bytes) tmu_date : the SAME new date at the tm_unz format */ -void change_file_date(filename,dosdate,tmu_date) - const char *filename; - uLong dosdate; - tm_unz tmu_date; +void change_file_date(filename, dosdate, tmu_date) const char *filename; +uLong dosdate; +tm_unz tmu_date; { #ifdef _WIN32 - HANDLE hFile; - FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; - - hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, - 0,NULL,OPEN_EXISTING,0,NULL); - GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); - DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); - LocalFileTimeToFileTime(&ftLocal,&ftm); - SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); - CloseHandle(hFile); + HANDLE hFile; + FILETIME ftm, ftLocal, ftCreate, ftLastAcc, ftLastWrite; + + hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GetFileTime(hFile, &ftCreate, &ftLastAcc, &ftLastWrite); + DosDateTimeToFileTime((WORD)(dosdate >> 16), (WORD)dosdate, &ftLocal); + LocalFileTimeToFileTime(&ftLocal, &ftm); + SetFileTime(hFile, &ftm, &ftLastAcc, &ftm); + CloseHandle(hFile); #else #ifdef unix - struct utimbuf ut; - struct tm newdate; - newdate.tm_sec = tmu_date.tm_sec; - newdate.tm_min=tmu_date.tm_min; - newdate.tm_hour=tmu_date.tm_hour; - newdate.tm_mday=tmu_date.tm_mday; - newdate.tm_mon=tmu_date.tm_mon; - if (tmu_date.tm_year > 1900) - newdate.tm_year=tmu_date.tm_year - 1900; - else - newdate.tm_year=tmu_date.tm_year ; - newdate.tm_isdst=-1; - - ut.actime=ut.modtime=mktime(&newdate); - utime(filename,&ut); + struct utimbuf ut; + struct tm newdate; + newdate.tm_sec = tmu_date.tm_sec; + newdate.tm_min = tmu_date.tm_min; + newdate.tm_hour = tmu_date.tm_hour; + newdate.tm_mday = tmu_date.tm_mday; + newdate.tm_mon = tmu_date.tm_mon; + if (tmu_date.tm_year > 1900) + newdate.tm_year = tmu_date.tm_year - 1900; + else + newdate.tm_year = tmu_date.tm_year; + newdate.tm_isdst = -1; + + ut.actime = ut.modtime = mktime(&newdate); + utime(filename, &ut); #endif #endif } - /* mymkdir and change_file_date are not 100 % portable As I don't know well Unix, I wait feedback for the unix portion */ -int mymkdir(dirname) - const char* dirname; +int mymkdir(dirname) const char *dirname; { - int ret=0; + int ret = 0; #ifdef _WIN32 ret = _mkdir(dirname); #else #ifdef unix - ret = mkdir (dirname,0775); + ret = mkdir(dirname, 0775); #endif #endif return ret; } -int makedir (newdir) - char *newdir; +int makedir(newdir) char *newdir; { - char *buffer ; - char *p; - int len = (int)strlen(newdir); - - if (len <= 0) - return 0; + char *buffer; + char *p; + int len = (int)strlen(newdir); - buffer = (char*)malloc(len+1); - if (buffer==NULL) - { - printf("Error allocating memory\n"); - return UNZ_INTERNALERROR; - } - strcpy(buffer,newdir); + if (len <= 0) return 0; - if (buffer[len-1] == '/') { - buffer[len-1] = '\0'; - } - if (mymkdir(buffer) == 0) - { - free(buffer); - return 1; + buffer = (char *)malloc(len + 1); + if (buffer == NULL) { + printf("Error allocating memory\n"); + return UNZ_INTERNALERROR; } + strcpy(buffer, newdir); - p = buffer+1; - while (1) - { - char hold; + if (buffer[len - 1] == '/') { + buffer[len - 1] = '\0'; + } + if (mymkdir(buffer) == 0) { + free(buffer); + return 1; + } - while(*p && *p != '\\' && *p != '/') - p++; - hold = *p; - *p = 0; - if ((mymkdir(buffer) == -1) && (errno == ENOENT)) - { - printf("couldn't create directory %s\n",buffer); - free(buffer); - return 0; + p = buffer + 1; + while (1) { + char hold; + + while (*p && *p != '\\' && *p != '/') + p++; + hold = *p; + *p = 0; + if ((mymkdir(buffer) == -1) && (errno == ENOENT)) { + printf("couldn't create directory %s\n", buffer); + free(buffer); + return 0; } - if (hold == 0) - break; - *p++ = hold; + if (hold == 0) break; + *p++ = hold; } - free(buffer); - return 1; + free(buffer); + return 1; } void do_banner() @@ -202,113 +190,98 @@ void do_banner() void do_help() { - printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ - " -e Extract without pathname (junk paths)\n" \ - " -x Extract with pathname\n" \ - " -v list files\n" \ - " -l list files\n" \ - " -d directory to extract into\n" \ - " -o overwrite files without prompting\n" \ + printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" + " -e Extract without pathname (junk paths)\n" + " -x Extract with pathname\n" + " -v list files\n" + " -l list files\n" + " -d directory to extract into\n" + " -o overwrite files without prompting\n" " -p extract crypted file using password\n\n"); } void Display64BitsSize(ZPOS64_T n, int size_char) { - /* to avoid compatibility problem , we do here the conversion */ - char number[21]; - int offset=19; - int pos_string = 19; - number[20]=0; - for (;;) { - number[offset]=(char)((n%10)+'0'); - if (number[offset] != '0') - pos_string=offset; - n/=10; - if (offset==0) - break; - offset--; - } - { - int size_display_string = 19-pos_string; - while (size_char > size_display_string) - { - size_char--; - printf(" "); - } - } - - printf("%s",&number[pos_string]); + /* to avoid compatibility problem , we do here the conversion */ + char number[21]; + int offset = 19; + int pos_string = 19; + number[20] = 0; + for (;;) { + number[offset] = (char)((n % 10) + '0'); + if (number[offset] != '0') pos_string = offset; + n /= 10; + if (offset == 0) break; + offset--; + } + { + int size_display_string = 19 - pos_string; + while (size_char > size_display_string) { + size_char--; + printf(" "); + } + } + + printf("%s", &number[pos_string]); } -int do_list(uf) - unzFile uf; +int do_list(uf) unzFile uf; { uLong i; unz_global_info64 gi; int err; - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); + err = unzGetGlobalInfo64(uf, &gi); + if (err != UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n", err); printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); - for (i=0;i0) - ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); + if (file_info.uncompressed_size > 0) ratio = (uLong)((file_info.compressed_size * 100) / file_info.uncompressed_size); /* display a '*' if the file is crypted */ - if ((file_info.flag & 1) != 0) - charCrypt='*'; - - if (file_info.compression_method==0) - string_method="Stored"; - else - if (file_info.compression_method==Z_DEFLATED) - { - uInt iLevel=(uInt)((file_info.flag & 0x6)/2); - if (iLevel==0) - string_method="Defl:N"; - else if (iLevel==1) - string_method="Defl:X"; - else if ((iLevel==2) || (iLevel==3)) - string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ - } - else - if (file_info.compression_method==Z_BZIP2ED) - { - string_method="BZip2 "; - } - else - string_method="Unkn. "; - - Display64BitsSize(file_info.uncompressed_size,7); - printf(" %6s%c",string_method,charCrypt); - Display64BitsSize(file_info.compressed_size,7); + if ((file_info.flag & 1) != 0) charCrypt = '*'; + + if (file_info.compression_method == 0) + string_method = "Stored"; + else if (file_info.compression_method == Z_DEFLATED) { + uInt iLevel = (uInt)((file_info.flag & 0x6) / 2); + if (iLevel == 0) + string_method = "Defl:N"; + else if (iLevel == 1) + string_method = "Defl:X"; + else if ((iLevel == 2) || (iLevel == 3)) + string_method = "Defl:F"; /* 2:fast , 3 : extra fast*/ + } else if (file_info.compression_method == Z_BZIP2ED) { + string_method = "BZip2 "; + } else + string_method = "Unkn. "; + + Display64BitsSize(file_info.uncompressed_size, 7); + printf(" %6s%c", string_method, charCrypt); + Display64BitsSize(file_info.compressed_size, 7); printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", - ratio, - (uLong)file_info.tmu_date.tm_mon + 1, - (uLong)file_info.tmu_date.tm_mday, - (uLong)file_info.tmu_date.tm_year % 100, - (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, - (uLong)file_info.crc,filename_inzip); - if ((i+1)='a') && (rep<='z')) - rep -= 0x20; - } - while ((rep!='Y') && (rep!='N') && (rep!='A')); + rep = answer[0]; + if ((rep >= 'a') && (rep <= 'z')) rep -= 0x20; + } while ((rep != 'Y') && (rep != 'N') && (rep != 'A')); } - if (rep == 'N') - skip = 1; + if (rep == 'N') skip = 1; - if (rep == 'A') - *popt_overwrite=1; + if (rep == 'A') *popt_overwrite = 1; } - if ((skip==0) && (err==UNZ_OK)) - { - fout=fopen64(write_filename,"wb"); + if ((skip == 0) && (err == UNZ_OK)) { + fout = fopen64(write_filename, "wb"); /* some zipfile don't contain directory alone before file */ - if ((fout==NULL) && ((*popt_extract_without_path)==0) && - (filename_withoutpath!=(char*)filename_inzip)) - { - char c=*(filename_withoutpath-1); - *(filename_withoutpath-1)='\0'; + if ((fout == NULL) && ((*popt_extract_without_path) == 0) && (filename_withoutpath != (char *)filename_inzip)) { + char c = *(filename_withoutpath - 1); + *(filename_withoutpath - 1) = '\0'; makedir(write_filename); - *(filename_withoutpath-1)=c; - fout=fopen64(write_filename,"wb"); + *(filename_withoutpath - 1) = c; + fout = fopen64(write_filename, "wb"); } - if (fout==NULL) - { - printf("error opening %s\n",write_filename); + if (fout == NULL) { + printf("error opening %s\n", write_filename); } } - if (fout!=NULL) - { - //printf(" extracting: %s\n",write_filename); + if (fout != NULL) { + // printf(" extracting: %s\n",write_filename); - do - { - err = unzReadCurrentFile(uf,buf,size_buf); - if (err<0) - { - printf("error %d with zipfile in unzReadCurrentFile\n",err); + do { + err = unzReadCurrentFile(uf, buf, size_buf); + if (err < 0) { + printf("error %d with zipfile in unzReadCurrentFile\n", err); break; } - if (err>0) - if (fwrite(buf,err,1,fout)!=1) - { + if (err > 0) + if (fwrite(buf, err, 1, fout) != 1) { printf("error in writing extracted file\n"); - err=UNZ_ERRNO; + err = UNZ_ERRNO; break; } - } - while (err>0); - if (fout) - fclose(fout); + } while (err > 0); + if (fout) fclose(fout); - if (err==0) - change_file_date(write_filename,file_info.dosDate, - file_info.tmu_date); + if (err == 0) change_file_date(write_filename, file_info.dosDate, file_info.tmu_date); } - if (err==UNZ_OK) - { - err = unzCloseCurrentFile (uf); - if (err!=UNZ_OK) - { - printf("error %d with zipfile in unzCloseCurrentFile\n",err); + if (err == UNZ_OK) { + err = unzCloseCurrentFile(uf); + if (err != UNZ_OK) { + printf("error %d with zipfile in unzCloseCurrentFile\n", err); } - } - else + } else unzCloseCurrentFile(uf); /* don't lose the error */ } @@ -481,35 +419,25 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password) return err; } - -int do_extract(uf,opt_extract_without_path,opt_overwrite,password) - unzFile uf; - int opt_extract_without_path; - int opt_overwrite; - const char* password; +int do_extract(uf, opt_extract_without_path, opt_overwrite, password) unzFile uf; +int opt_extract_without_path; +int opt_overwrite; +const char *password; { uLong i; unz_global_info64 gi; int err; - FILE* fout=NULL; - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); + err = unzGetGlobalInfo64(uf, &gi); + if (err != UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n", err); - for (i=0;i #endif -#define XML_FILE "modelDescription.xml" +#define XML_FILE "modelDescription.xml" -FMU fmu; // FMU to parse +FMU fmu; // FMU to parse /////////////////////////////////////////////////////////////////////////// /// Call the parser and save the information in fmu.modelDescription @@ -38,101 +38,103 @@ FMU fmu; // FMU to parse ///\param tmpPat Temporary path of the fmu file ///\return 0 if no error occurred /////////////////////////////////////////////////////////////////////////// -int callparser(const char* fmuFilNam, const char* tmpPat){ - size_t length; - char* xmlPat; - char* filNam, *tmp, *ext; - - // Get the model description - xmlPat = calloc(sizeof(char), strlen(fmuFilNam) + strlen(XML_FILE)-1); - printfDebug("fmuFilNam is \"%s\"\n", fmuFilNam); - printfDebug("Start to parse model description file\n", xmlPat); - sprintf(xmlPat, "%s%s%s", tmpPat, PATH_SEP, XML_FILE); - - fmu.modelDescription = parse(xmlPat); - printfDebug("Parsed model description file: \"%s\"\n", xmlPat); +int callparser(const char *fmuFilNam, const char *tmpPat) +{ + size_t length; + char *xmlPat; + char *filNam, *tmp, *ext; + + // Get the model description + xmlPat = (char *)calloc(strlen(fmuFilNam) + strlen(XML_FILE) + strlen(PATH_SEP) + 1, sizeof(char)); + printfDebug("fmuFilNam is \"%s\"\n", fmuFilNam); + sprintf(xmlPat, "%s%s%s", tmpPat, PATH_SEP, XML_FILE); + printfDebug("Start to parse model description file: \"%s\".\n", xmlPat); + + fmu.modelDescription = parse(xmlPat); + printfDebug("Parsed model description file: \"%s\"\n", xmlPat); + + if (fmu.modelDescription == NULL) { + printfError("Fail to parse xml file \"%s\".\n", xmlPat); + free(xmlPat); + return -1; + } - if (fmu.modelDescription==NULL){ - printfError("Fail to parse xml file \"%s\".\n", xmlPat); free(xmlPat); - return -1; - } - length = strlen(fmuFilNam); - tmp = malloc(length*sizeof(char)); - strcpy(tmp, fmuFilNam); + length = strlen(fmuFilNam); + tmp = (char *)malloc((length+1) * sizeof(char)); + strcpy(tmp, fmuFilNam); #ifdef _MSC_VER // Command in windows - filNam = malloc(length*sizeof(char)); - if(filNam == NULL) { - printError("Can not allocate memory for filName\n"); - free(tmp); - return -1; - } + filNam = (char *)malloc(length * sizeof(char)); + if (filNam == NULL) { + printError("Can not allocate memory for filName\n"); + free(tmp); + return -1; + } - ext = malloc(length*sizeof(char)); - if(ext == NULL) { - printError("Can not allocate memory for ext\n"); - free(filNam); - free(tmp); - return -1; - } + ext = (char *)malloc(length * sizeof(char)); + if (ext == NULL) { + printError("Can not allocate memory for ext\n"); + free(filNam); + free(tmp); + return -1; + } - _splitpath(tmp, NULL, NULL, filNam, ext); - filNam = strcat(filNam, ext); -#else // Command in linux - filNam = basename(tmp); + _splitpath(tmp, NULL, NULL, filNam, ext); + filNam = strcat(filNam, ext); +#else // Command in linux + filNam = basename(tmp); #endif - printidf(filNam, fmu.modelDescription); - printfDebug("***** Model description is \"%s\".\n", getModelIdentifier(fmu.modelDescription)); + printidf(filNam, fmu.modelDescription); + printfDebug("***** Model description is \"%s\".\n", getModelIdentifier(fmu.modelDescription)); - // Clean up memory - //free(xmlPat); - //free(tmp); - //free(filNam); - //free(ext); - return 0; + // Clean up memory + // free(xmlPat); // Done above + free(tmp); + free(filNam); + free(ext); + return 0; } - - ////////////////////////////////////////////////////////////////////// /// Print help information ///////////////////////////////////////////////////////////////////// -void help(){ - - printf("NAME\n"); - printf("\tparser - parse xml file\n\n"); - printf("SYNOPSIS\n"); - printf("\tparser OPTION...FMUFILE...[-name objNam]\n\n"); - printf("DESCRIPION\n"); - printf("\tThe parser parses informaiton in modelDescription.xml file in functional mock-up unit for co-simulation.\n\n"); - printf("OPTION\n"); - printf("\t-d, --delete\n"); - printf("\t\tdelete the unpacked fmu folder\n"); - printf("\t-h, --help\n"); - printf("\t\tprint help information\n"); - printf("\t-p, --printidf\n"); - printf("\t\tprint temporary IDF file for Energyplus\n"); - printf("\t-u, --unpack\n"); - printf("\t\tunpack the FMU\n"); - printf("\t-v, --verbose\n"); - printf("\t\tprint debug information. It is the only option that can combine with other options.\n"); - printf("OTHERS\n"); - printf("\t-n, --name\n"); - printf("\t\textract the fmu in folder objNam. The default folder name is fmu's name without the \".fmu\".\n\n"); - printf("EXAMPLE\n"); - printf("\tTo generate a temporary IDF file from a fmu named havc.fmu in Linux\n"); - printf("\t\tparser -p hvac.fmu\n\n"); - printf("\tTo unpack the fmu havc.fmu in a folder called MyFMU in linux\n"); - printf("\t\tparser -u havc.fmu -n MyFMU\n"); - printf("AUTHOR\n"); - printf("\tWangda Zuo, Thierry S. Nouidui, Michael Wetter @ Lawrence Berkeley National Laboratory\n"); - printf("LICENSE\n"); - printf("\tCopyright (c) 2012, The Regents of the University of California, through Lawrence Berkeley National Laboratory subject to receipt of any required approvals from the U.S. Dept. of Energy. All rights reserved.\n"); +void help() +{ + + printf("NAME\n"); + printf("\tparser - parse xml file\n\n"); + printf("SYNOPSIS\n"); + printf("\tparser OPTION...FMUFILE...[-name objNam]\n\n"); + printf("DESCRIPION\n"); + printf("\tThe parser parses informaiton in modelDescription.xml file in functional mock-up unit for co-simulation.\n\n"); + printf("OPTION\n"); + printf("\t-d, --delete\n"); + printf("\t\tdelete the unpacked fmu folder\n"); + printf("\t-h, --help\n"); + printf("\t\tprint help information\n"); + printf("\t-p, --printidf\n"); + printf("\t\tprint temporary IDF file for Energyplus\n"); + printf("\t-u, --unpack\n"); + printf("\t\tunpack the FMU\n"); + printf("\t-v, --verbose\n"); + printf("\t\tprint debug information. It is the only option that can combine with other options.\n"); + printf("OTHERS\n"); + printf("\t-n, --name\n"); + printf("\t\textract the fmu in folder objNam. The default folder name is fmu's name without the \".fmu\".\n\n"); + printf("EXAMPLE\n"); + printf("\tTo generate a temporary IDF file from a fmu named havc.fmu in Linux\n"); + printf("\t\tparser -p hvac.fmu\n\n"); + printf("\tTo unpack the fmu havc.fmu in a folder called MyFMU in linux\n"); + printf("\t\tparser -u havc.fmu -n MyFMU\n"); + printf("AUTHOR\n"); + printf("\tWangda Zuo, Thierry S. Nouidui, Michael Wetter @ Lawrence Berkeley National Laboratory\n"); + printf("LICENSE\n"); + printf("\tCopyright (c) 2012, The Regents of the University of California, through Lawrence Berkeley National Laboratory subject to receipt of " + "any required approvals from the U.S. Dept. of Energy. All rights reserved.\n"); } - ////////////////////////////////////////////////////////////////////////////////// /// Main routine of parser /// @@ -140,190 +142,179 @@ void help(){ ///\param argv Arguments ///\return 0 if no error occurred ////////////////////////////////////////////////////////////////////////////////// -int main(int argc, char* argv[]){ - int i; - const char *fmuFilNam; - char *tmpPat=NULL; - char *objNam=NULL; - option opt; - size_t length = 0; - int nam = 0; - int optNum = 0; - - printDebug("New Line:\n"); - - // Read command line arguments - for(i = 1; i < argc; i++) { - if (strcmp(argv[i], "--delete") == 0 || strcmp(argv[i], "-d") == 0) { - opt = opt_delete; - optNum++; - printDebug("Get option: delete"); - } - else if (strcmp(argv[i], "--printidf") == 0 || strcmp(argv[i], "-p") == 0) { - opt = opt_printidf; - optNum++; - printDebug("Get option: printidf"); - } - else if (strcmp(argv[i], "--unpack") == 0 || strcmp(argv[i], "-u") == 0) { - opt = opt_unpack; - optNum++; - printDebug("Get option: unpack"); - } - else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { - opt = opt_help; - optNum++; - printDebug("Get option: help"); +int main(int argc, char *argv[]) +{ + int i; + const char *fmuFilNam; + char *tmpPat = NULL; + char *objNam = NULL; + option opt; + size_t length = 0; + int nam = 0; + int optNum = 0; + + printDebug("New Line:\n"); + + // Read command line arguments + for (i = 1; i < argc; i++) { + if (strcmp(argv[i], "--delete") == 0 || strcmp(argv[i], "-d") == 0) { + opt = opt_delete; + optNum++; + printDebug("Get option: delete"); + } else if (strcmp(argv[i], "--printidf") == 0 || strcmp(argv[i], "-p") == 0) { + opt = opt_printidf; + optNum++; + printDebug("Get option: printidf"); + } else if (strcmp(argv[i], "--unpack") == 0 || strcmp(argv[i], "-u") == 0) { + opt = opt_unpack; + optNum++; + printDebug("Get option: unpack"); + } else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { + opt = opt_help; + optNum++; + printDebug("Get option: help"); + } else if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) { + setDebug(); + printDebug("Get option: verbose"); + } else if (strcmp(argv[i], "--name") == 0 || strcmp(argv[i], "-n") == 0) { + i++; + nam = 1; + if (argv[i] != NULL) + objNam = argv[i]; + else { + printError("with option -n, objNam is needed."); + return -1; + } + printDebug("Get option: name"); + } else if (strstr(argv[i], ".fmu") != NULL) + fmuFilNam = argv[i]; + else + printf("Warning: Ingore unrecognized input \"%s\"\n", argv[i]); } - else if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) { - setDebug(); - printDebug("Get option: verbose"); - } - else if (strcmp(argv[i], "--name") == 0 || strcmp(argv[i], "-n") == 0) { - i++; nam = 1; - if(argv[i] != NULL) - objNam = argv[i]; - else { - printError("with option -n, objNam is needed."); + + if (optNum == 0) { + if (IS_WINDOWS) { + printError("Missing option: parser.exe option [argument]"); + printf("For help, use: parser.exe -h \n"); + } else { + printError("Missing option: parser option [argument]"); + printf("For help, use: parser -h \n"); + } return -1; - } - printDebug("Get option: name"); } - else if (strstr(argv[i], ".fmu") != NULL) - fmuFilNam = argv[i]; - else - printf("Warning: Ingore unrecognized input \"%s\"\n", argv[i]); - } - if (optNum == 0) { - if (IS_WINDOWS) { - printError("Missing option: parser.exe option [argument]"); - printf("For help, use: parser.exe -h \n"); - } - else { - printError("Missing option: parser option [argument]"); - printf("For help, use: parser -h \n"); + if (optNum > 1) { + printError("Can not use more than 1 option at the same time except \"-u\"."); + if (IS_WINDOWS) { + printf("For help, use: parser.exe -h \n"); + } else { + printf("For help, use: parser -h \n"); + } + return -1; } - return -1; - } - if (optNum > 1) { - printError("Can not use more than 1 option at the same time except \"-u\"."); - if (IS_WINDOWS) { - printf("For help, use: parser.exe -h \n"); - } - else { - printf("For help, use: parser -h \n"); - } - return -1; - } + if (fmuFilNam == NULL && opt != opt_help) { + switch (opt) { + case opt_printidf: + case opt_unpack: + printError("No FMU file name is given.\n"); + break; + case opt_delete: + printError("No FMU folder is given.\n"); + break; + } - if(fmuFilNam == NULL && opt != opt_help) { - switch (opt) { - case opt_printidf: - case opt_unpack: - printError("No FMU file name is given.\n"); - break; - case opt_delete: - printError("No FMU folder is given.\n"); break; - } + if (IS_WINDOWS) { + printf("Correct usage: parser.exe option [argument] \n"); + printf("For help information, use: parser.exe -h \n"); + } else { + printf("Correct usage: parser option [argument] \n"); + printf("For help information, use: parser -h \n"); + } - if (IS_WINDOWS) { - printf("Correct usage: parser.exe option [argument] \n"); - printf("For help information, use: parser.exe -h \n"); - } - else { - printf("Correct usage: parser option [argument] \n"); - printf("For help information, use: parser -h \n"); + return -1; + } else { + printfDebug("FMU file/folder name is \"%s\".\n", fmuFilNam); } - return -1; - } - else - printfDebug("FMU file/folder name is \"%s\".\n", fmuFilNam); - - - - // Check command line arguments - switch (opt){ - case opt_printidf: + // Check command line arguments + switch (opt) { + case opt_printidf: case opt_unpack: case opt_delete: - if(nam == 0){ - length = strlen(fmuFilNam)-4; - if(length<0) { - printError("Cannot get correct length of fmu file name"); - return -1; - } - - objNam = calloc((length+1), sizeof(char)); - // Copy the fmufilNam without extension as objNam - if(strncpy(objNam, fmuFilNam, length)==NULL) { - printError("Can not get name \"objNam\" for new folder.\n"); - free(objNam); - return -1; - } - - if(strcat(objNam, "\0")==NULL) { - printError("Can not add ending for objNam.\n"); - free(objNam); - return -1; - } - printfDebug("objNam = \"%s\"\n", objNam); - } - else - length = strlen(objNam); - break; + if (nam == 0) { + length = strlen(fmuFilNam) - 4; + if (length < 0) { + printError("Cannot get correct length of fmu file name"); + return -1; + } + + objNam = (char *)calloc((length + 1), sizeof(char)); + // Copy the fmufilNam without extension as objNam + if (memcpy(objNam, fmuFilNam, length) == NULL) { + printError("Can not get name \"objNam\" for new folder.\n"); + free(objNam); + return -1; + } + + // This is pretty useless as calloc will initialize to 0 (which is in effect the null-terminator) + if (strcat(objNam, "\0") == NULL) { + printError("Can not add ending for objNam.\n"); + free(objNam); + return -1; + } + printfDebug("objNam = \"%s\"\n", objNam); + } else + length = strlen(objNam); + break; case opt_help: - help(); - return 0; - default: - printError("Missing options: --delete | -d | --printidf | -p | --unpack | -u| --verbose | -v \n"); - return -1; - } - - printDebug("Get length of file name"); - // Define the temporary folder - tmpPat = getTmpPath(objNam, length); - if(tmpPat == NULL){ - printError("Fail to allocate memory for temp dir.\n"); - return -1; + help(); + return 0; + default: + printError("Missing options: --delete | -d | --printidf | -p | --unpack | -u| --verbose | -v \n"); + return -1; } - printfDebug("Received tmpPat \"%s\".\n", tmpPat); - - // Act according to the option - switch (opt) - { - case opt_delete: - if(delete(objNam)!= 0){ - printfError("Fail to delete \"%s\".\n", objNam); - return -1; - } - else - printfDebug("Successfully deleted the temporary folder \"%s\".\n", objNam); - break; - case opt_unpack: - case opt_printidf: - // Unpack: Common part for unpack and printidf - if(unpackminizip(fmuFilNam, tmpPat)!= 0){ - printfError("Fail to unpack \"%s\".\n", fmuFilNam); + printDebug("Get length of file name"); + // Define the temporary folder + tmpPat = getTmpPath(objNam, length); + if (tmpPat == NULL) { + printError("Fail to allocate memory for temp dir.\n"); return -1; - } - else - printDebug("Successfully unpacked the fmu.\n"); + } - // Parser: Additional part for printidf - if (opt == opt_printidf) { - if ( callparser(fmuFilNam, tmpPat) != 0 ){ - printfError("Fail to print the idf file from \"%s\".\n", fmuFilNam); - return -1; + printfDebug("Received tmpPat \"%s\".\n", tmpPat); + + // Act according to the option + switch (opt) { + case opt_delete: + if (delete (objNam) != 0) { + printfError("Fail to delete \"%s\".\n", objNam); + return -1; + } else + printfDebug("Successfully deleted the temporary folder \"%s\".\n", objNam); + break; + case opt_unpack: + case opt_printidf: + // Unpack: Common part for unpack and printidf + if (unpackminizip(fmuFilNam, tmpPat) != 0) { + printfError("Fail to unpack \"%s\".\n", fmuFilNam); + return -1; + } else + printDebug("Successfully unpacked the fmu.\n"); + + // Parser: Additional part for printidf + if (opt == opt_printidf) { + if (callparser(fmuFilNam, tmpPat) != 0) { + printfError("Fail to print the idf file from \"%s\".\n", fmuFilNam); + return -1; + } else + printDebug("Successfully printed the idf file.\n"); } - else printDebug("Successfully printed the idf file.\n"); - } - break; - } + break; + } - free(objNam); - free(tmpPat); - return 0; + free(objNam); + free(tmpPat); + return 0; } diff --git a/third_party/FMUParser/parser.h b/third_party/FMUParser/parser.h index 634be885958..7371fd346a1 100644 --- a/third_party/FMUParser/parser.h +++ b/third_party/FMUParser/parser.h @@ -34,11 +34,10 @@ #include // for creating dirs on Linux #endif -#include "fmiModelTypes.h" #include "fmiFunctions.h" +#include "fmiModelTypes.h" #include "xml_parser_cosim.h" - FILE *f1 = NULL; FILE *fmuFil = NULL; /// FMU file name @@ -48,40 +47,45 @@ FILE *fmuFil = NULL; /// FMU file name #define PATH_SEP "/" #endif -#define true 1 +#define true 1 #define false 0 -typedef const char* (*fGetModelTypesPlatform)(); -typedef const char* (*fGetVersion)(); +typedef const char *(*fGetModelTypesPlatform)(); +typedef const char *(*fGetVersion)(); typedef fmiComponent (*fInstantiateModel)(fmiString instanceName, fmiString GUID, fmiCallbackFunctions functions, fmiBoolean loggingOn); -typedef void (*fFreeModelInstance) (fmiComponent c); -typedef fmiStatus (*fSetDebugLogging) (fmiComponent c, fmiBoolean loggingOn); -typedef fmiStatus (*fSetTime) (fmiComponent c, fmiReal time); +typedef void (*fFreeModelInstance)(fmiComponent c); +typedef fmiStatus (*fSetDebugLogging)(fmiComponent c, fmiBoolean loggingOn); +typedef fmiStatus (*fSetTime)(fmiComponent c, fmiReal time); typedef fmiStatus (*fSetContinuousStates)(fmiComponent c, const fmiReal x[], size_t nx); -typedef fmiStatus (*fCompletedIntegratorStep)(fmiComponent c, fmiBoolean* callEventUpdate); -typedef fmiStatus (*fSetReal) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); +typedef fmiStatus (*fCompletedIntegratorStep)(fmiComponent c, fmiBoolean *callEventUpdate); +typedef fmiStatus (*fSetReal)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiReal value[]); typedef fmiStatus (*fSetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiInteger value[]); typedef fmiStatus (*fSetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiBoolean value[]); -typedef fmiStatus (*fSetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); -typedef fmiStatus (*fInitialize)(fmiComponent c, fmiBoolean toleranceControlled, - fmiReal relativeTolerance, fmiEventInfo* eventInfo); -typedef fmiStatus (*fGetDerivatives) (fmiComponent c, fmiReal derivatives[] , size_t nx); +typedef fmiStatus (*fSetString)(fmiComponent c, const fmiValueReference vr[], size_t nvr, const fmiString value[]); +typedef fmiStatus (*fInitialize)(fmiComponent c, fmiBoolean toleranceControlled, fmiReal relativeTolerance, fmiEventInfo *eventInfo); +typedef fmiStatus (*fGetDerivatives)(fmiComponent c, fmiReal derivatives[], size_t nx); typedef fmiStatus (*fGetEventIndicators)(fmiComponent c, fmiReal eventIndicators[], size_t ni); -typedef fmiStatus (*fGetReal) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); +typedef fmiStatus (*fGetReal)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiReal value[]); typedef fmiStatus (*fGetInteger)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiInteger value[]); typedef fmiStatus (*fGetBoolean)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiBoolean value[]); -typedef fmiStatus (*fGetString) (fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); -typedef fmiStatus (*fEventUpdate) (fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo* eventInfo); -typedef fmiStatus (*fGetContinuousStates) (fmiComponent c, fmiReal states[], size_t nx); +typedef fmiStatus (*fGetString)(fmiComponent c, const fmiValueReference vr[], size_t nvr, fmiString value[]); +typedef fmiStatus (*fEventUpdate)(fmiComponent c, fmiBoolean intermediateResults, fmiEventInfo *eventInfo); +typedef fmiStatus (*fGetContinuousStates)(fmiComponent c, fmiReal states[], size_t nx); typedef fmiStatus (*fGetNominalContinuousStates)(fmiComponent c, fmiReal x_nominal[], size_t nx); -typedef fmiStatus (*fGetStateValueReferences) (fmiComponent c, fmiValueReference vrx[], size_t nx); -typedef fmiStatus (*fTerminate) (fmiComponent c); +typedef fmiStatus (*fGetStateValueReferences)(fmiComponent c, fmiValueReference vrx[], size_t nx); +typedef fmiStatus (*fTerminate)(fmiComponent c); -typedef enum {opt_printidf, opt_delete, opt_unpack, opt_help} option; +typedef enum +{ + opt_printidf, + opt_delete, + opt_unpack, + opt_help +} option; - -typedef struct { - ModelDescription* modelDescription; +typedef struct +{ + ModelDescription *modelDescription; HANDLE dllHandle; fGetModelTypesPlatform getModelTypesPlatform; fGetVersion getVersion; @@ -111,7 +115,6 @@ typedef struct { #endif // _MAIN_H_ -int callparser(const char* fmuFilNam, const char* tmpPat); +int callparser(const char *fmuFilNam, const char *tmpPat); void help(); - diff --git a/third_party/FMUParser/stack.c b/third_party/FMUParser/stack.c index 8a2d72be8c8..7a5cd9b67d4 100644 --- a/third_party/FMUParser/stack.c +++ b/third_party/FMUParser/stack.c @@ -1,16 +1,17 @@ -/* ------------------------------------------------------------------------- +/* ------------------------------------------------------------------------- * stack.c - * A stack of pointers. - * Copyright 2010 QTronic GmbH. All rights reserved. - * -------------------------------------------------------------------------*/ + * A stack of pointers. + * Copyright 2010 QTronic GmbH. All rights reserved. + * -------------------------------------------------------------------------*/ -#include +#include "stack.h" #include #include -#include "stack.h" +#include -Stack* stackNew(int initialSize, int inc){ - Stack* s = (Stack*)malloc(sizeof(Stack)); +Stack *stackNew(int initialSize, int inc) +{ + Stack *s = (Stack *)malloc(sizeof(Stack)); s->stack = NULL; s->stackSize = 0; s->stackPos = -1; @@ -19,17 +20,19 @@ Stack* stackNew(int initialSize, int inc){ return s; } -int stackIsEmpty(Stack* s) { +int stackIsEmpty(Stack *s) +{ return s->stackPos == -1; } // add an element to stack and grow stack if required // returns 1 to indicate success and 0 for error -int stackPush(Stack* s, void* e) { +int stackPush(Stack *s, void *e) +{ s->stackPos++; - if (s->stackPos==s->stackSize){ - s->stackSize += (s->stack ? s->inc: s->initialSize); - s->stack = (void**) realloc(s->stack, s->stackSize * sizeof(void*)); + if (s->stackPos == s->stackSize) { + s->stackSize += (s->stack ? s->inc : s->initialSize); + s->stack = (void **)realloc(s->stack, s->stackSize * sizeof(void *)); if (!s->stack) return 0; // error; } s->stack[s->stackPos] = e; @@ -38,48 +41,51 @@ int stackPush(Stack* s, void* e) { // return top element (possibly NULL), if stack not empty // runtime error if stack is empty -void* stackPeek(Stack* s){ +void *stackPeek(Stack *s) +{ assert(!stackIsEmpty(s)); return s->stack[s->stackPos]; } // remove top element (possibly NULL) from stack and return it // runtime error if stack is empty -void* stackPop(Stack* s){ +void *stackPop(Stack *s) +{ assert(!stackIsEmpty(s)); return s->stack[s->stackPos--]; } -// return the last n elements as null terminated array, +// return the last n elements as null terminated array, // or NULL if memory allocation fails -void** stackLastPopedAsArray0(Stack* s, int n){ +void **stackLastPopedAsArray0(Stack *s, int n) +{ int i; - void** array = (void**)malloc((n + 1)*sizeof(void*)); - if (! array) return NULL; // failure - for (i=0; istack[i+ s->stackPos + 1]; + void **array = (void **)malloc((n + 1) * sizeof(void *)); + if (!array) return NULL; // failure + for (i = 0; i < n; i++) { + array[i] = s->stack[i + s->stackPos + 1]; } - array[n]=NULL; // terminating NULL + array[n] = NULL; // terminating NULL return array; } // return stack as possibly empty array, or NULL if memory allocation fails // On sucessful return, the stack is empty. -void** stackPopAllAsArray(Stack* s, int *size) { +void **stackPopAllAsArray(Stack *s, int *size) +{ int i; - void** array = (void**)malloc((s->stackPos + 1)*sizeof(void*)); - if (! array) return NULL; // failure + void **array = (void **)malloc((s->stackPos + 1) * sizeof(void *)); + if (!array) return NULL; // failure *size = s->stackPos + 1; - for (i=0; i<*size; i++) + for (i = 0; i < *size; i++) array[i] = s->stack[i]; s->stackPos = -1; - return array; + return array; } // release the given stack -void stackFree(Stack* s){ +void stackFree(Stack *s) +{ if (s->stack) free(s->stack); free(s); } - - diff --git a/third_party/FMUParser/stack.h b/third_party/FMUParser/stack.h index 527404a604a..6d46e13d2a6 100644 --- a/third_party/FMUParser/stack.h +++ b/third_party/FMUParser/stack.h @@ -1,28 +1,28 @@ -/* ------------------------------------------------------------------------- +/* ------------------------------------------------------------------------- * stack.c - * A stack of pointers. - * Copyright 2010 QTronic GmbH. All rights reserved. - * -------------------------------------------------------------------------*/ + * A stack of pointers. + * Copyright 2010 QTronic GmbH. All rights reserved. + * -------------------------------------------------------------------------*/ #ifndef STACK_H #define STACK_H -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 +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); +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); #endif // STACK_H - diff --git a/third_party/FMUParser/util.c b/third_party/FMUParser/util.c index a3b634ae2e3..5f0e8a447fd 100644 --- a/third_party/FMUParser/util.c +++ b/third_party/FMUParser/util.c @@ -19,14 +19,14 @@ /// All rights reserved. /////////////////////////////////////////////////////// +#include "util.h" +#include "fmumini.h" #include #include #include #include -#include "util.h" -#include "fmumini.h" -int debug = 0; // Control for debug information +int debug = 0; // Control for debug information /////////////////////////////////////////////////////////////////////////////// /// Translate the double variable to string variable. @@ -34,8 +34,9 @@ int debug = 0; // Control for debug information ///\param buffer String variable. ///\param r Double variable. /////////////////////////////////////////////////////////////////////////////// -void doubleToCommaString(char* buffer, double r){ - char* comma; +void doubleToCommaString(char *buffer, double r) +{ + char *comma; sprintf(buffer, "%.16g", r); comma = strchr(buffer, '.'); if (comma) *comma = ','; @@ -47,40 +48,38 @@ void doubleToCommaString(char* buffer, double r){ ///\param tmpPat The path of the tmeporary folder ///\return 0 if no error occurred ///////////////////////////////////////////////////////////////////////// -int delete(char* tmpPat){ - int version = 0; - char* cmd; - char* filenames; - struct stat st; - - // Ceck if the folder present - if(stat(tmpPat,&st) != 0){ - printfError("Folder \"%s\" is not existing.\n", tmpPat); - return -1; - } - - cmd = calloc(sizeof(char), strlen(tmpPat) + 20); - if (cmd == NULL){ - printfError("Fail to allocate memory for cmd.\n", tmpPat); - return -1; - } - - if (IS_WINDOWS) - sprintf(cmd, "rd \"%s\" /S/Q", tmpPat); // Command in windows - else - sprintf(cmd, "rm -r \"%s\"", tmpPat); // Command in Linux - - - printfDebug("Generated cmd: \"%s\".\n", cmd); - if ( system(cmd) != 0 ){ - //if(rmdir(tmpPat) != 0) - printError("Fail to delete the temporary files"); - free(cmd); - return -1; - } - printDebug("Deleted temporary files"); - free(cmd); - return 0; +int delete (char *tmpPat) +{ + char *cmd; + struct stat st; + + // Ceck if the folder present + if (stat(tmpPat, &st) != 0) { + printfError("Folder \"%s\" is not existing.\n", tmpPat); + return -1; + } + + cmd = calloc(strlen(tmpPat) + 20, sizeof(char)); + if (cmd == NULL) { + printfError("Fail to allocate memory for cmd.\n", tmpPat); + return -1; + } + + if (IS_WINDOWS) + sprintf(cmd, "rd \"%s\" /S/Q", tmpPat); // Command in windows + else + sprintf(cmd, "rm -r \"%s\"", tmpPat); // Command in Linux + + printfDebug("Generated cmd: \"%s\".\n", cmd); + if (system(cmd) != 0) { + // if(rmdir(tmpPat) != 0) + printError("Fail to delete the temporary files"); + free(cmd); + return -1; + } + printDebug("Deleted temporary files"); + free(cmd); + return 0; } ////////////////////////////////////////////////////////////////////////////// @@ -92,31 +91,31 @@ int delete(char* tmpPat){ ///////////////////////////////////////////////////////////////////////////// char *getTmpPath(const char *nam, size_t length) { - char *tmpPat; - - tmpPat = calloc(sizeof(char), length+2); - - // Define the temporary folder - if(strncpy(tmpPat, nam, length) == NULL){ - printError("Fail to allocate memory for temp dir.\n"); - free(tmpPat); - return NULL; - } - if(IS_WINDOWS) strcat(tmpPat, "\\"); - else strcat(tmpPat, "/"); - printfDebug("tmpPat=\"%s\"\n",tmpPat); - return tmpPat; + char *tmpPat; + + tmpPat = calloc(length + 2, sizeof(char)); + + // Define the temporary folder + if (strncpy(tmpPat, nam, length) == NULL) { + printError("Fail to allocate memory for temp dir.\n"); + free(tmpPat); + return NULL; + } + if (IS_WINDOWS) + strcat(tmpPat, "\\"); + else + strcat(tmpPat, "/"); + printfDebug("tmpPat=\"%s\"\n", tmpPat); + return tmpPat; } - - ////////////////////////////////////////////////////////////////////////////// /// Set the mode in debug so that the debug information will be printed /// ////////////////////////////////////////////////////////////////////////////// -void setDebug( ) +void setDebug() { - debug = 1; + debug = 1; } ////////////////////////////////////////////////////////////////////////////// @@ -124,12 +123,12 @@ void setDebug( ) /// ///\param msg Message to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printDebug(const char* msg){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, "%s\n", msg); - } +void printDebug(const char *msg) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, "%s\n", msg); + } } ////////////////////////////////////////////////////////////////////////////// @@ -138,12 +137,12 @@ void printDebug(const char* msg){ ///\param str1 Message to be printed for debugging ///\param str2 String variable to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printfDebug(const char* str1, const char* str2){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, str1, str2); - } +void printfDebug(const char *str1, const char *str2) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, str1, str2); + } } ////////////////////////////////////////////////////////////////////////////// @@ -152,12 +151,12 @@ void printfDebug(const char* str1, const char* str2){ ///\param str1 Message to be printed for debugging ///\param integer Integer variable to be printed for debugging ////////////////////////////////////////////////////////////////////////////// -void printfIntDebug(const char* str1, const int integer){ - if (debug == 1) - { - fprintf(stdout, "Debug: "); - fprintf(stdout, str1, integer); - } +void printfIntDebug(const char *str1, const int integer) +{ + if (debug == 1) { + fprintf(stdout, "Debug: "); + fprintf(stdout, str1, integer); + } } ////////////////////////////////////////////////////////////////////////////// @@ -165,9 +164,10 @@ void printfIntDebug(const char* str1, const int integer){ /// ///\param msg Error message to be printed ////////////////////////////////////////////////////////////////////////////// -void printError(const char* msg){ - fprintf(stderr, "*** Error: "); - fprintf(stderr, "%s\n", msg); +void printError(const char *msg) +{ + fprintf(stderr, "*** Error: "); + fprintf(stderr, "%s\n", msg); } ////////////////////////////////////////////////////////////////////////////// @@ -176,9 +176,10 @@ void printError(const char* msg){ ///\param str1 Error message to be printed ///\param str2 String variable to be printed ////////////////////////////////////////////////////////////////////////////// -void printfError(const char* str1, const char* str2){ - fprintf(stderr, "*** Error: "); - fprintf(stderr, str1, str2); +void printfError(const char *str1, const char *str2) +{ + fprintf(stderr, "*** Error: "); + fprintf(stderr, str1, str2); } ////////////////////////////////////////////////////////////////////////////// @@ -188,7 +189,7 @@ void printfError(const char* str1, const char* str2){ ///\param tmpPat Temporary path of the output file ///\return 0 if no error occurred ///////////////////////////////////////////////////////////////////////////// -int unpackminizip(const char* fmuFilNam, char* tmpPat){ - return unpackmz(fmuFilNam, tmpPat); +int unpackminizip(const char *fmuFilNam, char *tmpPat) +{ + return unpackmz(fmuFilNam, tmpPat); } - diff --git a/third_party/FMUParser/util.h b/third_party/FMUParser/util.h index aaee644399a..15f31fb7360 100644 --- a/third_party/FMUParser/util.h +++ b/third_party/FMUParser/util.h @@ -23,27 +23,28 @@ #define HANDLE void * /* See http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html */ #include // for creating dirs on Linux +#include // defines size_t #endif -//static char* getfmuPat(const char* fmuFilNam); -int delete(char* tmpPat); +// static char* getfmuPat(const char* fmuFilNam); +int delete (char *tmpPat); -void doubleToCommaString(char* buffer, double r); +void doubleToCommaString(char *buffer, double r); char *getTmpPath(const char *nam, size_t length); -void printDebug(const char* msg); +void printDebug(const char *msg); -void printfDebug(const char* str1, const char* str2); +void printfDebug(const char *str1, const char *str2); -void printfIntDebug(const char* str1, const int integer); +void printfIntDebug(const char *str1, const int integer); -void printError(const char* msg); +void printError(const char *msg); -void printfError(const char* str1, const char* str2); +void printfError(const char *str1, const char *str2); void setDebug(); -int unpack(const char* fmuFilNam, const char* tmpPat); +int unpack(const char *fmuFilNam, const char *tmpPat); -int unpackminizip(const char* fmuFilNam, char* tmpPat); +int unpackminizip(const char *fmuFilNam, char *tmpPat); diff --git a/third_party/FMUParser/xml_parser_cosim.c b/third_party/FMUParser/xml_parser_cosim.c old mode 100755 new mode 100644 index 255fd6f6c6e..6dc9e7104bd --- a/third_party/FMUParser/xml_parser_cosim.c +++ b/third_party/FMUParser/xml_parser_cosim.c @@ -45,86 +45,173 @@ * Copyright 2010 QTronic GmbH. All rights reserved. * -------------------------------------------------------------------------*/ -#include -#include -#include -#include #include "xml_parser_cosim.h" #include "util.h" +#include +#include +#include +#include -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" -}; +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 ANY_TYPE -1 #define XMLBUFSIZE 1024 -char text[XMLBUFSIZE]; // XML file is parsed in chunks of length XMLBUFZIZE +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 recordig content +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 recordig 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; +const char *getString(void *element, Att a) +{ + Element *e = (Element *)element; + const char **attr = e->attributes; int i; - for (i=0; in; i+=2) - if (attr[i]==attNames[a]) return attr[i+1]; + 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 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; + 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 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; + 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 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; + 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; }; +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; @@ -132,28 +219,34 @@ char getBoolean(void* element, Att a, ValueStatus* vs){ return 0; } -static int checkEnumValue(const char* enu); +static int 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 -1 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 getEnumValue(void *element, Att a, ValueStatus *vs) +{ + const char *value = getString(element, a); Enu id /*= 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 -1; + 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 -1; } } id = checkEnumValue(value); - if (id==-1) *vs = valueIllegal; + if (id == -1) *vs = valueIllegal; return id; } @@ -161,50 +254,57 @@ Enu getEnumValue(void* element, Att a, ValueStatus* vs) { // Convenience methods for accessing the model description. // Use is only safe after the ast has been successfuly validated. -const char* getModelIdentifier(ModelDescription* md) { - const char* modelId = getString(md, att_modelIdentifier); +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) { +int getNumberOfStates(ModelDescription *md) +{ ValueStatus vs; int n = getUInt(md, att_numberOfContinuousStates, &vs); - assert(vs==valueDefined); // this is a required attribute + assert(vs == valueDefined); // this is a required attribute return n; } -int getNumberOfEventIndicators(ModelDescription* md) { +int getNumberOfEventIndicators(ModelDescription *md) +{ ValueStatus vs; int n = getInt(md, att_numberOfEventIndicators, &vs); - assert(vs==valueDefined); // this is a required attribute + 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); +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) { +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) { +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) { +Enu getAlias(void *scalarVariable) +{ ValueStatus vs; return getEnumValue(scalarVariable, att_alias, &vs); } @@ -212,58 +312,61 @@ Enu getAlias(void* scalarVariable) { // 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) { +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 reqired attribute + assert(((Element *)scalarVariable)->type == elm_ScalarVariable); + assert(vs == valueDefined); // this is a reqired attribute return vr; } // the name is unique within a fmu -ScalarVariable* getVariableByName(ModelDescription* md, const char* name) { +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; - } + 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); +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 -ScalarVariable* getVariable(ModelDescription* md, fmiValueReference vr, Elm type){ +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; - } + 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; } -Type* getDeclaredType(ModelDescription* md, const char* declaredType){ +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; - } + for (i = 0; md->typeDefinitions[i]; i++) { + Type *tp = (Type *)md->typeDefinitions[i]; + if (!strcmp(declaredType, getName(tp))) return tp; + } return NULL; } -const char* getString2(ModelDescription* md, void* tp, Att a) { - Type* type; - const char* value = getString(tp, a); +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)); @@ -271,9 +374,10 @@ const char* getString2(ModelDescription* md, void* tp, Att a) { } // 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; +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)); @@ -282,11 +386,11 @@ const char * getDescription(ModelDescription* md, ScalarVariable* sv) { // 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); +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 @@ -297,29 +401,34 @@ const char * getVariableAttributeString(ModelDescription* md, // 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 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; + 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){ +double getNominal(ModelDescription *md, fmiValueReference vr) +{ ValueStatus vs; double nominal = getVariableAttributeDouble(md, vr, elm_Real, att_nominal, &vs); - return vs==valueDefined ? nominal : 1.0; + 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) { +static int checkPointer(const void *ptr) +{ + if (!ptr) { printf("Out of memory\n"); if (parser) XML_StopParser(parser, XML_FALSE); return 0; // error @@ -327,9 +436,10 @@ static int checkPointer(const void* ptr){ return 1; // success } -static int checkName(const char* name, const char* kind, const char* array[], int n){ +static int checkName(const char *name, const char *kind, const char *array[], int n) +{ int i; - for (i=0; itype == e) return 1; // success logFatalTypeError(elmNames[e], elm->type); return 0; // error @@ -370,26 +484,33 @@ static int checkElementType(void* element, Elm e) { // Returns 0 to indicate error // Verify that the next stack element exists and is of the given type // If e==ANY_TYPE, the type check is ommited -static int checkPeek(Elm e) { - if (stackIsEmpty(stack)){ - printf("Illegal document structure, expected %s\n", elmNames[e]); +static int checkPeek(Elm e) +{ + if (stackIsEmpty(stack)) { + if (e == ANY_TYPE) { + printf("Illegal document structure, expected ANY_TYPE (-1)\n"); + } else { + printf("Illegal document structure, expected %s\n", elmNames[e]); + } XML_StopParser(parser, XML_FALSE); return 0; // error } - return e==ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e); + return e == ANY_TYPE ? 1 : checkElementType(stackPeek(stack), e); } // Returns NULL to indicate error // Get the next stack element, it is of the given type. // If e==ANY_TYPE, the type check is ommited -static void* checkPop(Elm e){ +static void *checkPop(Elm e) +{ return checkPeek(e) ? stackPop(stack) : NULL; } // ------------------------------------------------------------------------- // Helper -AstNodeType getAstNodeType(Elm e){ +AstNodeType getAstNodeType(Elm e) +{ switch (e) { case elm_fmiModelDescription: return astModelDescription; @@ -419,21 +540,23 @@ AstNodeType getAstNodeType(Elm e){ // 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 addAttributes(Element *el, const char **attr) +{ int n, a; - const char** att = NULL; - for (n=0; attr[n]; n+=2); - if (n>0) { - att = calloc(n, sizeof(char*)); + const char **att = NULL; + for (n = 0; attr[n]; n += 2) + ; + if (n > 0) { + att = calloc(n, sizeof(char *)); if (!checkPointer(att)) return 0; } - for (n=0; attr[n]; n+=2) { - char* value = strdup(attr[n+1]); + for (n = 0; attr[n]; n += 2) { + char *value = strdup(attr[n + 1]); if (!checkPointer(value)) return 0; a = checkAttribute(attr[n]); if (a == -1) return 0; // illegal attribute error - att[n ] = attNames[a]; // no heap memory - att[n+1] = value; // heap memory + att[n] = attNames[a]; // no heap memory + att[n + 1] = value; // heap memory } el->attributes = att; // NULL if n=0 el->n = n; @@ -441,12 +564,13 @@ int addAttributes(Element* el, const char** attr) { } // Returns NULL to indicate error -Element* newElement(Elm type, int size, const char** attr) { - Element* e = (Element*)calloc(1, size); +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; + e->n = 0; if (!addAttributes(e, attr)) return NULL; return e; } @@ -455,21 +579,35 @@ Element* newElement(Elm type, int size, const char** attr) { // 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) { +static void XMLCALL startElement(void *context, const char *elm, const char **attr) +{ Elm el; - void* e; + void *e; int size; el = checkElement(elm); - if (el==-1) return; // error + if (el == -1) 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); + 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); checkPointer(e); @@ -479,198 +617,212 @@ default: assert(0); // 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) { +static void popList(Elm e) +{ int n = 0; - Element** array; - Element* elm = stackPop(stack); + Element **array; + Element *elm = stackPop(stack); while (elm->type == e) { elm = stackPop(stack); n++; } - stackPush(stack, elm); // push ListElement back to stack - array = (Element**)stackLastPopedAsArray0(stack, n); // NULL terminated list - if (getAstNodeType(elm->type)!=astListElement) return; // failure - ((ListElement*)elm)->list = array; + stackPush(stack, elm); // push ListElement back to stack + array = (Element **)stackLastPopedAsArray0(stack, n); // NULL terminated list + if (getAstNodeType(elm->type) != astListElement) 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) { +static void XMLCALL endElement(void *context, const char *elm) +{ Elm el; 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 = checkPop(ANY_TYPE); - if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) { - cs = (CoSimulation*)child; - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_ModelVariables){ - mv = (ScalarVariable**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_VendorAnnotations){ - va = (ListElement**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_DefaultExperiment){ - de = (Element*)child; - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_TypeDefinitions){ - td = (Type**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - if (child->type == elm_UnitDefinitions){ - ud = (ListElement**)child->list; - free(child); - child = checkPop(ANY_TYPE); - if (!child) return; - } - // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location - if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) { - cs = (CoSimulation*)child; - child = checkPop(ANY_TYPE); - 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(ANY_TYPE); - void* im = checkPop(elm_Implementation); - stackPush(stack, cs); - free(im); - el = ((Element*)cs)->type; - break; - } - case elm_CoSimulation_StandAlone: - { - Element* ca = checkPop(elm_Capabilities); - CoSimulation* cs = checkPop(elm_CoSimulation_StandAlone); - if (!ca || !cs) return; - cs->capabilities = ca; - stackPush(stack, cs); - break; - } - case elm_CoSimulation_Tool: - { - ListElement* mo = checkPop(elm_Model); - Element* ca = checkPop(elm_Capabilities); - CoSimulation* cs = 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 = checkPop(ANY_TYPE); - 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 = checkPop(ANY_TYPE); - if (!child) return; - if (child->type==elm_DirectDependency){ - list = ((ListElement*)child)->list; - free(child); - child = checkPop(ANY_TYPE); - 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 = checkPop(elm_Name); - if (!name) return; - name->n = 2; - name->attributes = 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 -1: return; // illegal element error - default: // must be a leaf Element - assert(getAstNodeType(el)==astElement); - break; + 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 = checkPop(ANY_TYPE); + if (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool) { + cs = (CoSimulation *)child; + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_ModelVariables) { + mv = (ScalarVariable **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_VendorAnnotations) { + va = (ListElement **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_DefaultExperiment) { + de = (Element *)child; + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_TypeDefinitions) { + td = (Type **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + if (child->type == elm_UnitDefinitions) { + ud = (ListElement **)child->list; + free(child); + child = checkPop(ANY_TYPE); + if (!child) return; + } + // work around bug of SimulationX 3.4 and 3.5 which places Implementation at wrong location + if (!cs && (child->type == elm_CoSimulation_StandAlone || child->type == elm_CoSimulation_Tool)) { + cs = (CoSimulation *)child; + child = checkPop(ANY_TYPE); + 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(ANY_TYPE); + void *im = checkPop(elm_Implementation); + stackPush(stack, cs); + free(im); + el = ((Element *)cs)->type; + break; + } + case elm_CoSimulation_StandAlone: { + Element *ca = checkPop(elm_Capabilities); + CoSimulation *cs = checkPop(elm_CoSimulation_StandAlone); + if (!ca || !cs) return; + cs->capabilities = ca; + stackPush(stack, cs); + break; + } + case elm_CoSimulation_Tool: { + ListElement *mo = checkPop(elm_Model); + Element *ca = checkPop(elm_Capabilities); + CoSimulation *cs = 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 = checkPop(ANY_TYPE); + 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 = checkPop(ANY_TYPE); + if (!child) return; + if (child->type == elm_DirectDependency) { + list = ((ListElement *)child)->list; + free(child); + child = checkPop(ANY_TYPE); + 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 = checkPop(elm_Name); + if (!name) return; + name->n = 2; + name->attributes = 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 -1: + 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. @@ -683,7 +835,8 @@ static void XMLCALL endElement(void *context, const char *elm) { // For some reason, if the element data is the empty string (Eg. ) // 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) { +void XMLCALL handleData(void *context, const XML_Char *s, int len) +{ size_t n; if (skipData) return; if (!data) { @@ -695,17 +848,16 @@ void XMLCALL handleData(void *context, const XML_Char *s, int len) { strncpy(data, s, len); data[len] = '\0'; } - } - else { + } else { // continue existing string n = strlen(data) + len; - char* tmpData; - tmpData = realloc(data, n+1); + char *tmpData; + tmpData = realloc(data, n + 1); if (!tmpData) { - printf("Couldnt allocate memory in xml_parser_cosim::handleData\n"); - return; - } - data = tmpData; + printf("Couldnt allocate memory in xml_parser_cosim::handleData\n"); + return; + } + data = tmpData; strncat(data, s, len); data[n] = '\0'; } @@ -715,57 +867,61 @@ void XMLCALL handleData(void *context, const XML_Char *s, int len) { // ------------------------------------------------------------------------- // printing -static void printList(int indent, void** list); +static void printList(int indent, void **list); -void printElement(int indent, void* element){ +void printElement(int indent, void *element) +{ int i; - Element* e = (Element*)element; + Element *e = (Element *)element; if (!e) return; // print attributes - for (i=0; itype]); - for (i=0; in; i+=2) - printf(" %s=%s", e->attributes[i], e->attributes[i+1]); + 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: - printElement(indent, (void**)(Element*)e); - 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; - } + case astElement: + printElement(indent, (void **)(Element *)e); + 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){ +static void printList(int indent, void **list) +{ int i; - if (list) for (i=0; list[i]; i++) - printElement(indent, list[i]); + if (list) + for (i = 0; list[i]; i++) + printElement(indent, list[i]); } //////////////////////////////////////////////////////////////////////////////////// @@ -773,149 +929,141 @@ static void printList(int indent, void** list){ /// ///\param md The model description //////////////////////////////////////////////////////////////////////////////////// -void printidf(const char* fmuFilNam, ModelDescription* md) -{ - FILE *fp; - - char type[12]; - int i, j, varname, vardes=-1; - void **list; - ScalarVariable* se; - Element* ee; - - fp = fopen("tmp.idf", "w"); - - if (fp == NULL) { - printf("Can't create temporary idf file!\n"); - exit(42); // STL error code: File not open. - } - - ///////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface - fprintf(fp, "ExternalInterface,\n"); - fprintf(fp, " FunctionalMockupUnitImport;\t\t!- Name of External Interface\n"); - - //////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface:FunctionalMockupUnit - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport,\n"); - - fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); - //fprintf(fp, " ,\t\t!- FMU Model Name\n"); - fprintf(fp, " ,\t\t!- FMU Timeout in milli-seconds\n"); - //fprintf(fp, " ,\t\t!- FMU Visible Value\n"); - //fprintf(fp, " ,\t\t!- FMU Interactive Value\n"); - fprintf(fp, " ;\t\t!- FMU LoggingOn\n"); - - list = (void **)md->modelVariables; - if (list) - for(j=0; list[j]; j++) - { - Element* e = (Element*)list[j]; - Enu val = enu_none; - - for(i=0; in; i+=2) - { - if(!strcmp(e->attributes[i], "name")) - varname = i+1; - else if(!strcmp(e->attributes[i], "causality")) - val = checkEnumValue(e->attributes[i+1]); - else if(!strcmp(e->attributes[i], "description")) - vardes = i+1; - } - - ///////////////////////////////////////////////////////////////////////////////////// - // Define ExternalInterface:FunctionalMockupUnitImport:From:Variable - // Define part of ExternalInterface:FunctionalMockupUnitImport:To, - if(val == enu_input || val == enu_output) - { - switch (val) - { - case enu_input: - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:From:Variable,\n"); - fprintf(fp, " ,\t\t!- Output:Variable Index Key Name\n"); - fprintf(fp, " ,\t\t!- Output:Variable Name\n"); - break; - case enu_output: - // User should manually define the To type: Schedule, Actuator, Variable - fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:To:,\n"); - fprintf(fp, " ,\t\t!- Name\n"); - break; - default: - break; - } - fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); - fprintf(fp, " ,\t\t!- FMU Instance Name\n"); - switch (val) - { - case enu_input: - fprintf(fp, " %s;\t\t!- FMU Variable Name\n", e->attributes[varname]); - break; - case enu_output: - fprintf(fp, " %s,\t\t!- FMU Variable Name\n", e->attributes[varname]); - break; - default: - break; - } - } - - if(val==enu_output) fprintf(fp, " ;\t\t!- Initial Value\n"); - - - } - fclose(fp); -} - -static void freeList(void** list); - -void freeElement(void* element){ +void printidf(const char *fmuFilNam, ModelDescription *md) +{ + FILE *fp; + + int i, j, varname, vardes = -1; + void **list; + + fp = fopen("tmp.idf", "w"); + + if (fp == NULL) { + printf("Can't create temporary idf file!\n"); + exit(42); // STL error code: File not open. + } + + ///////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface + fprintf(fp, "ExternalInterface,\n"); + fprintf(fp, " FunctionalMockupUnitImport;\t\t!- Name of External Interface\n"); + + //////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface:FunctionalMockupUnit + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport,\n"); + + fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); + // fprintf(fp, " ,\t\t!- FMU Model Name\n"); + fprintf(fp, " ,\t\t!- FMU Timeout in milli-seconds\n"); + // fprintf(fp, " ,\t\t!- FMU Visible Value\n"); + // fprintf(fp, " ,\t\t!- FMU Interactive Value\n"); + fprintf(fp, " ;\t\t!- FMU LoggingOn\n"); + + list = (void **)md->modelVariables; + if (list) + for (j = 0; list[j]; j++) { + Element *e = (Element *)list[j]; + Enu val = enu_none; + + for (i = 0; i < e->n; i += 2) { + if (!strcmp(e->attributes[i], "name")) + varname = i + 1; + else if (!strcmp(e->attributes[i], "causality")) + val = checkEnumValue(e->attributes[i + 1]); + else if (!strcmp(e->attributes[i], "description")) + vardes = i + 1; + } + + ///////////////////////////////////////////////////////////////////////////////////// + // Define ExternalInterface:FunctionalMockupUnitImport:From:Variable + // Define part of ExternalInterface:FunctionalMockupUnitImport:To, + if (val == enu_input || val == enu_output) { + switch (val) { + case enu_input: + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:From:Variable,\n"); + fprintf(fp, " ,\t\t!- Output:Variable Index Key Name\n"); + fprintf(fp, " ,\t\t!- Output:Variable Name\n"); + break; + case enu_output: + // User should manually define the To type: Schedule, Actuator, Variable + fprintf(fp, "\nExternalInterface:FunctionalMockupUnitImport:To:,\n"); + fprintf(fp, " ,\t\t!- Name\n"); + break; + default: + break; + } + fprintf(fp, " %s,\t\t!- FMU File Name\n", fmuFilNam); + fprintf(fp, " ,\t\t!- FMU Instance Name\n"); + switch (val) { + case enu_input: + fprintf(fp, " %s;\t\t!- FMU Variable Name\n", e->attributes[varname]); + break; + case enu_output: + fprintf(fp, " %s,\t\t!- FMU Variable Name\n", e->attributes[varname]); + break; + default: + break; + } + } + + if (val == enu_output) fprintf(fp, " ;\t\t!- Initial Value\n"); + } + fclose(fp); +} + +static void freeList(void **list); + +void freeElement(void *element) +{ int i; - Element* e = (Element*)element; + Element *e = (Element *)element; if (!e) return; // free attributes - for (i=0; in; i+=2) - free((void*)e->attributes[i+1]); - if (e->attributes) free((void*)e->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: -// Add an empty case here to avoid warnings from -Wall -// The element e gets freed elsewhere, if we free it -// here, we get warnings -//freeElement((void**)(Element*)e); - 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; - } + case astElement: + // Add an empty case here to avoid warnings from -Wall + // The element e gets freed elsewhere, if we free it + // here, we get warnings + // freeElement((void**)(Element*)e); + 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){ +static void freeList(void **list) +{ int i; if (!list) return; - for (i=0; list[i]; i++) + for (i = 0; list[i]; i++) freeElement(list[i]); free(list); } @@ -923,19 +1071,20 @@ static void freeList(void** list){ // ------------------------------------------------------------------------- // Validation - done after parsing to report all errors -ModelDescription* validate(ModelDescription* md) { +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) { - printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv)); - error++; + 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) { + printf("Warning: Declared type %s of variable %s not found in modelDescription.xml\n", declaredType, getName(sv)); + error++; + } } - } if (error) { printf("Error: Found %d error in modelDescription.xml\n", error); return NULL; @@ -946,7 +1095,8 @@ ModelDescription* validate(ModelDescription* md) { // ------------------------------------------------------------------------- // Entry function parse() of the XML parser -static void cleanup(FILE *file) { +static void cleanup(FILE *file) +{ stackFree(stack); stack = NULL; XML_ParserFree(parser); @@ -957,8 +1107,9 @@ static void cleanup(FILE *file) { // 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) { - ModelDescription* md = NULL; +ModelDescription *parse(const char *xmlPath) +{ + ModelDescription *md = NULL; FILE *file; int done = 0; stack = stackNew(100, 10); @@ -967,31 +1118,30 @@ ModelDescription* parse(const char* xmlPath) { if (!checkPointer(parser)) return NULL; // failure XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, handleData); - file = fopen(xmlPath, "rb"); -if (file == NULL) { + file = fopen(xmlPath, "rb"); + if (file == NULL) { printf("Cannot open file '%s'\n", xmlPath); - XML_ParserFree(parser); + XML_ParserFree(parser); return NULL; // failure } while (!done) { size_t n = fread(text, sizeof(char), XMLBUFSIZE, file); -if (n != XMLBUFSIZE) done = 1; - if (!XML_Parse(parser, text, (int)n, done)){ - printf("Parse error in file %s at line %d:\n%s\n", - xmlPath, - (int)XML_GetCurrentLineNumber(parser), - XML_ErrorString(XML_GetErrorCode(parser))); - while (! stackIsEmpty(stack)) md = stackPop(stack); - if (md) freeElement(md); - cleanup(file); - return NULL; // failure + if (n != XMLBUFSIZE) done = 1; + if (!XML_Parse(parser, text, (int)n, done)) { + printf("Parse error in file %s at line %d:\n%s\n", + xmlPath, + (int)XML_GetCurrentLineNumber(parser), + XML_ErrorString(XML_GetErrorCode(parser))); + while (!stackIsEmpty(stack)) + md = stackPop(stack); + if (md) freeElement(md); + cleanup(file); + return NULL; // failure } } md = stackPop(stack); assert(stackIsEmpty(stack)); cleanup(file); - //printElement(1, md); // debug + // printElement(1, md); // debug return validate(md); // success if all refs are valid } - - diff --git a/third_party/FMUParser/xml_parser_cosim.h b/third_party/FMUParser/xml_parser_cosim.h old mode 100755 new mode 100644 index ebf7f4c20bc..af501fdacc7 --- a/third_party/FMUParser/xml_parser_cosim.h +++ b/third_party/FMUParser/xml_parser_cosim.h @@ -1,17 +1,17 @@ /// This file is based on xml_parser.c that is copyrighted by -/// QTronic GmbH and that is distributed under the BSD license. -/// The original file, its copyright notice and its license can +/// QTronic GmbH and that is distributed under the BSD license. +/// The original file, its copyright notice and its license can /// be found in Copyright /// -/// The file has been modified and renamed to xml_parser_cosim.c -/// for use with the FMU standard for co-simulation. +/// The file has been modified and renamed to xml_parser_cosim.c +/// for use with the FMU standard for co-simulation. /// The original file was developed for model exchange. /// Copyright notice of original file that served as the basis of this imlementation. -/* ------------------------------------------------------------------------- +/* ------------------------------------------------------------------------- * xml_parser.h * A parser for file modelVariables.xml of an FMU. - * Copyright 2010 QTronic GmbH. All rights reserved. + * Copyright 2010 QTronic GmbH. All rights reserved. * -------------------------------------------------------------------------*/ #ifndef xml_parser_cosim_h @@ -37,91 +37,176 @@ extern const char *attNames[SIZEOF_ATT]; extern const char *enuNames[SIZEOF_ENU]; // Elements -typedef enum { - 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 +typedef enum +{ + 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_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 +typedef enum +{ + 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_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 +typedef enum +{ + 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 +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 +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. +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 +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 } 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 +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 +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 { +typedef enum +{ astElement, astListElement, astType, @@ -131,40 +216,40 @@ typedef enum { } AstNodeType; // Possible results when retrieving an attribute value from an element -typedef enum { +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 printidf(const char* fmuFilNam, ModelDescription* md); -void freeElement (void* element); +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 printidf(const char *fmuFilNam, ModelDescription *md); +void freeElement(void *element); // Convenience methods for AST access. To be used afer 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); -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, fmiValueReference vr); +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); +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, fmiValueReference vr); #endif // xml_parser_cosim_h - diff --git a/third_party/Windows-CalcEngine/src/Gases/src/Gas.cpp b/third_party/Windows-CalcEngine/src/Gases/src/Gas.cpp index 8ba1886ebae..b8c2d5590df 100644 --- a/third_party/Windows-CalcEngine/src/Gases/src/Gas.cpp +++ b/third_party/Windows-CalcEngine/src/Gases/src/Gas.cpp @@ -22,7 +22,7 @@ namespace Gases { m_Properties( t_Gas.m_Properties ), m_DefaultGas( t_Gas.m_DefaultGas ), m_Pressure( t_Gas.m_Pressure ) { m_GasItem.clear(); - for ( auto item : t_Gas.m_GasItem ) { + for ( auto const &item : t_Gas.m_GasItem ) { m_GasItem.push_back( item ); } } @@ -39,7 +39,7 @@ namespace Gases { double CGas::totalPercent() { auto totalPercent = 0.0; - for ( auto& it : m_GasItem ) { + for ( auto const &it : m_GasItem ) { totalPercent += it.getFraction(); } @@ -256,7 +256,7 @@ namespace Gases { CGas& CGas::operator=( CGas const& t_Gas ) { m_GasItem.clear(); - for ( auto const item : t_Gas.m_GasItem ) { + for ( auto const &item : t_Gas.m_GasItem ) { m_GasItem.push_back( item ); } m_SimpleProperties = t_Gas.m_SimpleProperties; diff --git a/tst/EnergyPlus/unit/OutputProcessor.unit.cc b/tst/EnergyPlus/unit/OutputProcessor.unit.cc index 8022d170667..ddc1052f204 100644 --- a/tst/EnergyPlus/unit/OutputProcessor.unit.cc +++ b/tst/EnergyPlus/unit/OutputProcessor.unit.cc @@ -3434,7 +3434,7 @@ namespace OutputProcessor { ReportingFrequency report_freq = ReportingFrequency::EachCall; - for (auto const option : valid_options) { + for (auto const &option : valid_options) { report_freq = determineFrequency(*state, option.first); EXPECT_EQ(option.second, report_freq); } @@ -4032,7 +4032,7 @@ namespace OutputProcessor { {17, std::make_tuple(2, "MYBUILDINGOTHER", "Electricity", "", "", "", "J")}, }); - for (auto const result : meters_result) { + for (auto const &result : meters_result) { EXPECT_EQ(std::get<0>(result.second), EnergyMeters(result.first).TypeOfMeter); EXPECT_EQ(std::get<1>(result.second), EnergyMeters(result.first).Name); EXPECT_EQ(std::get<2>(result.second), EnergyMeters(result.first).ResourceType); @@ -4082,7 +4082,7 @@ namespace OutputProcessor { {6, std::make_tuple(0, "GeneralLights:InteriorLights:Electricity", "Electricity", "InteriorLights", "GeneralLights", "", "J")}, }); - for (auto const result : meters_result) { + for (auto const &result : meters_result) { EXPECT_EQ(std::get<0>(result.second), EnergyMeters(result.first).TypeOfMeter); EXPECT_EQ(std::get<1>(result.second), EnergyMeters(result.first).Name); EXPECT_EQ(std::get<2>(result.second), EnergyMeters(result.first).ResourceType);