diff --git a/libs/util/src/win/libs.c b/libs/util/src/win/libs.c index 9f0d20b..7f6bc34 100644 --- a/libs/util/src/win/libs.c +++ b/libs/util/src/win/libs.c @@ -10,6 +10,7 @@ #define _WINSOCKAPI_ // stops windows.h including winsock.h #include +#include #include "common/logging.h" #include "common/memory.h" @@ -23,24 +24,12 @@ extern "C" { #endif /* __cplusplus */ -McxStatus mcx_dll_load(DllHandle * handle, const char * dllPath) { - DllHandleCheck compValue; - - wchar_t * wDllPath = mcx_string_to_widechar(dllPath); - - * handle = LoadLibraryExW(wDllPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); - mcx_free(wDllPath); - - compValue = (DllHandleCheck) * handle; - if (compValue <= HINSTANCE_ERROR) { - LPVOID lpMsgBuf; - DWORD err = GetLastError(); - - mcx_log(LOG_ERROR, "Util: Dll (%s) could not be loaded", dllPath); - - switch (err) { +static void print_last_error() { + LPVOID lpMsgBuf; + DWORD err = GetLastError(); + switch (err) { case ERROR_BAD_EXE_FORMAT: - mcx_log(LOG_ERROR, "Util: There is a mismatch in bitness (32/64) between current Model.CONNECT Execution Engine and the dynamic library", dllPath); + mcx_log(LOG_ERROR, "Util: There is a mismatch in bitness (32/64) between current Model.CONNECT Execution Engine and the dynamic library"); break; default: FormatMessage( @@ -56,11 +45,62 @@ McxStatus mcx_dll_load(DllHandle * handle, const char * dllPath) { mcx_log(LOG_ERROR, "Util: Error %d: %s", err, lpMsgBuf); LocalFree(lpMsgBuf); break; + } +} + + +McxStatus mcx_dll_load(DllHandle * handle, const char * dllPath) { + DllHandleCheck compValue; + + wchar_t * wDllPath = mcx_string_to_widechar(dllPath); + + McxStatus retVal = RETURN_OK; + + if (PathIsRelativeW(wDllPath)) { + wchar_t * wFullDllPath = NULL; + DWORD length = GetFullPathNameW(wDllPath, 0, NULL, NULL); + if (length == 0) { + mcx_log(LOG_ERROR, "Util: Error retrieving length of absolute path of Dll (%s)", dllPath); + print_last_error(); + retVal = RETURN_ERROR; + goto relpath_cleanup; + } + wFullDllPath = (wchar_t *) mcx_malloc(sizeof(wchar_t) * length); + length = GetFullPathNameW(wDllPath, length, wFullDllPath, NULL); + if (length == 0) { + mcx_log(LOG_ERROR, "Util: Error creating absolute path for Dll (%s)", dllPath); + print_last_error(); + retVal = RETURN_ERROR; + goto relpath_cleanup; } - return RETURN_ERROR; +relpath_cleanup: + if (wDllPath) { + mcx_free(wDllPath); + } + if (retVal != RETURN_OK) { + goto cleanup; + } + wDllPath = wFullDllPath; + } + + mcx_log(LOG_DEBUG, "Util: Loading Dll %S", wDllPath); + + * handle = LoadLibraryExW(wDllPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + + compValue = (DllHandleCheck) * handle; + if (compValue <= HINSTANCE_ERROR) { + mcx_log(LOG_ERROR, "Util: Dll (%s) could not be loaded", dllPath); + print_last_error(); + retVal = RETURN_ERROR; + goto cleanup; + } + +cleanup: + if (wDllPath) { + mcx_free(wDllPath); } - return RETURN_OK; + return retVal; } diff --git a/libs/util/src/win/os.c b/libs/util/src/win/os.c index ed71dac..66742ad 100644 --- a/libs/util/src/win/os.c +++ b/libs/util/src/win/os.c @@ -87,10 +87,25 @@ const char * mcx_os_get_errno_descr(int errnum) { int mcx_os_path_exists(const char * path) { int ret; - wchar_t * wPath = mcx_string_to_widechar(path); + char * absoluteNormalizedPath = NULL; + wchar_t * wPath = NULL; + + absoluteNormalizedPath = mcx_os_path_normalize(path); + if (path && !absoluteNormalizedPath) { + mcx_log(LOG_ERROR, "Util: Could not convert path '%s' to a normalized absolute path", path); + return 0; + } + + wPath = mcx_string_to_widechar(absoluteNormalizedPath); + + if (absoluteNormalizedPath) { + mcx_free(absoluteNormalizedPath); + } ret = (_waccess(wPath, 0) != -1); - mcx_free(wPath); + if (wPath) { + mcx_free(wPath); + } return ret; } diff --git a/mcx/mcx.c b/mcx/mcx.c index c5c0f43..d3afd34 100644 --- a/mcx/mcx.c +++ b/mcx/mcx.c @@ -316,14 +316,20 @@ McxStatus RunMCX(int argc, char *argv[]) { goto cleanup; } + mcx_signal_handler_set_function("ConfigSetupFromCmdLine"); retVal = config->SetupFromCmdLine(config, argc, argv); + mcx_signal_handler_unset_function(); if (retVal == RETURN_ERROR) { goto cleanup; } + mcx_signal_handler_set_function("SetupLogFiles"); SetupLogFiles(config->logFile, config->writeAllLogFile); + mcx_signal_handler_unset_function(); logInitialized = 1; + mcx_signal_handler_set_function("ConfigSetupFromEnvironment"); retVal = config->SetupFromEnvironment(config); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { mcx_log(LOG_INFO, "Setting up configuration from environment failed"); retVal = RETURN_ERROR; @@ -337,14 +343,18 @@ McxStatus RunMCX(int argc, char *argv[]) { goto cleanup; } + mcx_signal_handler_set_function("ReaderSetup"); retVal = reader->Setup(reader, config->modelFile, config); + mcx_signal_handler_unset_function(); if (retVal == RETURN_ERROR) { mcx_log(LOG_ERROR, "Input reader setup failed"); retVal = RETURN_ERROR; goto cleanup; } + mcx_signal_handler_set_function("ReaderRead"); mcxInput = reader->Read(reader, config->modelFile); + mcx_signal_handler_unset_function(); if (!mcxInput) { mcx_log(LOG_ERROR, "Parsing of input file failed"); retVal = RETURN_ERROR; @@ -352,7 +362,9 @@ McxStatus RunMCX(int argc, char *argv[]) { } element = (InputElement *) mcxInput; + mcx_signal_handler_set_function("ConfigSetupFromInput"); retVal = config->SetupFromInput(config, mcxInput->config); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Setting up configuration from input file failed"); retVal = RETURN_ERROR; @@ -387,20 +399,26 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_cpu_time_get(&clock_read_begin); mcx_time_get(&time_read_begin); + mcx_signal_handler_set_function("TaskRead"); retVal = task->Read(task, mcxInput->task); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } + mcx_signal_handler_set_function("ModelRead"); retVal = model->Read(model, mcxInput->model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } object_destroy(mcxInput); + mcx_signal_handler_set_function("ReaderCleanup"); reader->Cleanup(reader); + mcx_signal_handler_unset_function(); object_destroy(reader); mcx_cpu_time_get(&clock_read_end); @@ -421,19 +439,25 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_cpu_time_get(&clock_setup_begin); mcx_time_get(&time_setup_begin); + mcx_signal_handler_set_function("TaskSetup"); retVal = task->Setup(task, model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } + mcx_signal_handler_set_function("ModelSetup"); retVal = model->Setup(model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } + mcx_signal_handler_set_function("TaskPrepareRun"); retVal = task->PrepareRun(task, model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; @@ -457,7 +481,9 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_cpu_time_get(&clock_init_begin); mcx_time_get(&time_init_begin); + mcx_signal_handler_set_function("TaskInitialize"); retVal = task->Initialize(task, model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; @@ -481,7 +507,9 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_sim_begin); mcx_time_get(&time_sim_begin); + mcx_signal_handler_set_function("TaskRun"); retVal = task->Run(task, model); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; @@ -512,6 +540,7 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_cpu_time_get(&clock_cleanup_begin); mcx_time_get(&time_cleanup_begin); + mcx_signal_handler_set_function("RunMCX:Cleanup"); object_destroy(task); object_destroy(model); object_destroy(config); @@ -544,6 +573,10 @@ McxStatus RunMCX(int argc, char *argv[]) { cleanup: + if (reader) { + reader->Cleanup(reader); + object_destroy(reader); + } if (mcxInput) { object_destroy(mcxInput); } if (model) { object_destroy(model); } @@ -554,6 +587,7 @@ McxStatus RunMCX(int argc, char *argv[]) { mcx_log(LOG_INFO, "**********************************************************************"); } + mcx_signal_handler_unset_function(); // RunMCX:Cleanup return retVal; } diff --git a/scripts/SSP/Ports.xsd b/scripts/SSP/Ports.xsd index dee8489..448802c 100644 --- a/scripts/SSP/Ports.xsd +++ b/scripts/SSP/Ports.xsd @@ -25,10 +25,6 @@ - - - - @@ -38,7 +34,7 @@ - + diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2de6bcc..5808f1e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -18,6 +18,7 @@ file(GLOB MCX_SRC_COMMON "core/channels/*.c" "core/channels/*.cpp" "core/connections/*.c" "core/connections/*.cpp" "core/connections/filters/*.c" "core/connections/filters/*.cpp" + "core/parameters/*.c" "core/parameters/*.cpp" "components/*.c" "components/*.cpp" "fmu/*.c" "fmu/*.cpp" "objects/*.c" "objects/*.cpp" diff --git a/src/CentralParts.h b/src/CentralParts.h index 7740e94..653e54d 100644 --- a/src/CentralParts.h +++ b/src/CentralParts.h @@ -100,7 +100,6 @@ typedef enum DecoupleTypeDef { DECOUPLE_ALWAYS = 0x4 } DecoupleType; -// Note: the enum values are mandatory because the enum is used in integer context typedef enum PolyOrderTypeDef { POLY_CONSTANT = 0 , POLY_LINEAR = 1 @@ -150,6 +149,7 @@ typedef enum StoreLevel { STORE_NONE = 1, STORE_SYNCHRONIZATION = 2, STORE_COUPLING = 3, + STORE_MICRO = 4, } StoreLevel; typedef enum { diff --git a/src/components/ComponentTypes.c b/src/components/ComponentTypes.c index 7cc989f..503824e 100644 --- a/src/components/ComponentTypes.c +++ b/src/components/ComponentTypes.c @@ -38,8 +38,10 @@ OBJECT_CLASS(ComponentType, Object); /*****************************************************************************/ /* ComponentTypeConstant */ /*****************************************************************************/ +const char * const compConstantTypeString = "CONSTANT"; + static const char * ComponentTypeConstantToString(ComponentType * type) { - return "CONSTANT"; + return compConstantTypeString; } static void ComponentTypeConstantDestructor(ComponentTypeConstant * type) { diff --git a/src/components/ComponentTypes.h b/src/components/ComponentTypes.h index a4043be..0152de7 100644 --- a/src/components/ComponentTypes.h +++ b/src/components/ComponentTypes.h @@ -28,6 +28,7 @@ struct ComponentType { }; +extern const char * const compConstantTypeString; extern const ObjectClass _ComponentTypeConstant; typedef struct ComponentTypeConstant { ComponentType _; diff --git a/src/components/comp_constant.c b/src/components/comp_constant.c index 5e1f472..57556fb 100644 --- a/src/components/comp_constant.c +++ b/src/components/comp_constant.c @@ -10,6 +10,7 @@ #include "components/comp_constant.h" +#include "core/channels/ChannelValue.h" #include "core/Databus.h" #include "reader/model/components/specific_data/ConstantInput.h" @@ -18,42 +19,32 @@ extern "C" { #endif /* __cplusplus */ -typedef struct CompConstant { - Component _; - - ChannelValue ** values; -} CompConstant; - static McxStatus Read(Component * comp, ComponentInput * input, const struct Config * const config) { CompConstant * compConstant = (CompConstant *)comp; ConstantInput * constantInput = (ConstantInput *)input; Databus * db = comp->GetDatabus(comp); - size_t numVecOut = DatabusGetOutVectorChannelsNum(db); + size_t numOut = DatabusGetOutChannelsNum(db); - // We read each vector channel (scalars are vectors of length 1) - // and the corresponding values from the input file. - compConstant->values = (ChannelValue **)mcx_calloc(numVecOut, sizeof(ChannelValue *)); + compConstant->values = (ChannelValue **)mcx_calloc(numOut, sizeof(ChannelValue *)); if (constantInput->values) { ConstantValuesInput * values = constantInput->values; size_t i = 0; - for (i = 0; i < numVecOut; i++) { + for (i = 0; i < numOut; i++) { ConstantValueInput * value = (ConstantValueInput *)values->values->At(values->values, i); if (value->type == CONSTANT_VALUE_SCALAR) { - compConstant->values[i] = (ChannelValue *)mcx_calloc(1, sizeof(ChannelValue)); - ChannelValueInit(compConstant->values[i], value->value.scalar->type); - ChannelValueSetFromReference(compConstant->values[i], &value->value.scalar->value); + compConstant->values[i] = ChannelValueNewScalar(value->value.scalar->type, &value->value.scalar->value); + if (!compConstant->values[i]) { + ComponentLog(comp, LOG_ERROR, "Could not set channel value"); + return RETURN_ERROR; + } } else { - size_t j = 0; - size_t size = ChannelValueTypeSize(value->value.array->type); - compConstant->values[i] = (ChannelValue *)mcx_calloc(value->value.array->numValues, - sizeof(ChannelValue)); - for (j = 0; j < value->value.array->numValues; j++) { - ChannelValueInit(compConstant->values[i] + j, value->value.array->type); - ChannelValueSetFromReference(compConstant->values[i] + j, - (char *)value->value.array->values + j * size); + compConstant->values[i] = ChannelValueNewArray(1, &value->value.array->numValues, value->value.array->type, value->value.array->values); + if (!compConstant->values[i]) { + ComponentLog(comp, LOG_ERROR, "Could not set channel value"); + return RETURN_ERROR; } } } @@ -62,20 +53,32 @@ static McxStatus Read(Component * comp, ComponentInput * input, const struct Con return RETURN_OK; } +static ChannelValue * GetValue(CompConstant * compConstant, size_t idx) { + Component * comp = (Component *) (compConstant); + Databus * db = comp->GetDatabus(comp); + size_t numOut = DatabusGetOutChannelsNum(db); + ChannelValue * value = NULL; + + if (idx >= numOut) { + ComponentLog(comp, LOG_ERROR, "GetValue: Invalid index (%zu) provided", idx); + return NULL; + } + + value = compConstant->values[idx]; + + return value; +} + static McxStatus Setup(Component * comp) { CompConstant * constComp = (CompConstant *)comp; McxStatus retVal = RETURN_OK; Databus * db = comp->GetDatabus(comp); - size_t numVecOut = DatabusGetOutVectorChannelsNum(db); + size_t numOut = DatabusGetOutChannelsNum(db); size_t i = 0; - for (i = 0; i < numVecOut; i++) { - VectorChannelInfo * vInfo = DatabusGetOutVectorChannelInfo(db, i); - size_t startIdx = vInfo->GetStartIndex(vInfo); - size_t endIdx = vInfo->GetEndIndex(vInfo); - size_t numCh = endIdx - startIdx; - retVal = DatabusSetOutRefVectorChannel(db, i, startIdx, endIdx, constComp->values[i]); + for (i = 0; i < numOut; i++) { + retVal = DatabusSetOutReference(db, i, (void *) &constComp->values[i]->value, constComp->values[i]->type); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register out channel reference"); return RETURN_ERROR; @@ -97,18 +100,12 @@ static void CompConstantDestructor(CompConstant * compConst) { Component * comp = (Component *)compConst; McxStatus retVal = RETURN_OK; Databus * db = comp->GetDatabus(comp); - size_t numVecOut = DatabusGetOutVectorChannelsNum(db); - - if (numVecOut > 0 && compConst->values != NULL) { - size_t i, j; - for (i = 0; i < numVecOut; i++) { - VectorChannelInfo * vInfo = DatabusGetOutVectorChannelInfo(db, i); - size_t startIdx = vInfo->GetStartIndex(vInfo); - size_t endIdx = vInfo->GetEndIndex(vInfo); - size_t numCh = endIdx - startIdx + 1; - for (j = 0; j < numCh; j++) { - ChannelValueDestructor(&compConst->values[i][j]); - } + size_t numOut = DatabusGetOutChannelsNum(db); + + if (numOut > 0 && compConst->values != NULL) { + size_t i; + for (i = 0; i < numOut; i++) { + ChannelValueDestructor(compConst->values[i]); mcx_free(compConst->values[i]); } mcx_free(compConst->values); @@ -118,13 +115,15 @@ static void CompConstantDestructor(CompConstant * compConst) { static Component * CompConstantCreate(Component * comp) { CompConstant * self = (CompConstant *)comp; - // map to local funciotns + // map to local functions comp->Read = Read; comp->Setup = Setup; comp->Initialize = Initialize; comp->GetFinishState = CompConstantGetFinishState; + // local functions + self->GetValue = GetValue; // local values self->values = NULL; diff --git a/src/components/comp_constant.h b/src/components/comp_constant.h index 46e5b14..5c2957e 100644 --- a/src/components/comp_constant.h +++ b/src/components/comp_constant.h @@ -12,13 +12,28 @@ #define MCX_COMPONENTS_COMP_CONSTANT_H #include "core/Component.h" +#include "core/channels/ChannelValue.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ + +typedef struct CompConstant CompConstant; + extern const struct ObjectClass _CompConstant; +typedef ChannelValue * (*fCompConstantGetValue)(CompConstant * compConstant, size_t idx); + +struct CompConstant { + Component _; + + fCompConstantGetValue GetValue; + + ChannelValue ** values; +}; + + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ diff --git a/src/components/comp_fmu.c b/src/components/comp_fmu.c index 4b3fee0..8b8cfff 100644 --- a/src/components/comp_fmu.c +++ b/src/components/comp_fmu.c @@ -13,12 +13,16 @@ #include "FMI/fmi_import_context.h" #include "components/comp_fmu_impl.h" #include "core/Databus.h" +#include "core/Component_impl.h" +#include "core/channels/ChannelInfo.h" +#include "core/connections/ConnectionInfoFactory.h" #include "fmilib.h" #include "fmu/Fmu1Value.h" #include "fmu/Fmu2Value.h" #include "objects/Map.h" #include "reader/model/components/specific_data/FmuInput.h" #include "util/string.h" +#include "util/signals.h" #ifdef __cplusplus extern "C" { @@ -46,46 +50,40 @@ static McxStatus Fmu1SetupDatabus(Component * comp) { numChannels = DatabusInfoGetChannelNum(dbInfo); vals = fmu1->in; for (i = 0; i < numChannels; i++) { + Channel * ch = (Channel *) DatabusGetInChannel(db, i); ChannelInfo * info = DatabusInfoGetChannel(dbInfo, i); + ChannelDimension * dimension = info->dimension; + ChannelType * type = info->type; - if (DatabusChannelInIsValid(db, i)) { + if (ch->IsConnected(ch) || ch->info.defaultValue) { Fmu1Value * val = NULL; fmi1_import_variable_t * var = NULL; jm_status_enu_t status = jm_status_success; - const char * channelName = info->GetNameInTool(info); + const char * channelName = info->nameInTool; if (NULL == channelName) { - channelName = info->GetName(info); + channelName = ChannelInfoGetName(info); } - var = fmi1_import_get_variable_by_name(fmu1->fmiImport, channelName); - if (!var) { - ComponentLog(comp, LOG_ERROR, "Could not get variable %s", channelName); - return RETURN_ERROR; + if (dimension) { // arrays + val = Fmu1ValueReadArray(comp->GetName(comp), type, info->channel, channelName, dimension, fmu1->fmiImport); + } else { // scalars + val = Fmu1ValueReadScalar(comp->GetName(comp), type, info->channel, channelName, fmu1->fmiImport); } - if (info->GetType(info) != Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var))) { - ComponentLog(comp, LOG_ERROR, "Variable types of %s do not match", channelName); - ComponentLog(comp, LOG_ERROR, "Expected: %s, Imported from FMU: %s", - ChannelTypeToString(info->GetType(info)), ChannelTypeToString(Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))); - return RETURN_ERROR; - } - - val = Fmu1ValueMake(channelName, var, info->channel); if (!val) { - ComponentLog(comp, LOG_ERROR, "Could not set value for channel %s", channelName); + ComponentLog(comp, LOG_ERROR, "Could not create value for channel %s", channelName); return RETURN_ERROR; } - retVal = vals->PushBackNamed(vals, (Object *)val, channelName); + retVal = vals->PushBackNamed(vals, (Object *) val, channelName); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not store value for %s", channelName); return RETURN_ERROR; } - retVal = DatabusSetInReference(comp->GetDatabus(comp), i, ChannelValueReference(&val->val), - ChannelValueType(&val->val)); + retVal = DatabusSetInReference(db, i, ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not set reference for channel %s", channelName); return RETURN_ERROR; @@ -98,43 +96,36 @@ static McxStatus Fmu1SetupDatabus(Component * comp) { vals = fmu1->out; for (i = 0; i < numChannels; i++) { ChannelInfo * info = DatabusInfoGetChannel(dbInfo, i); + ChannelDimension * dimension = info->dimension; + ChannelType * type = info->type; Fmu1Value * val = NULL; fmi1_import_variable_t * var = NULL; jm_status_enu_t status = jm_status_success; - const char * channelName = info->GetNameInTool(info); + const char * channelName = info->nameInTool; if (NULL == channelName) { - channelName = info->GetName(info); + channelName = ChannelInfoGetName(info); } - var = fmi1_import_get_variable_by_name(fmu1->fmiImport, channelName); - if (!var) { - ComponentLog(comp, LOG_ERROR, "Could not get variable %s", channelName); - return RETURN_ERROR; + if (dimension) { // arrays + val = Fmu1ValueReadArray(comp->GetName(comp), type, info->channel, channelName, dimension, fmu1->fmiImport); + } else { // scalars + val = Fmu1ValueReadScalar(comp->GetName(comp), type, info->channel, channelName, fmu1->fmiImport); } - if (info->GetType(info) != Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var))) { - ComponentLog(comp, LOG_ERROR, "Variable types of %s do not match", channelName); - ComponentLog(comp, LOG_ERROR, "Expected: %s, Imported from FMU: %s", - ChannelTypeToString(info->GetType(info)), ChannelTypeToString(Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))); - return RETURN_ERROR; - } - - val = Fmu1ValueMake(channelName, var, NULL); if (!val) { - ComponentLog(comp, LOG_ERROR, "Could not set value for channel %s", channelName); + ComponentLog(comp, LOG_ERROR, "Could not create value for channel %s", channelName); return RETURN_ERROR; } - retVal = vals->PushBack(vals, (Object *)val); + retVal = vals->PushBackNamed(vals, (Object *) val, channelName); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not store value for %s", channelName); return RETURN_ERROR; } - retVal = DatabusSetOutReference(comp->GetDatabus(comp), i, ChannelValueReference(&val->val), - ChannelValueType(&val->val)); + retVal = DatabusSetOutReference(db, i, ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not set reference for channel %s", channelName); return RETURN_ERROR; @@ -227,10 +218,12 @@ static McxStatus Fmu1Initialize(Component * comp, size_t group, double startTime // Initialization Mode ComponentLog(comp, LOG_DEBUG, "fmiInitializeSlave"); + mcx_signal_handler_set_function("fmi1_import_initialize_slave"); status = fmi1_import_initialize_slave(fmu1->fmiImport, startTime, fmi1_false, 0.0); + mcx_signal_handler_unset_function(); if (fmi1_status_ok != status) { ComponentLog(comp, LOG_ERROR, "fmiInitializeSlave failed"); return RETURN_ERROR; @@ -286,7 +279,9 @@ static McxStatus Fmu1DoStep(Component * comp, size_t group, double time, double } // Do calculations + mcx_signal_handler_set_function("fmi1_import_do_step"); status = fmi1_import_do_step(fmu1->fmiImport, compFmu->lastCommunicationTimePoint, deltaTime, fmi1_true); + mcx_signal_handler_unset_function(); if (fmi1_status_ok == status) { // fine } else if (fmi1_status_discard == status) { @@ -381,25 +376,21 @@ static McxStatus Fmu2SetupChannelIn(ObjectContainer /* Fmu2Values */ * vals, Dat numChannels = DatabusInfoGetChannelNum(dbInfo); for (i = 0; i < numChannels; i++) { + Channel * ch = (Channel *)DatabusGetInChannel(db, i); ChannelInfo * info = DatabusInfoGetChannel(dbInfo, i); Fmu2Value * val = (Fmu2Value *) vals->At(vals, i); - if (DatabusChannelInIsValid(db, i)) { - const char * channelName = info->GetNameInTool(info); - if (NULL == channelName) { - channelName = info->GetName(info); - } - + if (ch->IsConnected(ch) || ch->info.defaultValue) { val->SetChannel(val, info->channel); - if (val->val.type != info->GetType(info)) { - ChannelValueInit(&val->val, info->GetType(info)); + if (!ChannelTypeIsValid(val->val.type)) { + ChannelValueInit(&val->val, ChannelTypeClone(info->type)); } retVal = DatabusSetInReference(db, i, - ChannelValueReference(&val->val), + ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "%s: Could not set reference for channel %s", logPrefix, channelName); + mcx_log(LOG_ERROR, "%s: Could not set reference for channel %s", logPrefix, val->name); return RETURN_ERROR; } } @@ -423,16 +414,18 @@ static McxStatus Fmu2SetupChannelOut(ObjectContainer /* Fmu2Values */ * vals, Da ChannelInfo * info = DatabusInfoGetChannel(dbInfo, i); Fmu2Value * val = (Fmu2Value *) vals->At(vals, i); - const char * channelName = info->GetNameInTool(info); + const char * channelName = info->nameInTool; if (NULL == channelName) { - channelName = info->GetName(info); + channelName = ChannelInfoGetName(info); } - if (val->val.type != info->GetType(info)) { - ChannelValueInit(&val->val, info->GetType(info)); + val->SetChannel(val, info->channel); + + if (!ChannelTypeEq(val->val.type, info->type)) { + ChannelValueInit(&val->val, ChannelTypeClone(info->type)); } retVal = DatabusSetOutReference(db, i, - ChannelValueReference(&val->val), + ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "%s: Could not set reference for channel %s", logPrefix, channelName); @@ -509,13 +502,13 @@ static McxStatus Fmu2ReadChannelIn(ObjectContainer /* Fmu2Value */ * vals, Datab Fmu2Value * val = NULL; fmi2_import_variable_t * var = NULL; - const char * channelName = info->GetNameInTool(info); + const char * channelName = info->nameInTool; if (NULL == channelName) { - channelName = info->GetName(info); + channelName = ChannelInfoGetName(info); } // TODO: move content of if-else blocks to separate functions - if (info->IsBinary(info)) { + if (ChannelInfoIsBinary(info)) { // see https://github.com/OpenSimulationInterface/osi-sensor-model-packaging for more info char * channelNameLo = mcx_string_merge(2, channelName, ".base.lo"); char * channelNameHi = mcx_string_merge(2, channelName, ".base.hi"); @@ -543,24 +536,24 @@ static McxStatus Fmu2ReadChannelIn(ObjectContainer /* Fmu2Value */ * vals, Datab return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelNameLo); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))); return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelNameHi); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))); return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelNameSize); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))); return RETURN_ERROR; } @@ -573,32 +566,40 @@ static McxStatus Fmu2ReadChannelIn(ObjectContainer /* Fmu2Value */ * vals, Datab mcx_free(channelNameLo); mcx_free(channelNameHi); mcx_free(channelNameSize); - } else { // scalar - var = fmi2_import_get_variable_by_name(fmiImport, channelName); - if (!var) { - mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix, channelName); + + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); return RETURN_ERROR; } - - if (info->GetType(info) != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var))) { - mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelName); - mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, - ChannelTypeToString(info->GetType(info)), - ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))); + } else if (info->dimension) { + val = Fmu2ReadFmu2ArrayValue(logPrefix, info->type, channelName, info->dimension, info->unitString, fmiImport); + if (!val) { + mcx_log(LOG_ERROR, "%s: Could not create value for %s", logPrefix, channelName); return RETURN_ERROR; } - val = Fmu2ValueScalarMake(channelName, var, info->unitString, NULL); + val->SetChannel(val, info->channel); + + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); + return RETURN_ERROR; + } + } else { // scalar + val = Fmu2ReadFmu2ScalarValue(logPrefix, info->type, channelName, info->unitString, fmiImport); if (!val) { - mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix, channelName); + mcx_log(LOG_ERROR, "%s: Could not create value for %s", logPrefix, channelName); return RETURN_ERROR; } - } - retVal = vals->PushBack(vals, (Object *)val); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); - return RETURN_ERROR; + val->SetChannel(val, info->channel); + + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); + return RETURN_ERROR; + } } } @@ -620,12 +621,12 @@ static McxStatus Fmu2ReadChannelOut(ObjectContainer /* Fmu2Value */ * vals, Data Fmu2Value * val = NULL; fmi2_import_variable_t * var = NULL; - const char * channelName = info->GetNameInTool(info); + const char * channelName = info->nameInTool; if (NULL == channelName) { - channelName = info->GetName(info); + channelName = ChannelInfoGetName(info); } - if (info->IsBinary(info)) { + if (ChannelInfoIsBinary(info)) { char * channelNameLo = mcx_string_merge(2, channelName, ".base.lo"); char * channelNameHi = mcx_string_merge(2, channelName, ".base.hi"); char * channelNameSize = mcx_string_merge(2, channelName, ".size"); @@ -652,24 +653,24 @@ static McxStatus Fmu2ReadChannelOut(ObjectContainer /* Fmu2Value */ * vals, Data return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix , channelNameLo); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varLo)))); return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix , channelNameHi); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varHi)))); return RETURN_ERROR; } - if (CHANNEL_INTEGER != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize))) { + if (!ChannelTypeEq(&ChannelTypeInteger, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))) { mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix , channelNameSize); mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", - ChannelTypeToString(CHANNEL_INTEGER), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))); + ChannelTypeToString(&ChannelTypeInteger), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(varSize)))); return RETURN_ERROR; } @@ -682,32 +683,29 @@ static McxStatus Fmu2ReadChannelOut(ObjectContainer /* Fmu2Value */ * vals, Data mcx_free(channelNameLo); mcx_free(channelNameHi); mcx_free(channelNameSize); - } else { // scalar - var = fmi2_import_get_variable_by_name(fmiImport, channelName); - if (!var) { - mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix , channelName); + + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix , channelName); return RETURN_ERROR; } + } else if (info->dimension) { + val = Fmu2ReadFmu2ArrayValue(logPrefix, info->type, channelName, info->dimension, info->unitString, fmiImport); - if (info->GetType(info) != Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var))) { - mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix , channelName); - mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", - ChannelTypeToString(info->GetType(info)), ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))); + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); return RETURN_ERROR; } + } else { // scalar + val = Fmu2ReadFmu2ScalarValue(logPrefix, info->type, channelName, info->unitString, fmiImport); - val = Fmu2ValueScalarMake(channelName, var, info->unitString, NULL); - if (!val) { - mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix , channelName); + retVal = vals->PushBack(vals, (Object *)val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix, channelName); return RETURN_ERROR; } } - - retVal = vals->PushBack(vals, (Object *)val); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "%s: Could not store value for %s", logPrefix , channelName); - return RETURN_ERROR; - } } return RETURN_OK; @@ -795,20 +793,17 @@ static McxStatus Fmu2Read(Component * comp, ComponentInput * input, const struct ParametersInput * parametersInput = input->parameters; if (parametersInput) { - vals = Fmu2ReadParams(parametersInput, - compFmu->fmu2.fmiImport, - NULL + retVal = Fmu2ReadParams( + fmu2->params, + fmu2->arrayParams, + parametersInput, + compFmu->fmu2.fmiImport, + NULL ); - if (!vals) { - ComponentLog(comp, LOG_ERROR, "Could not read parameters"); - return RETURN_ERROR; - } - retVal = fmu2->params->Append(fmu2->params, vals); if (RETURN_OK != retVal) { - ComponentLog(comp, LOG_ERROR, "Could not add parameters"); + ComponentLog(comp, LOG_ERROR, "Could not read parameters"); return RETURN_ERROR; } - object_destroy(vals); } } @@ -817,17 +812,11 @@ static McxStatus Fmu2Read(Component * comp, ComponentInput * input, const struct ParametersInput * parametersInput = input->initialValues; if (parametersInput) { - vals = Fmu2ReadParams(parametersInput, compFmu->fmu2.fmiImport, NULL); - if (!vals) { - ComponentLog(comp, LOG_ERROR, "Could not read initial values"); - return RETURN_ERROR; - } - retVal = fmu2->initialValues->Append(fmu2->initialValues, vals); + retVal = Fmu2ReadParams(fmu2->initialValues, NULL, parametersInput, compFmu->fmu2.fmiImport, NULL); if (RETURN_OK != retVal) { - ComponentLog(comp, LOG_ERROR, "Could not add initial values"); + ComponentLog(comp, LOG_ERROR, "Could not read initial values"); return RETURN_ERROR; } - object_destroy(vals); } } @@ -852,6 +841,24 @@ static McxStatus Fmu2Read(Component * comp, ComponentInput * input, const struct return RETURN_OK; } +static McxStatus Fmu2CollectConnectedInputs(Component * comp) { + CompFMU * compFmu = (CompFMU *)comp; + size_t num = compFmu->fmu2.in->Size(compFmu->fmu2.in); + + for (size_t i = 0; i < num; i++) { + Fmu2Value * val = (Fmu2Value *)compFmu->fmu2.in->At(compFmu->fmu2.in, i); + + if (val->channel && val->channel->IsConnected(val->channel)) { + McxStatus retVal = compFmu->fmu2.connectedIn->PushBack(compFmu->fmu2.connectedIn, (Object *)val); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + } + } + + return RETURN_OK; +} + static McxStatus Fmu2Initialize(Component * comp, size_t group, double startTime) { CompFMU * compFmu = (CompFMU *) comp; int a = FALSE; @@ -863,21 +870,20 @@ static McxStatus Fmu2Initialize(Component * comp, size_t group, double startTime McxStatus retVal = RETURN_OK; - // Set variables - retVal = Fmu2SetVariableArray(fmu2, fmu2->params); + retVal = Fmu2SetVariableArrayInitialize(fmu2, fmu2->params); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting params failed"); return RETURN_ERROR; } - retVal = Fmu2SetVariableArray(fmu2, fmu2->initialValues); + retVal = Fmu2SetVariableArrayInitialize(fmu2, fmu2->initialValues); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting initialValues failed"); return RETURN_ERROR; } - retVal = Fmu2SetVariableArray(fmu2, fmu2->in); + retVal = Fmu2SetVariableArrayInitialize(fmu2, fmu2->in); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting inChannels failed"); return RETURN_ERROR; @@ -886,12 +892,14 @@ static McxStatus Fmu2Initialize(Component * comp, size_t group, double startTime defaultTolerance = fmi2_import_get_default_experiment_tolerance(fmu2->fmiImport); compFmu->lastCommunicationTimePoint = startTime; + mcx_signal_handler_set_function("fmi2_import_setup_experiment"); status = fmi2_import_setup_experiment(fmu2->fmiImport, fmi2_false, /* toleranceDefine */ defaultTolerance, startTime, /* startTime */ fmi2_false, /* stopTimeDefined */ 0.0 /* stopTime */); + mcx_signal_handler_unset_function(); if (fmi2_status_ok != status) { ComponentLog(comp, LOG_ERROR, "SetupExperiment failed"); @@ -899,20 +907,22 @@ static McxStatus Fmu2Initialize(Component * comp, size_t group, double startTime } // Initialization Mode + mcx_signal_handler_set_function("fmi2_import_enter_initialization_mode"); status = fmi2_import_enter_initialization_mode(fmu2->fmiImport); + mcx_signal_handler_unset_function(); if (fmi2_status_ok != status) { ComponentLog(comp, LOG_ERROR, "Could not enter Initialization Mode"); return RETURN_ERROR; } // Set variables - retVal = Fmu2SetVariableArray(fmu2, fmu2->initialValues); + retVal = Fmu2SetVariableArrayInitialize(fmu2, fmu2->initialValues); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting initialValues failed"); return RETURN_ERROR; } - retVal = Fmu2SetVariableArray(fmu2, fmu2->in); + retVal = Fmu2SetVariableArrayInitialize(fmu2, fmu2->in); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting inChannels failed"); return RETURN_ERROR; @@ -942,7 +952,9 @@ static McxStatus Fmu2Initialize(Component * comp, size_t group, double startTime static McxStatus Fmu2ExitInitializationMode(Component *comp) { CompFMU *compFmu = (CompFMU*)comp; + mcx_signal_handler_set_function("fmi2_import_exit_initialization_mode"); fmi2_status_t status = fmi2_import_exit_initialization_mode(compFmu->fmu2.fmiImport); + mcx_signal_handler_unset_function(); if (fmi2_status_ok != status) { ComponentLog(comp, LOG_ERROR, "Could not exit Initialization Mode"); return RETURN_ERROR; @@ -958,22 +970,28 @@ static McxStatus Fmu2DoStep(Component * comp, size_t group, double time, double McxStatus retVal; fmi2_status_t status = fmi2_status_ok; + TimeSnapshotStart(&comp->data->rtData.funcTimings.rtInput); // Set variables - retVal = Fmu2SetVariableArray(fmu2, fmu2->in); + retVal = Fmu2SetVariableArray(fmu2, fmu2->connectedIn); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Setting inChannels failed"); return RETURN_ERROR; } + TimeSnapshotEnd(&comp->data->rtData.funcTimings.rtInput); // Do calculations + mcx_signal_handler_set_function("fmi2_import_do_step"); status = fmi2_import_do_step(fmu2->fmiImport, compFmu->lastCommunicationTimePoint, deltaTime, fmi2_true); + mcx_signal_handler_unset_function(); if (fmi2_status_ok == status) { // fine } else if (fmi2_status_discard == status) { fmi2_status_t fmi2status; fmi2_boolean_t isTerminated = fmi2_false; + mcx_signal_handler_set_function("fmi2_import_get_boolean_status"); fmi2status = fmi2_import_get_boolean_status(fmu2->fmiImport, fmi2_terminated, &isTerminated); + mcx_signal_handler_unset_function(); if (fmi2_status_ok == fmi2status) { if (fmi2_true == isTerminated) { comp->SetIsFinished(comp); @@ -1008,22 +1026,6 @@ static McxStatus Fmu2DoStep(Component * comp, size_t group, double time, double compFmu->lastCommunicationTimePoint += deltaTime; - // Get outputs - retVal = Fmu2GetVariableArray(fmu2, fmu2->out); - if (RETURN_OK != retVal) { - ComponentLog(comp, LOG_ERROR, "Retrieving outChannels failed"); - return RETURN_ERROR; - } - - // local variables - if (compFmu->localValues) { - retVal = Fmu2GetVariableArray(fmu2, fmu2->localValues); - if (RETURN_OK != retVal) { - ComponentLog(comp, LOG_ERROR, "Retrieving local variables failed"); - return RETURN_ERROR; - } - } - return RETURN_OK; } @@ -1088,164 +1090,6 @@ static ChannelMode GetInChannelDefaultMode(struct Component * comp) { return CHANNEL_OPTIONAL; } -static McxStatus SetDependenciesFMU2(CompFMU *compFmu, struct Dependencies *deps) { - Component * comp = (Component *) compFmu; - McxStatus ret_val = RETURN_OK; - - size_t *start_index = NULL; - size_t *dependency = NULL; - char *factor_kind = NULL; - - size_t i = 0, j = 0, k = 0; - size_t num_dependencies = 0; - size_t dep_idx = 0; - - SizeTSizeTMap *dependencies_to_in_channels = (SizeTSizeTMap*)object_create(SizeTSizeTMap); - // dictionary used to store input connection information - SizeTSizeTMap *in_channel_connectivity = (SizeTSizeTMap*)object_create(SizeTSizeTMap); - SizeTSizeTMap *unknowns_to_out_channels = (SizeTSizeTMap*)object_create(SizeTSizeTMap); - // dictionary used to later find ommitted elements - SizeTSizeTMap *processed_out_channels = (SizeTSizeTMap*)object_create(SizeTSizeTMap); - - // get dependency information via the fmi library - fmi2_import_variable_list_t * init_unknowns = fmi2_import_get_initial_unknowns_list(compFmu->fmu2.fmiImport); - size_t num_init_unknowns = fmi2_import_get_variable_list_size(init_unknowns); - - fmi2_import_get_initial_unknowns_dependencies(compFmu->fmu2.fmiImport, &start_index, &dependency, &factor_kind); - - // the dependency information in is encoded via variable indices in modelDescription.xml - // our dependency matrix uses channel indices - // to align those 2 index types we use helper dictionaries which store the mapping between them - - // map each dependency index to an input channel index - ObjectContainer *in_vars = compFmu->fmu2.in; - size_t num_in_vars = in_vars->Size(in_vars); - - Databus * db = comp->GetDatabus(comp); - DatabusInfo * db_info = DatabusGetInInfo(db); - size_t num_in_channels = DatabusInfoGetChannelNum(db_info); - - for (i = 0; i < num_in_vars; ++i) { - Fmu2Value *val = (Fmu2Value *)in_vars->At(in_vars, i); - ChannelInfo * info = DatabusInfoGetChannel(db_info, i); - if (DatabusChannelInIsValid(db, k) && info->connected) { - // key i in the map means channel i is connected - in_channel_connectivity->Add(in_channel_connectivity, i, 1 /* true */); - } - - if (val->data->type == FMU2_VALUE_SCALAR) { - fmi2_import_variable_t *var = val->data->data.scalar; - size_t idx = fmi2_import_get_variable_original_order(var) + 1; - dependencies_to_in_channels->Add(dependencies_to_in_channels, idx, i); - } - } - - // element is not present in modelDescription.xml - // The dependency matrix consists of only 1 (if input is connected) - if (start_index == NULL) { - for (i = 0; i < GetDependencyNumOut(deps); ++i) { - for (j = 0; j < GetDependencyNumIn(deps); ++j) { - SizeTSizeTElem * elem = in_channel_connectivity->Get(in_channel_connectivity, j); - if (elem) { - ret_val = SetDependency(deps, j, i, DEP_DEPENDENT); - if (RETURN_OK != ret_val) { - goto cleanup; - } - } - } - } - - goto cleanup; - } - - // map each initial_unkown index to an output channel index - ObjectContainer *out_vars = compFmu->fmu2.out; - size_t num_out_vars = out_vars->Size(out_vars); - - for (i = 0; i < num_out_vars; ++i) { - Fmu2Value *val = (Fmu2Value *)out_vars->At(out_vars, i); - - if (val->data->type == FMU2_VALUE_SCALAR) { - fmi2_import_variable_t *var = val->data->data.scalar; - size_t idx = fmi2_import_get_variable_original_order(var) + 1; - unknowns_to_out_channels->Add(unknowns_to_out_channels, idx, i); - } - } - - // fill up the dependency matrix - for (i = 0; i < num_init_unknowns; ++i) { - fmi2_import_variable_t *init_unknown = fmi2_import_get_variable(init_unknowns, i); - size_t init_unknown_idx = fmi2_import_get_variable_original_order(init_unknown) + 1; - - SizeTSizeTElem * out_pair = unknowns_to_out_channels->Get(unknowns_to_out_channels, init_unknown_idx); - if (out_pair == NULL) { - continue; // in case some variables are ommitted from the input file - } - - processed_out_channels->Add(processed_out_channels, out_pair->value, 1); - - num_dependencies = start_index[i + 1] - start_index[i]; - for (j = 0; j < num_dependencies; ++j) { - dep_idx = dependency[start_index[i] + j]; - if (dep_idx == 0) { - // The element does not explicitly define a `dependencies` attribute - // In this case it depends on all inputs - for (k = 0; k < num_in_channels; ++k) { - SizeTSizeTElem * elem = in_channel_connectivity->Get(in_channel_connectivity, k); - if (elem) { - ret_val = SetDependency(deps, k, out_pair->value, DEP_DEPENDENT); - if (RETURN_OK != ret_val) { - goto cleanup; - } - } - } - } else { - // The element explicitly defines its dependencies - SizeTSizeTElem * in_pair = dependencies_to_in_channels->Get(dependencies_to_in_channels, dep_idx); - - if (in_pair) { - SizeTSizeTElem * elem = in_channel_connectivity->Get(in_channel_connectivity, in_pair->value); - if (elem) { - ret_val = SetDependency(deps, in_pair->value, out_pair->value, DEP_DEPENDENT); - if (RETURN_OK != ret_val) { - goto cleanup; - } - } - } - } - } - } - - // Initial unknowns which are ommitted from the element in - // modelDescription.xml file depend on all inputs - for (i = 0; i < num_out_vars; ++i) { - if (processed_out_channels->Get(processed_out_channels, i) == NULL) { - Fmu2Value *val = (Fmu2Value *)out_vars->At(out_vars, i); - - if (fmi2_import_get_initial(val->data->data.scalar) != fmi2_initial_enu_exact) { - for (k = 0; k < num_in_channels; ++k) { - SizeTSizeTElem * elem = in_channel_connectivity->Get(in_channel_connectivity, k); - if (elem) { - ret_val = SetDependency(deps, k, i, DEP_DEPENDENT); - if (RETURN_OK != ret_val) { - goto cleanup; - } - } - } - } - } - } - -cleanup: // free dynamically allocated objects - object_destroy(dependencies_to_in_channels); - object_destroy(in_channel_connectivity); - object_destroy(unknowns_to_out_channels); - object_destroy(processed_out_channels); - fmi2_import_free_variable_list(init_unknowns); - - return ret_val; -} - static struct Dependencies* Fmu2GetInOutGroupsInitialDependency(const Component * comp) { CompFMU *comp_fmu = (CompFMU *)comp; struct Dependencies *dependencies = NULL; @@ -1262,7 +1106,8 @@ static struct Dependencies* Fmu2GetInOutGroupsInitialDependency(const Component size_t dummy_num_out = 1; dependencies = DependenciesCreate(num_in, dummy_num_out); for (j = 0; j < num_in; ++j) { - if (DatabusChannelInIsValid(db, j)) { + Channel * ch = (Channel *) DatabusGetInChannel(db, j); + if (ch->IsConnected(ch) || ch->info.defaultValue) { retVal = SetDependency(dependencies, j, 0, DEP_DEPENDENT); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Initial dependency matrix for %s could not be created", comp->GetName(comp)); @@ -1272,7 +1117,7 @@ static struct Dependencies* Fmu2GetInOutGroupsInitialDependency(const Component } } else { dependencies = DependenciesCreate(num_in, num_out); - if (SetDependenciesFMU2(comp_fmu, dependencies) != RETURN_OK) { + if (Fmu2SetDependencies(&comp_fmu->fmu2, db, dependencies, TRUE) != RETURN_OK) { mcx_log(LOG_ERROR, "Initial dependency matrix for %s could not be created", comp->GetName(comp)); return NULL; } @@ -1287,6 +1132,7 @@ static McxStatus Fmu2UpdateOutChannels(Component * comp) { Fmu2CommonStruct * fmu2 = &comp_fmu->fmu2; McxStatus retVal; + TimeSnapshotStart(&comp->data->rtData.funcTimings.rtOutput); retVal = Fmu2GetVariableArray(fmu2, fmu2->out); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Initialization computation failed"); @@ -1298,6 +1144,7 @@ static McxStatus Fmu2UpdateOutChannels(Component * comp) { ComponentLog(comp, LOG_ERROR, "Initialization computation failed"); return RETURN_ERROR; } + TimeSnapshotEnd(&comp->data->rtData.funcTimings.rtOutput); return RETURN_OK; } @@ -1323,21 +1170,29 @@ static void CompFMUDestructor(CompFMU * compFmu) { // TOOD: Move this to the common struct destructors if (fmu1->fmiImport) { if (fmi1_true == fmu1->runOk) { + mcx_signal_handler_set_function("fmi1_import_terminate_slave"); fmi1_import_terminate_slave(fmu1->fmiImport); + mcx_signal_handler_unset_function(); } if (fmi1_true == fmu1->instantiateOk) { + mcx_signal_handler_set_function("fmi1_import_free_slave_instance"); fmi1_import_free_slave_instance(fmu1->fmiImport); + mcx_signal_handler_unset_function(); } } if (fmu2->fmiImport) { if (fmi2_true == fmu2->runOk) { + mcx_signal_handler_set_function("fmi2_import_terminate"); fmi2_import_terminate(fmu2->fmiImport); + mcx_signal_handler_unset_function(); } if (fmi2_true == fmu2->instantiateOk) { + mcx_signal_handler_set_function("fmi2_import_free_instance"); fmi2_import_free_instance(fmu2->fmiImport); + mcx_signal_handler_unset_function(); } } @@ -1359,6 +1214,8 @@ static Component * CompFMUCreate(Component * comp) { comp->DoStep = Fmu2DoStep; comp->Setup = CompFmuSetup; + comp->OnConnectionsDone = Fmu2CollectConnectedInputs; + comp->UpdateInChannels = Fmu2UpdateInChannels; comp->UpdateInitialOutChannels = Fmu2UpdateOutChannels; comp->UpdateOutChannels = Fmu2UpdateOutChannels; diff --git a/src/components/comp_integrator.c b/src/components/comp_integrator.c index 968c261..c05c538 100644 --- a/src/components/comp_integrator.c +++ b/src/components/comp_integrator.c @@ -56,13 +56,13 @@ static McxStatus Setup(Component * comp) { CompIntegrator * integrator = (CompIntegrator *) comp; McxStatus retVal = RETURN_OK; - retVal = DatabusSetInReference(comp->GetDatabus(comp), 0, &integrator->deriv, CHANNEL_DOUBLE); + retVal = DatabusSetInReference(comp->GetDatabus(comp), 0, &integrator->deriv, &ChannelTypeDouble); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register in channel reference"); return RETURN_ERROR; } - retVal = DatabusSetOutReference(comp->GetDatabus(comp), 0, &integrator->state, CHANNEL_DOUBLE); + retVal = DatabusSetOutReference(comp->GetDatabus(comp), 0, &integrator->state, &ChannelTypeDouble); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register out channel reference"); return RETURN_ERROR; diff --git a/src/components/comp_vector_integrator.c b/src/components/comp_vector_integrator.c index 57b6bc1..efd1ba7 100644 --- a/src/components/comp_vector_integrator.c +++ b/src/components/comp_vector_integrator.c @@ -11,6 +11,7 @@ #include "components/comp_vector_integrator.h" #include "core/Databus.h" +#include "core/channels/ChannelValue.h" #include "reader/model/components/specific_data/VectorIntegratorInput.h" #ifdef __cplusplus @@ -20,9 +21,10 @@ extern "C" { typedef struct CompVectorIntegrator { Component _; - size_t numStates; - double * state; - double * deriv; + size_t num; + + ChannelValue * state; + ChannelValue * deriv; double initialState; @@ -33,32 +35,52 @@ static McxStatus Read(Component * comp, ComponentInput * input, const struct Con CompVectorIntegrator * integrator = (CompVectorIntegrator *) comp; VectorIntegratorInput * integratorInput = (VectorIntegratorInput *) input; - size_t numAllIn = 0, numAllOut = 0; size_t i = 0; Databus * db = comp->GetDatabus(comp); - size_t numVecIn = DatabusGetInVectorChannelsNum(db); - size_t numVecOut = DatabusGetOutVectorChannelsNum(db); + size_t numIn = DatabusGetInChannelsNum(db); + size_t numOut = DatabusGetOutChannelsNum(db); - for (i = 0; i < numVecIn; i++) { - VectorChannelInfo *vInfo = DatabusGetInVectorChannelInfo(db, i); - size_t numCh = vInfo->GetEndIndex(vInfo) - vInfo->GetStartIndex(vInfo) + 1; - numAllIn += numCh; + if (numIn != numOut) { + ComponentLog(comp, LOG_ERROR, "#inports (%zu) does not match the #outports (%zu)", numIn, numOut); + return RETURN_ERROR; } - for (i = 0; i < numVecOut; i++) { - VectorChannelInfo *vInfo = DatabusGetOutVectorChannelInfo(db, i); - size_t numCh = vInfo->GetEndIndex(vInfo) - vInfo->GetStartIndex(vInfo) + 1; - numAllOut += numCh; + + integrator->num = numOut; + + integrator->deriv = mcx_calloc(sizeof(ChannelValue), integrator->num); + if (!integrator->deriv) { + return RETURN_ERROR; } - if (numAllIn != numAllOut) { - ComponentLog(comp, LOG_ERROR, "#inports (%d) does not match the #outports (%d)", numAllIn, numAllOut); + integrator->state = mcx_calloc(sizeof(ChannelValue), integrator->num); + if (!integrator->state) { return RETURN_ERROR; } - integrator->numStates = numAllOut; integrator->initialState = integratorInput->initialState.defined ? integratorInput->initialState.value : 0.0; + for (i = 0; i < integrator->num; i++) { + ChannelInfo * inInfo = DatabusGetInChannelInfo(db, i); + ChannelInfo * outInfo = DatabusGetOutChannelInfo(db, i); + + if (!ChannelTypeEq(inInfo->type, outInfo->type)) { + ComponentLog(comp, LOG_ERROR, "Types of inport %s and outport %s do not match", ChannelInfoGetName(inInfo), ChannelInfoGetName(outInfo)); + return RETURN_ERROR; + } + + ChannelInfo * info = outInfo; + ChannelType * type = info->type; + + if (!ChannelTypeEq(ChannelTypeBaseType(type), &ChannelTypeDouble)) { + ComponentLog(comp, LOG_ERROR, "Inport %s: Invalid type", ChannelInfoGetName(info)); + return RETURN_ERROR; + } + + ChannelValueInit(&integrator->deriv[i], ChannelTypeClone(type)); + ChannelValueInit(&integrator->state[i], ChannelTypeClone(type)); + } + return RETURN_OK; } @@ -66,40 +88,26 @@ static McxStatus Setup(Component * comp) { CompVectorIntegrator * integrator = (CompVectorIntegrator *) comp; McxStatus retVal = RETURN_OK; Databus * db = comp->GetDatabus(comp); - size_t numVecIn = DatabusGetInVectorChannelsNum(db); - size_t numVecOut = DatabusGetOutVectorChannelsNum(db); + size_t numIn = DatabusGetInChannelsNum(db); + size_t numOut = DatabusGetOutChannelsNum(db); size_t i = 0; - size_t nextIdx = 0; - - integrator->deriv = (double *) mcx_malloc(integrator->numStates * sizeof(double)); - integrator->state = (double *) mcx_malloc(integrator->numStates * sizeof(double)); - - nextIdx = 0; - for (i = 0; i < numVecIn; i++) { - VectorChannelInfo *vInfo = DatabusGetInVectorChannelInfo(db, i); - size_t startIdx = vInfo->GetStartIndex(vInfo); - size_t endIdx = vInfo->GetEndIndex(vInfo); - size_t numCh = endIdx - startIdx; - retVal = DatabusSetInRefVector(db, i, startIdx, endIdx, integrator->deriv + nextIdx, CHANNEL_DOUBLE); + + for (i = 0; i < integrator->num; i++) { + ChannelInfo * inInfo = DatabusGetInChannelInfo(db, i); + ChannelInfo * outInfo = DatabusGetOutChannelInfo(db, i); + + retVal = DatabusSetInReference(db, i, ChannelValueDataPointer(&integrator->deriv[i]), inInfo->type); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register in channel reference"); return RETURN_ERROR; } - nextIdx = nextIdx + numCh + 1; - } - nextIdx = 0; - for (i = 0; i < numVecOut; i++) { - VectorChannelInfo *vInfo = DatabusGetOutVectorChannelInfo(db, i); - size_t startIdx = vInfo->GetStartIndex(vInfo); - size_t endIdx = vInfo->GetEndIndex(vInfo); - size_t numCh = endIdx - startIdx; - retVal = DatabusSetOutRefVector(db, i, startIdx, endIdx, integrator->state + nextIdx, CHANNEL_DOUBLE); + retVal = DatabusSetOutReference(db, i, ChannelValueDataPointer(&integrator->state[i]), outInfo->type); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register out channel reference"); return RETURN_ERROR; } - nextIdx = nextIdx + numCh + 1; + } return RETURN_OK; @@ -109,8 +117,22 @@ static McxStatus Setup(Component * comp) { static McxStatus DoStep(Component * comp, size_t group, double time, double deltaTime, double endTime, int isNewStep) { CompVectorIntegrator * integrator = (CompVectorIntegrator *) comp; size_t i; - for (i = 0; i < integrator->numStates; i++) { - integrator->state[i] = integrator->state[i] + integrator->deriv[i] * deltaTime; + for (i = 0; i < integrator->num; i++) { + if (ChannelTypeIsArray(ChannelValueType(&integrator->state[i]))) { + mcx_array * state = ChannelValueDataPointer(&integrator->state[i]); + mcx_array * deriv = ChannelValueDataPointer(&integrator->deriv[i]); + + size_t j = 0; + for (j = 0; j < mcx_array_num_elements(state); j++) { + ((double *)state->data)[j] = ((double *)state->data)[j] + ((double *)deriv->data)[j] * deltaTime; + } + + } else { + double * state = (double *) ChannelValueDataPointer(&integrator->state[i]); + double * deriv = (double *) ChannelValueDataPointer(&integrator->deriv[i]); + + (*state) = (*state) + (*deriv) * deltaTime; + } } return RETURN_OK; @@ -120,8 +142,17 @@ static McxStatus DoStep(Component * comp, size_t group, double time, double delt static McxStatus Initialize(Component * comp, size_t idx, double startTime) { CompVectorIntegrator * integrator = (CompVectorIntegrator *) comp; size_t i; - for (i = 0; i < integrator->numStates; i++) { - integrator->state[i] = integrator->initialState; + for (i = 0; i < integrator->num; i++) { + if (ChannelTypeIsArray(ChannelValueType(&integrator->state[i]))) { + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&integrator->state[i]); + size_t j; + + for (j = 0; j < mcx_array_num_elements(a); j++) { + ((double *) a->data)[j] = integrator->initialState; + } + } else { + ChannelValueSetFromReference(&integrator->state[i], &integrator->initialState); + } } return RETURN_OK; } @@ -146,7 +177,7 @@ static Component * CompVectorIntegratorCreate(Component * comp) { // local values self->initialState = 0.; - self->numStates = 0; + self->num = 0; self->state = NULL; self->deriv = NULL; diff --git a/src/core/Component.c b/src/core/Component.c index ef09db6..305fee5 100644 --- a/src/core/Component.c +++ b/src/core/Component.c @@ -17,7 +17,6 @@ #include "core/Model.h" #include "core/channels/Channel.h" #include "core/channels/Channel_impl.h" -#include "core/connections/Connection_impl.h" #include "steptypes/StepType.h" #include "storage/ComponentStorage.h" #include "storage/ResultsStorage.h" @@ -57,7 +56,7 @@ void ComponentLog(const Component * comp, LogSeverity sev, const char * format, } } -McxStatus ComponentRead(Component * comp, ComponentInput * input) { +McxStatus ComponentRead(Component * comp, ComponentInput * input, const struct Config * const config) { InputElement * inputElement = (InputElement *)input; McxStatus retVal = RETURN_OK; @@ -149,6 +148,7 @@ McxStatus ComponentRead(Component * comp, ComponentInput * input) { if (input->results->rtFactor.defined) { comp->data->rtData.defined = TRUE; comp->data->rtData.enabled = input->results->rtFactor.value; + comp->data->rtData.funcTimings.profilingTimesEnabled = config->profilingMode; } retVal = comp->data->storage->Read(comp->data->storage, input->results); @@ -180,6 +180,7 @@ McxStatus ComponentSetup(Component * comp) { if (comp->data->model->task) { if (!comp->data->rtData.defined) { comp->data->rtData.enabled = comp->data->model->task->rtFactorEnabled; + comp->data->rtData.funcTimings.profilingTimesEnabled = comp->data->model->config->profilingMode; } if (comp->data->model->task->params) { @@ -201,87 +202,139 @@ McxStatus ComponentSetup(Component * comp) { if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not setup real time factor"); return RETURN_ERROR; - } + } + + return RETURN_OK; +} + +static McxStatus DefineTimingChannel(Component * comp, const char * chName, const char * unit, const void * reference) { + McxStatus retVal = RETURN_OK; + + char * id = CreateChannelID(comp->GetName(comp), chName); + if (!id) { + ComponentLog(comp, LOG_ERROR, "Could not create ID for timing port %s", chName); + return RETURN_ERROR; + } + + retVal = DatabusAddRTFactorChannel(comp->data->databus, chName, id, unit, reference, &ChannelTypeDouble); + + mcx_free(id); + + if (retVal == RETURN_ERROR) { + ComponentLog(comp, LOG_ERROR, "Could not add timing port %s", chName); + return RETURN_ERROR; + } return RETURN_OK; } static McxStatus ComponentSetupRTFactor(Component * comp) { - // Add rt factor if (comp->data->rtData.enabled) { - char * id = NULL; + McxStatus retVal = RETURN_OK; - id = CreateChannelID(comp->GetName(comp), "RealTime Clock"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Clock"); - return RETURN_ERROR; - } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Clock", id, GetTimeUnitString(), &comp->data->rtData.simTimeTotal, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Clock"); - mcx_free(id); + // RealTime channels + retVal = DefineTimingChannel(comp, "RealTime Clock", GetTimeUnitString(), &comp->data->rtData.rtTotalSum_s); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - mcx_free(id); - id = CreateChannelID(comp->GetName(comp), "RealTime Clock Calc"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Clock Calc"); + retVal = DefineTimingChannel(comp, "RealTime Clock Calc", GetTimeUnitString(), &comp->data->rtData.rtCalcSum_s); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Clock Calc", id, GetTimeUnitString(), &comp->data->rtData.simTime, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Clock Calc"); - mcx_free(id); + + retVal = DefineTimingChannel(comp, "RealTime Factor Calc", "-", &comp->data->rtData.rtFactorCalc); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - mcx_free(id); - id = CreateChannelID(comp->GetName(comp), "RealTime Factor Calc"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Factor Calc"); + retVal = DefineTimingChannel(comp, "RealTime Factor Calc (Avg)", "-", &comp->data->rtData.rtFactorCalcAvg); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Factor Calc", id, "-", &comp->data->rtData.rtFactor, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Factor Calc"); - mcx_free(id); + + retVal = DefineTimingChannel(comp, "RealTime Factor", "-", &comp->data->rtData.rtFactorTotal); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - mcx_free(id); - id = CreateChannelID(comp->GetName(comp), "RealTime Factor Calc (Avg)"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Factor Calc (Avg)"); + retVal = DefineTimingChannel(comp, "RealTime Factor (Avg)", "-", &comp->data->rtData.rtFactorTotalAvg); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Factor Calc (Avg)", id, "-", &comp->data->rtData.rtFactorAvg, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Factor Calc (Avg)"); - mcx_free(id); + + // Scheduling channels + retVal = DefineTimingChannel(comp, "CalcStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtCalc.startTime); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - mcx_free(id); - id = CreateChannelID(comp->GetName(comp), "RealTime Factor"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Factor"); + retVal = DefineTimingChannel(comp, "CalcEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtCalc.endTime); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Factor", id, "-", &comp->data->rtData.totalRtFactor, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Factor"); - mcx_free(id); + + retVal = DefineTimingChannel(comp, "SyncStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtSync.startTime); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - mcx_free(id); - id = CreateChannelID(comp->GetName(comp), "RealTime Factor (Avg)"); - if (!id) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not create ID for port %s", "RealTime Clock Calc"); + retVal = DefineTimingChannel(comp, "SyncEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtSync.endTime); + if (RETURN_ERROR == retVal) { return RETURN_ERROR; } - if (RETURN_ERROR == DatabusAddRTFactorChannel(comp->data->databus, "RealTime Factor (Avg)", id, "-", &comp->data->rtData.totalRtFactorAvg, CHANNEL_DOUBLE)) { - ComponentLog(comp, LOG_ERROR, "Setup real time factor: Could not add port %s", "RealTime Clock Calc"); - mcx_free(id); - return RETURN_ERROR; + + if (comp->data->rtData.funcTimings.profilingTimesEnabled) { + retVal = DefineTimingChannel(comp, "InputStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtInput.startTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "InputEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtInput.endTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "OutputStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtOutput.startTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "OutputEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtOutput.endTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "StoreStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtStore.snapshot.startTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "StoreEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtStore.snapshot.endTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "StoreInStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtStoreIn.snapshot.startTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "StoreInEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtStoreIn.snapshot.endTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "TriggerInStartWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtTriggerIn.startTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = DefineTimingChannel(comp, "TriggerInEndWallClockTime", "time~mys", &comp->data->rtData.funcTimings.rtTriggerIn.endTime); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } } - mcx_free(id); } return RETURN_OK; @@ -331,7 +384,7 @@ McxStatus ComponentRegisterStorage(Component * comp, ResultsStorage * storage) { for (i = 0; i < numInChannels; i++) { Channel * channel = (Channel *) DatabusGetInChannel(db, i); - if (channel->IsValid(channel)) { + if (channel->ProvidesValue(channel)) { retVal = compStore->RegisterChannel(compStore, CHANNEL_STORE_IN, channel); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Could not register inport %d at storage", i); @@ -386,10 +439,17 @@ static McxStatus ComponentStore(Component * comp, ChannelStoreType chType, doubl McxStatus ComponentInitialize(Component * comp, size_t group, double startTime) { comp->data->time = startTime; - comp->data->rtData.startTime = startTime; - mcx_time_get(&comp->data->rtData.startClock); - comp->data->rtData.lastDoStepClock = comp->data->rtData.startClock; - comp->data->rtData.lastCommDoStepClock = comp->data->rtData.startClock; + comp->data->rtData.simStartTime = startTime; + + return RETURN_OK; +} + +McxStatus ComponentBeforeDoSteps(Component * comp, void * param) { + FunctionTimingsSetGlobalSimStart(&comp->data->rtData.funcTimings, (McxTime *)param); + + mcx_time_get(&comp->data->rtData.rtCompStart); + comp->data->rtData.rtLastEndCalc = comp->data->rtData.rtCompStart; + comp->data->rtData.rtLastCompEnd = comp->data->rtData.rtCompStart; return RETURN_OK; } @@ -430,25 +490,28 @@ McxStatus ComponentUpdateOutChannels(Component * comp, TimeInterval * time) { McxStatus ComponentDoStep(Component * comp, size_t group, double time, double deltaTime, double endTime, int isNewStep) { McxStatus retVal = RETURN_OK; - McxTime start, end, diff; /* of this DoStep call */ double startTime; - McxTime totalDiff, totalDiffAvg; + McxTime rtTotal, rtTotalSum; if (comp->data->rtData.enabled) { /* data for local rt factor */ startTime = comp->GetTime(comp); - mcx_time_get(&start); + TimeSnapshotStart(&comp->data->rtData.funcTimings.rtCalc); } MCX_DEBUG_LOG("DoStep: %.16f -> %.16f", time, endTime); if (comp->DoStep) { mcx_signal_handler_set_name(comp->GetName(comp)); + mcx_signal_handler_set_this_function(); retVal = comp->DoStep(comp, group, time, deltaTime, endTime, isNewStep); + mcx_signal_handler_unset_function(); mcx_signal_handler_unset_name(); - if (RETURN_OK != retVal) { - ComponentLog(comp, LOG_DEBUG, "Component specific DoStep failed"); + if (RETURN_ERROR == retVal) { + ComponentLog(comp, LOG_ERROR, "Component specific DoStep failed"); return RETURN_ERROR; + } else if (RETURN_WARNING == retVal) { + ComponentLog(comp, LOG_DEBUG, "Component specific DoStep returned with a warning"); } } @@ -484,43 +547,39 @@ McxStatus ComponentDoStep(Component * comp, size_t group, double time, double de } if (comp->data->rtData.enabled) { + McxTime rtDeltaCalc; ComponentRTFactorData * rtData = &comp->data->rtData; - double timeDiff = endTime - rtData->startTime; + double simCalcSum = endTime - rtData->simStartTime; - /* wall time of this DoStep */ - mcx_time_get(&end); + TimeSnapshotEnd(&rtData->funcTimings.rtCalc); + mcx_time_diff(&rtData->funcTimings.rtCalc.start, &rtData->funcTimings.rtCalc.end, &rtDeltaCalc); // data for local rt factor - /* data for local rt factor */ - mcx_time_diff(&start, &end, &diff); + mcx_time_diff(&rtData->rtLastCompEnd, &rtData->funcTimings.rtCalc.end, &rtTotal); // data for total rt factor and avg rt factor + mcx_time_diff(&rtData->rtCompStart, &rtData->funcTimings.rtCalc.end, &rtTotalSum); - /* data for total rt factor and avg rt factor */ - mcx_time_diff(&rtData->lastCommDoStepClock, &end, &totalDiff); - mcx_time_diff(&rtData->startClock, &end, &totalDiffAvg); + rtData->rtLastEndCalc = rtData->funcTimings.rtCalc.end; // udpate wall clock for next dostep - /* udpate wall clock for next dostep */ - rtData->lastDoStepClock = end; + mcx_time_add(&rtData->rtCalcSum, &rtDeltaCalc, &rtData->rtCalcSum); // ticks of all DoSteps of this component since start + mcx_time_add(&rtData->rtCommStepTime, &rtDeltaCalc, &rtData->rtCommStepTime); // ticks of all DoSteps of this component for the current communication step - /* ticks of all DoSteps of this component since start */ - mcx_time_add(&rtData->simClock, &diff, &rtData->simClock); + /* time of all DoSteps of this component since start/for the current communication step */ + rtData->rtCalcSum_s = mcx_time_to_seconds(&rtData->rtCalcSum); + rtData->rtTotalSum_s = mcx_time_to_seconds(&rtTotalSum); - /* ticks of all DoSteps of this component for the current communication step */ - mcx_time_add(&rtData->stepClock, &diff, &rtData->stepClock); + rtData->rtCommStepTime_s = mcx_time_to_seconds(&rtData->rtCommStepTime); - /* time of all DoSteps of this component since start/for the current communication step */ - rtData->simTime = mcx_time_to_seconds(&rtData->simClock); - rtData->simTimeTotal = mcx_time_to_seconds(&totalDiffAvg); - rtData->stepTime = mcx_time_to_seconds(&rtData->stepClock); + rtData->simCommStepTime += comp->GetTime(comp) - startTime; // simulation time of the current communication time step + + rtData->rtFactorCalc = rtData->rtCommStepTime_s / rtData->simCommStepTime; + rtData->rtFactorCalcAvg = rtData->rtCalcSum_s / simCalcSum; - /* simulation time of the current communication time step */ - rtData->commTime += comp->GetTime(comp) - startTime; + // Total = (all components + framework) rt factor + // Sum = from simulation begin - /* local (only this component) rt factor */ - rtData->rtFactor = rtData->stepTime / rtData->commTime; - rtData->rtFactorAvg = rtData->simTime / timeDiff; + rtData->rtFactorTotal = mcx_time_to_seconds(&rtTotal) / rtData->simCommStepTime; + rtData->rtFactorTotalAvg = rtData->rtTotalSum_s / simCalcSum; - /* total (all components + framework) rt factor */ - rtData->totalRtFactor = mcx_time_to_seconds(&totalDiff) / rtData->commTime; - rtData->totalRtFactorAvg = mcx_time_to_seconds(&totalDiffAvg) / timeDiff; + FunctionTimingsCalculateTimeDiffs(&rtData->funcTimings); } return RETURN_OK; @@ -558,13 +617,80 @@ static size_t ComponentGetNumWriteRTFactorChannels(const Component * comp) { return DatabusInfoGetNumWriteChannels(DatabusGetRTFactorInfo(comp->data->databus)); } +static size_t ComponentGetNumObservableChannels(const Component * comp) { + size_t num = 0; + + num += DatabusGetOutChannelsNum(comp->data->databus); + num += DatabusGetInChannelsNum(comp->data->databus); + num += DatabusGetLocalChannelsNum(comp->data->databus); + num += DatabusGetRTFactorChannelsNum(comp->data->databus); + + return num; +} + +static McxStatus AddObservableChannels(const Component * comp, StringContainer * container, size_t * count) { + size_t numOut = comp->GetNumOutChannels(comp); + size_t numIn = comp->GetNumInChannels(comp); + size_t numLocal = comp->GetNumLocalChannels(comp); + size_t numRTFactor = comp->GetNumRTFactorChannels(comp); + + size_t i = 0; + Databus * db = comp->GetDatabus(comp); + + for (i = 0; i < numOut; i++) { + Channel * channel = (Channel *) DatabusGetOutChannel(db, i); + char * id = channel->info.id; + + if (NULL != id) { + StringContainerSetKeyValue(container, *count, id, channel); + (*count)++; + } + } + + for (i = 0; i < numIn; i++) { + Channel * channel = (Channel *) DatabusGetInChannel(db, i); + char * id = channel->info.id; + int isValid = channel->IsConnected(channel) || channel->info.defaultValue; + + if (NULL != id && isValid) { + StringContainerSetKeyValue(container, *count, id, channel); + (*count)++; + } + } + + for (i = 0; i < numLocal; i++) { + Channel * channel = (Channel *) DatabusGetLocalChannel(db, i); + char * id = channel->info.id; + int isValid = channel->ProvidesValue(channel); + + if (NULL != id && isValid) { + StringContainerSetKeyValue(container, *count, id, channel); + (*count)++; + } + } + + for (i = 0; i < numRTFactor; i++) { + Channel * channel = (Channel *) DatabusGetRTFactorChannel(db, i); + char * id = channel->info.id; + int isValid = channel->ProvidesValue(channel); + + if (NULL != id && isValid) { + StringContainerSetKeyValue(container, *count, id, channel); + (*count)++; + } + } + + return RETURN_OK; +} + + static size_t ComponentGetNumConnectedOutChannels(const Component * comp) { size_t count = 0; size_t i = 0; for (i = 0; (int) i < DatabusInfoGetChannelNum(DatabusGetOutInfo(comp->data->databus)); i++) { Channel * channel = (Channel *) DatabusGetOutChannel(comp->data->databus, i); - if (channel->IsValid(channel)) { + if (channel->IsConnected(channel)) { count++; } } @@ -670,32 +796,38 @@ struct Dependencies * ComponentGetInOutGroupsNoDependency(const Component * comp McxStatus ComponentEnterCommunicationPoint(Component * comp, TimeInterval * time) { McxStatus retVal = RETURN_OK; + ComponentRTFactorData * rtData = &comp->data->rtData; + + mcx_time_init(&rtData->rtCommStepTime); + rtData->simCommStepTime = 0; + rtData->rtLastCompEnd = rtData->rtLastEndCalc; - mcx_time_init(&comp->data->rtData.stepClock); - comp->data->rtData.commTime = 0; - comp->data->rtData.lastCommDoStepClock = comp->data->rtData.lastDoStepClock; + TimeSnapshotStart(&rtData->funcTimings.rtSync); retVal = DatabusEnterCommunicationMode(comp->data->databus, time->startTime); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Cannot enter communication mode at time %.17g s", time->startTime); return RETURN_ERROR; } - ComponentUpdateOutChannels(comp, time); + TimeSnapshotEnd(&rtData->funcTimings.rtSync); return RETURN_OK; } -McxStatus ComponentEnterCommunicationPointForConnections(Component * comp, ObjectContainer * connections, TimeInterval * time) { +McxStatus ComponentEnterCommunicationPointForConnections(Component * comp, ObjectList * connections, TimeInterval * time) { McxStatus retVal = RETURN_OK; + ComponentRTFactorData * rtData = &comp->data->rtData; - mcx_time_init(&comp->data->rtData.stepClock); - comp->data->rtData.commTime = 0; - comp->data->rtData.lastCommDoStepClock = comp->data->rtData.lastDoStepClock; + mcx_time_init(&rtData->rtCommStepTime); + rtData->simCommStepTime = 0; + rtData->rtLastCompEnd = rtData->rtLastEndCalc; + + TimeSnapshotStart(&rtData->funcTimings.rtSync); retVal = DatabusEnterCommunicationModeForConnections(comp->data->databus, connections, time->startTime); if (RETURN_OK != retVal) { ComponentLog(comp, LOG_ERROR, "Cannot enter communication mode for connections at time %.17g s", time->startTime); return RETURN_ERROR; } - ComponentUpdateOutChannels(comp, time); + TimeSnapshotEnd(&rtData->funcTimings.rtSync); return RETURN_OK; } @@ -708,22 +840,22 @@ static void ComponentSetModel(Component * comp, Model * model) { comp->data->model = model; } -ConnectionInfo * GetInConnectionInfo(const Component * comp, size_t channelID) { +Vector * GetInConnectionInfos(const Component * comp, size_t channelID) { size_t channelNum = DatabusInfoGetChannelNum(DatabusGetInInfo(comp->data->databus)); if (channelID < channelNum) { ChannelIn * in = DatabusGetInChannel(comp->data->databus, channelID); - return in->GetConnectionInfo(in); + return in->GetConnectionInfos(in); } return NULL; } -Connection * GetInConnection(const Component * comp, size_t channelID) { +ConnectionList * GetInConnections(const Component * comp, size_t channelID) { size_t channelNum = DatabusInfoGetChannelNum(DatabusGetInInfo(comp->data->databus)); if (channelID < channelNum) { ChannelIn * in = DatabusGetInChannel(comp->data->databus, channelID); - return in->GetConnection(in); + return in->GetConnections(in); } return NULL; @@ -826,13 +958,13 @@ static int ComponentGetSequenceNumber(const Component * comp) { return comp->data->triggerSequence; } -static ObjectContainer * ComponentGetConnections(Component * fromComp, Component * toComp) { +static ObjectList * ComponentGetConnections(Component * fromComp, Component * toComp) { size_t i = 0; size_t j = 0; McxStatus retVal = RETURN_OK; struct Databus * db = fromComp->GetDatabus(fromComp); - ObjectContainer * connections = (ObjectContainer *) object_create(ObjectContainer); + ObjectList * connections = (ObjectList *) object_create(ObjectList); if (!connections) { return NULL; @@ -840,13 +972,13 @@ static ObjectContainer * ComponentGetConnections(Component * fromComp, Component for (i = 0; i < DatabusGetOutChannelsNum(db); i++) { ChannelOut * out = DatabusGetOutChannel(db, i); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (j = 0; j < conns->Size(conns); j++) { - Connection * conn = (Connection *) conns->At(conns, j); + for (j = 0; j < conns->numConnections; j++) { + Connection * conn = conns->connections[j]; ConnectionInfo * info = conn->GetInfo(conn); - if (info->GetTargetComponent(info) == toComp) { + if (info->targetComponent == toComp) { retVal = connections->PushBack(connections, (Object *) conn); if (RETURN_OK != retVal) { ComponentLog(fromComp, LOG_ERROR, "Could not collect connections"); @@ -881,10 +1013,10 @@ McxStatus ComponentOutConnectionsEnterInitMode(Component * comp) { for (i = 0; i < numOutChannels; i++) { ChannelOut * out = DatabusGetOutChannel(db, i); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); + for (j = 0; j < conns->numConnections; j++) { + Connection * connection = conns->connections[j]; retVal = connection->EnterInitializationMode(connection); if (RETURN_OK != retVal) { // error message in calling function return RETURN_ERROR; @@ -901,10 +1033,10 @@ McxStatus ComponentDoOutConnectionsInitialization(Component * comp, int onlyIfDe for (i = 0; i < numOutChannels; i++) { ChannelOut * out = DatabusGetOutChannel(db, i); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); + for (j = 0; j < conns->numConnections; j++) { + Connection * connection = conns->connections[j]; if (!onlyIfDecoupled || connection->IsDecoupled(connection)) { McxStatus retVal = connection->UpdateInitialValue(connection); @@ -928,10 +1060,10 @@ McxStatus ComponentOutConnectionsExitInitMode(Component * comp, double time) { for (i = 0; i < numOutChannels; i++) { ChannelOut * out = DatabusGetOutChannel(db, i); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); + for (j = 0; j < conns->numConnections; j++) { + Connection * connection = conns->connections[j]; retVal = connection->ExitInitializationMode(connection, time); if (RETURN_OK != retVal) { // error message in calling function return RETURN_ERROR; @@ -1015,7 +1147,7 @@ Component * CreateComponentFromComponentInput(ComponentFactory * factory, } // General Data - retVal = ComponentRead(comp, componentInput); + retVal = ComponentRead(comp, componentInput, config); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Model: Could not create element data"); object_destroy(comp); @@ -1073,6 +1205,7 @@ static Component * ComponentCreate(Component * comp) { comp->Store = ComponentStore; comp->DoStep = NULL; + comp->PostDoStep = NULL; comp->Finish = NULL; comp->GetNumInChannels = ComponentGetNumInChannels; @@ -1106,6 +1239,8 @@ static Component * ComponentCreate(Component * comp) { comp->SetModel = ComponentSetModel; + comp->ContainsComponent = NULL; + comp->GetDatabus = ComponentGetDatabus; comp->GetName = ComponentGetName; comp->GetModel = ComponentGetModel; @@ -1153,9 +1288,119 @@ static Component * ComponentCreate(Component * comp) { comp->data->typeString = NULL; + StepTypeSynchronizationInit(&comp->syncHints); + + comp->GetNumObservableChannels = ComponentGetNumObservableChannels; + comp->AddObservableChannels = AddObservableChannels; + + comp->OnConnectionsDone = NULL; + return comp; } +void TimeSnapshotStart(TimeSnapshot * snapshot) { + if (!snapshot->enabled) { + return; + } + + mcx_time_get(&snapshot->start); +} + +void TimeSnapshotEnd(TimeSnapshot * snapshot) { + if (!snapshot->enabled) { + return; + } + + mcx_time_get(&snapshot->end); +} + +static void TimeSnapshotDiffToMicroSeconds(TimeSnapshot * snapshot, McxTime * startTimePoint) { + McxTime start; + McxTime end; + + mcx_time_diff(startTimePoint, &snapshot->start, &start); + mcx_time_diff(startTimePoint, &snapshot->end, &end); + + snapshot->startTime = mcx_time_to_micro_s(&start); + snapshot->endTime = mcx_time_to_micro_s(&end); + + snapshot->startTime = snapshot->startTime < 0.0 ? 0.0 : snapshot->startTime; + snapshot->endTime = snapshot->endTime < 0.0 ? 0.0 : snapshot->endTime; +} + +static void TimeSnapshotInit(TimeSnapshot * snapshot) { + snapshot->enabled = FALSE; + + mcx_time_init(&snapshot->start); + mcx_time_init(&snapshot->end); + + snapshot->startTime = 0.0; + snapshot->endTime = 0.0; +} + +static void DelayedTimeSnapshotInit(DelayedTimeSnapshot * snapshot) { + TimeSnapshotInit(&snapshot->snapshot); + + snapshot->startTimePre = 0.0; + snapshot->endTimePre = 0.0; +} + +static void DelayedTimeSnapshotDiffToMicroSeconds(DelayedTimeSnapshot * snapshot, McxTime * startTimePoint) { + McxTime start; + McxTime end; + + snapshot->snapshot.startTime = snapshot->startTimePre; + snapshot->snapshot.endTime = snapshot->endTimePre;; + + mcx_time_diff(startTimePoint, &snapshot->snapshot.start, &start); + mcx_time_diff(startTimePoint, &snapshot->snapshot.end, &end); + + snapshot->startTimePre = mcx_time_to_micro_s(&start); + snapshot->endTimePre = mcx_time_to_micro_s(&end); +} + +void FunctionTimingsCalculateTimeDiffs(FunctionTimings * timings) { + TimeSnapshotDiffToMicroSeconds(&timings->rtCalc, &timings->rtGlobalSimStart); + TimeSnapshotDiffToMicroSeconds(&timings->rtSync, &timings->rtGlobalSimStart); + + TimeSnapshotDiffToMicroSeconds(&timings->rtInput, &timings->rtGlobalSimStart); + TimeSnapshotDiffToMicroSeconds(&timings->rtOutput, &timings->rtGlobalSimStart); + TimeSnapshotDiffToMicroSeconds(&timings->rtTriggerIn, &timings->rtGlobalSimStart); + + DelayedTimeSnapshotDiffToMicroSeconds(&timings->rtStore, &timings->rtGlobalSimStart); + DelayedTimeSnapshotDiffToMicroSeconds(&timings->rtStoreIn, &timings->rtGlobalSimStart); +} + +void FunctionTimingsSetGlobalSimStart(FunctionTimings * timings, McxTime * simStart) { + timings->rtGlobalSimStart = *simStart; + + timings->rtCalc.enabled = TRUE; + timings->rtSync.enabled = TRUE; + + timings->rtInput.enabled = TRUE; + timings->rtOutput.enabled = TRUE; + timings->rtTriggerIn.enabled = TRUE; + + timings->rtStore.snapshot.enabled = TRUE; + timings->rtStoreIn.snapshot.enabled = TRUE; +} + +static void FunctionTimingsInit(FunctionTimings * timings) { + mcx_time_init(&timings->rtGlobalSimStart); + + timings->profilingTimesEnabled = FALSE; + + TimeSnapshotInit(&timings->rtCalc); + TimeSnapshotInit(&timings->rtSync); + + TimeSnapshotInit(&timings->rtInput); + TimeSnapshotInit(&timings->rtOutput); + TimeSnapshotInit(&timings->rtTriggerIn); + + DelayedTimeSnapshotInit(&timings->rtStore); + DelayedTimeSnapshotInit(&timings->rtStoreIn); +} + static void ComponentDataDestructor(ComponentData * data) { object_destroy(data->databus); @@ -1200,24 +1445,28 @@ static ComponentData * ComponentDataCreate(ComponentData * data) { rtData->defined = FALSE; rtData->enabled = FALSE; - mcx_time_init(&rtData->simClock); - mcx_time_init(&rtData->stepClock); + mcx_time_init(&rtData->rtCalcSum); + mcx_time_init(&rtData->rtCommStepTime); + + rtData->rtCalcSum_s = 0.; + rtData->rtTotalSum_s = 0.; + + rtData->rtCommStepTime_s = 0.; + + rtData->simStartTime = 0.; + rtData->simCommStepTime = 0.; - rtData->simTime = 0.; - rtData->simTimeTotal = 0.; - rtData->stepTime = 0.; - rtData->startTime = 0.; - rtData->commTime = 0.; + rtData->rtFactorCalc = 0.; + rtData->rtFactorCalcAvg = 0.; - rtData->rtFactor = 0.; - rtData->rtFactorAvg = 0.; + mcx_time_init(&rtData->rtCompStart); + mcx_time_init(&rtData->rtLastEndCalc); + mcx_time_init(&rtData->rtLastCompEnd); - mcx_time_init(&rtData->startClock); - mcx_time_init(&rtData->lastDoStepClock); - mcx_time_init(&rtData->lastCommDoStepClock); + FunctionTimingsInit(&rtData->funcTimings); - rtData->totalRtFactor = 0.; - rtData->totalRtFactorAvg = 0.; + rtData->rtFactorTotal = 0.; + rtData->rtFactorTotalAvg = 0.; data->hasOwnInputEvaluationTime = FALSE; data->useInputsAtCouplingStepEndTime = FALSE; diff --git a/src/core/Component.h b/src/core/Component.h index 406dfd2..997d330 100644 --- a/src/core/Component.h +++ b/src/core/Component.h @@ -16,13 +16,15 @@ #include "core/Component_interface.h" #include "core/Dependency.h" #include "objects/StringContainer.h" +#include "objects/Vector.h" #include "reader/model/components/ComponentInput.h" +#include "core/connections/ConnectionInfo.h" +#include "steptypes/StepType.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ - typedef enum ComponentFinishState { COMP_IS_FINISHED, COMP_IS_NOT_FINISHED, @@ -34,7 +36,6 @@ struct Model; struct ComponentData; struct ChannelInfo; struct Connection; -struct ConnectionInfo; struct StepTypeParams; struct ResultsStorage; struct ComponentStorage; @@ -49,9 +50,12 @@ typedef McxStatus (* fComponentUpdateOutChannels)(Component * comp); typedef McxStatus (* fComponentUpdateInChannels)(Component * comp); +typedef int (* fComponentContainsComponent)(Component * comp, const Component * otherComp); + typedef struct ComponentStorage * (* fComponentGetStorage)(const Component * comp); typedef McxStatus (* fComponentDoStep)(Component * comp, size_t group, double time, double deltaTime, double endTime, int isNewStep); +typedef McxStatus (*fComponentPostDoStep)(Component * comp); typedef McxStatus (* fComponentFinish)(Component * comp, FinishState * finishState); typedef size_t (* fComponentGetNumber)(const Component * comp); @@ -72,13 +76,15 @@ typedef int (* fComponentOneOutputOneGroup)(Component * comp); typedef ComponentFinishState (* fComponentGetFinishState)(const Component * comp); typedef void (* fComponentSetIsFinished)(Component * comp); +typedef McxStatus (* fOnConnectionsDone)(Component* comp); + typedef struct Databus * (* fComponentGetDatabus)(const Component * comp); typedef const char * (* fComponentGetName)(const Component * comp); typedef struct Model * (* fComponentGetModel)(const Component * comp); typedef size_t (* fComponentGetID)(const Component * comp); typedef int (* fComponentGetSequenceNumber)(const Component * comp); typedef int (* fComponentGetCPUIdx)(const Component * comp); -typedef ObjectContainer * (*fComponentGetConnections)(Component * fromComp, Component * toComp); +typedef ObjectList * (*fComponentGetConnections)(Component * fromComp, Component * toComp); typedef struct PpdLink * (* fGetPPDLink)(struct Component * comp); typedef ChannelMode (* fGetChannelDefaultMode)(struct Component * comp); @@ -100,6 +106,8 @@ typedef McxStatus (*fComponentSetDouble)(Component * comp, double offset); typedef void (*fComponentSetIsPartOfInitCalculation)(Component * comp, int isPartOfInitCalculation); +typedef McxStatus (* fAddObservableChannels)(const Component * comp, StringContainer * container, size_t * count); + extern const struct ObjectClass _Component; struct Component { @@ -136,6 +144,7 @@ struct Component { fComponentStore Store; fComponentDoStep DoStep; + fComponentPostDoStep PostDoStep; fComponentFinish Finish; // Read and Setup Channels @@ -189,6 +198,8 @@ struct Component { fComponentSetModel SetModel; + fComponentContainsComponent ContainsComponent; + fComponentGetDatabus GetDatabus; fComponentGetName GetName; fComponentGetName GetType; @@ -212,19 +223,27 @@ struct Component { fComponentSetDouble SetResultTimeOffset; + fComponentGetNumber GetNumObservableChannels; + fAddObservableChannels AddObservableChannels; + + fOnConnectionsDone OnConnectionsDone; + struct ComponentData * data; + + StepTypeSynchronization syncHints; }; /* these functions have to be called by subclasses */ void ComponentLog(const Component * comp, LogSeverity sev, const char * format, ...); -McxStatus ComponentRead(Component * comp, ComponentInput * input); +McxStatus ComponentRead(Component * comp, ComponentInput * input, const struct Config * const config); McxStatus ComponentSetup(Component * comp); McxStatus ComponentRegisterStorage(Component* comp, struct ResultsStorage* storage); McxStatus ComponentInitialize(Component * comp, size_t group, double startTime); McxStatus ComponentExitInitializationMode(Component * comp); +McxStatus ComponentBeforeDoSteps(Component * comp, void * param); McxStatus ComponentUpdateOutChannels(Component * comp, TimeInterval * time); @@ -233,10 +252,10 @@ McxStatus ComponentDoStep(Component * comp, size_t group, double time, double de McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, struct StepTypeParams * params); McxStatus ComponentEnterCommunicationPoint(Component * comp, TimeInterval * time); -McxStatus ComponentEnterCommunicationPointForConnections(Component * comp, ObjectContainer * connections, TimeInterval * time); +McxStatus ComponentEnterCommunicationPointForConnections(Component * comp, ObjectList * connections, TimeInterval * time); -struct ConnectionInfo * GetInConnectionInfo(const Component * comp, size_t channelID); -struct Connection * GetInConnection(const Component * comp, size_t channelID); +Vector * GetInConnectionInfos(const Component * comp, size_t channelID); +struct ConnectionList * GetInConnections(const Component * comp, size_t channelID); size_t ComponentGetNumOutGroups(const Component * comp); size_t ComponentGetNumInitialOutGroups(const Component * comp); diff --git a/src/core/Component_impl.h b/src/core/Component_impl.h index f680118..4eb5098 100644 --- a/src/core/Component_impl.h +++ b/src/core/Component_impl.h @@ -24,6 +24,50 @@ extern "C" { struct Model; struct Databus; +typedef struct { + int enabled; + + McxTime start; + McxTime end; + + double startTime; + double endTime; +} TimeSnapshot; + + +void TimeSnapshotStart(TimeSnapshot * snapshot); +void TimeSnapshotEnd(TimeSnapshot * snapshot); + + +typedef struct { + TimeSnapshot snapshot; + + double startTimePre; + double endTimePre; +} DelayedTimeSnapshot; + + +typedef struct { + McxTime rtGlobalSimStart; // wall clock of start of simulation + + TimeSnapshot rtCalc; + TimeSnapshot rtSync; + + int profilingTimesEnabled; + + TimeSnapshot rtInput; + TimeSnapshot rtOutput; + TimeSnapshot rtTriggerIn; + + DelayedTimeSnapshot rtStore; + DelayedTimeSnapshot rtStoreIn; +} FunctionTimings; + + +void FunctionTimingsCalculateTimeDiffs(FunctionTimings * timings); +void FunctionTimingsSetGlobalSimStart(FunctionTimings * timings, McxTime * simStart); + + typedef struct ComponentRTFactorData ComponentRTFactorData; struct ComponentRTFactorData { @@ -33,27 +77,31 @@ struct ComponentRTFactorData { int defined; int enabled; - McxTime simClock; /* ticks in doStep since simulation start */ - McxTime stepClock; /* ticks in the current communication step */ + McxTime rtCalcSum; // ticks in doStep since simulation start + double rtCalcSum_s; // time in doSteps since simulation start + + McxTime rtCommStepTime; // ticks in the current communication step + double rtCommStepTime_s; // time in the current communication step + + double simCommStepTime; // simulated time in current communication step + + double rtTotalSum_s; // time since initialize + + double simStartTime; // start time of simulation - double simTime; /* time in doStep since simulation start */ - double simTimeTotal; /* time since initialize */ - double stepTime; /* time in the current communication step */ + double rtFactorCalc; + double rtFactorCalcAvg; - double startTime; /* start time of simulation */ - double commTime; /* simulated time in current communication step */ + double rtFactorTotal; + double rtFactorTotalAvg; - double rtFactor; - double rtFactorAvg; + McxTime rtCompStart; // wall clock of start of component - McxTime startClock; /* wall clock of start of simulation */ - McxTime lastDoStepClock; /* wall clock of last DoStep */ + McxTime rtLastEndCalc; // wall clock of last Calc End - /* wall clock of last DoStep before entering communication mode */ - McxTime lastCommDoStepClock; + McxTime rtLastCompEnd; // wall clock of last DoStep before entering communication mode - double totalRtFactor; - double totalRtFactorAvg; + FunctionTimings funcTimings; }; diff --git a/src/core/Config.c b/src/core/Config.c index ecd81e5..d94f3b5 100644 --- a/src/core/Config.c +++ b/src/core/Config.c @@ -49,7 +49,7 @@ void CreateLogHeader(Config * config, LogSeverity sev) { char * currentWorkingDirectory; time(&config->timeStamp); - strftime(timeString, TIMESTAMPLENGTH-1, "%a, %d.%m.%Y %H:%M:%S", localtime(&config->timeStamp)); + strftime(timeString, TIMESTAMPLENGTH-1, "%a, %Y-%m-%d %H:%M:%S", localtime(&config->timeStamp)); strcpy(compileTimeString, __DATE__ ); strcat(compileTimeString, "-"); strcat(compileTimeString, __TIME__ ); @@ -295,6 +295,115 @@ static McxStatus ConfigSetupFromEnvironment(Config * config) { } } + { + char * profilingMode = mcx_os_get_env_var("MC_PROFILING"); + if (profilingMode) { + if (!is_off(profilingMode)) { + mcx_log(LOG_INFO, "Development mode turned on"); + config->profilingMode = TRUE; + } + + mcx_free(profilingMode); + } + } + + { + char * str = mcx_os_get_env_var("MC_INTERPOLATION_BUFFER_SIZE"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid interpolation filter buffer size (%d). Falling back to the default (%zu)", + size, config->interpolationBuffSize); + } else { + config->interpolationBuffSize = (size_t) size; + mcx_log(LOG_INFO, "Interpolation filter buffer size: %zu", config->interpolationBuffSize); + } + mcx_free(str); + } + } + + { + char * str = mcx_os_get_env_var("MC_OVERRIDE_INTERPOLATION_BUFFER_SIZE"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid interpolation filter override buffer size (%d)", size); + } else { + config->overrideInterpolationBuffSize = (size_t) size; + mcx_log(LOG_INFO, "Interpolation filter override buffer size: %zu", config->overrideInterpolationBuffSize); + } + mcx_free(str); + } + } + + { + char * str = mcx_os_get_env_var("MC_INTERPOLATION_BUFFER_SIZE_LIMIT"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid interpolation filter buffer size limit (%d)", size); + } else { + config->interpolationBuffSizeLimit = (size_t) size; + mcx_log(LOG_INFO, "Interpolation filter buffer size limit: %zu", config->interpolationBuffSizeLimit); + } + mcx_free(str); + } + } + + { + char * str = mcx_os_get_env_var("MC_INTERPOLATION_BUFFER_SIZE_SAFE_EXT"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid interpolation filter buffer size safety extension (%d)", size); + } else { + config->interpolationBuffSizeSafetyExt = (size_t) size; + mcx_log(LOG_INFO, "Interpolation filter buffer size safety extension: %zu", config->interpolationBuffSizeSafetyExt); + } + mcx_free(str); + } + } + + { + char * disableMemFilter = NULL; + + disableMemFilter = mcx_os_get_env_var("MC_DISABLE_MEM_FILTER"); + if (disableMemFilter) { + if (is_on(disableMemFilter)) { + config->useMemFilter = FALSE; + } + mcx_free(disableMemFilter); + } + } + + { + char * str = mcx_os_get_env_var("MC_MEM_FILTER_HISTORY_LIMIT"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid memory filter history size limit (%s)", str); + } else { + config->memFilterHistoryLimit = (size_t) size; + mcx_log(LOG_INFO, "Memory filter history size limit: %zu", config->memFilterHistoryLimit); + } + mcx_free(str); + } + } + + { + char * str = mcx_os_get_env_var("MC_MEM_FILTER_HISTORY_EXTRA"); + if (str) { + int size = atoi(str); + if (size <= 0) { + mcx_log(LOG_WARNING, "Invalid memory filter extra history size (%s)", str); + } else { + config->memFilterHistoryExtra = (size_t) size; + mcx_log(LOG_INFO, "Memory filter extra history size: %zu", config->memFilterHistoryExtra); + } + mcx_free(str); + } + } + { char * cosimInitEnabled = NULL; @@ -307,6 +416,18 @@ static McxStatus ConfigSetupFromEnvironment(Config * config) { } } + { + char * wrongInitBehaviorDisabled = NULL; + + wrongInitBehaviorDisabled = mcx_os_get_env_var("MCX_WRONG_INIT_BEHAVIOR"); + if (wrongInitBehaviorDisabled) { + if (is_on(wrongInitBehaviorDisabled)) { + config->patchWrongInitBehavior = FALSE; + } + mcx_free(wrongInitBehaviorDisabled); + } + } + { char * numWarnings = mcx_os_get_env_var("NUM_TIME_SNAP_WARNINGS"); if (numWarnings) { @@ -456,19 +577,30 @@ static Config * ConfigCreate(Config * config) { config->executable = NULL; config->flushEveryStore = FALSE; - config->sumTimeDefined = FALSE; config->sumTime = TRUE; config->writeAllLogFile = FALSE; config->cosimInitEnabled = FALSE; + config->patchWrongInitBehavior = TRUE; config->maxNumTimeSnapWarnings = MAX_NUM_MSGS; config->nanCheck = NAN_CHECK_ALWAYS; config->nanCheckNumMessages = MAX_NUM_MSGS; + config->interpolationBuffSize = 1000; + config->overrideInterpolationBuffSize = 0; + config->interpolationBuffSizeLimit = 100000; + config->interpolationBuffSizeSafetyExt = 1; + + config->useMemFilter = TRUE; + config->memFilterHistoryLimit = 10000000; + config->memFilterHistoryExtra = 1; + + config->profilingMode = FALSE; + return config; } diff --git a/src/core/Config.h b/src/core/Config.h index 54e1cbe..6ae1643 100644 --- a/src/core/Config.h +++ b/src/core/Config.h @@ -56,12 +56,25 @@ struct Config { char * executable; int flushEveryStore; + int sumTime; int sumTimeDefined; int writeAllLogFile; + size_t interpolationBuffSize; + size_t overrideInterpolationBuffSize; + size_t interpolationBuffSizeLimit; + size_t interpolationBuffSizeSafetyExt; + + int useMemFilter; + size_t memFilterHistoryLimit; + size_t memFilterHistoryExtra; + int cosimInitEnabled; + int patchWrongInitBehavior; + + int profilingMode; size_t maxNumTimeSnapWarnings; diff --git a/src/core/Conversion.c b/src/core/Conversion.c index d11f48a..cb1677d 100644 --- a/src/core/Conversion.c +++ b/src/core/Conversion.c @@ -10,6 +10,8 @@ #include "CentralParts.h" #include "core/Conversion.h" +#include "core/channels/ChannelValueReference.h" +#include "core/channels/ChannelValue.h" #include "units/Units.h" #ifdef __cplusplus @@ -34,25 +36,140 @@ OBJECT_CLASS(Conversion, Object); // ---------------------------------------------------------------------- // Range Conversion +static int RangeConversionElemwiseLeq(void * first, void * second, ChannelType * type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) first <= *(double *) second; + case CHANNEL_INTEGER: + return *(int *) first <= *(int *) second; + default: + return 0; + } +} + +static int RangeConversionElemwiseGeq(void * first, void * second, ChannelType * type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) first >= *(double *) second; + case CHANNEL_INTEGER: + return *(int *) first >= *(int *) second; + default: + return 0; + } +} static McxStatus RangeConversionConvert(Conversion * conversion, ChannelValue * value) { RangeConversion * rangeConversion = (RangeConversion *) conversion; + McxStatus retVal = RETURN_OK; + + if (!ChannelTypeEq(ChannelValueType(value), rangeConversion->type)) { + mcx_log(LOG_ERROR, + "Range conversion: Value has wrong type %s, expected: %s", + ChannelTypeToString(ChannelValueType(value)), + ChannelTypeToString(rangeConversion->type)); + return RETURN_ERROR; + } + + if (rangeConversion->min) { + retVal = ChannelValueDataSetFromReferenceIfElemwisePred(&value->value, + value->type, + &rangeConversion->min->value, + RangeConversionElemwiseLeq); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Range conversion: Set value to min failed"); + return RETURN_ERROR; + } + } + + if (rangeConversion->max) { + retVal = ChannelValueDataSetFromReferenceIfElemwisePred(&value->value, + value->type, + &rangeConversion->max->value, + RangeConversionElemwiseGeq); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Range conversion: Set value to max failed"); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +McxStatus RangeConversionMinValueRefConversion(void * element, size_t idx, ChannelType * type, void * ctx) { + ChannelValue * min = (ChannelValue *) ctx; + void * minElem = mcx_array_get_elem_reference(&min->value.a, idx); + if (RangeConversionElemwiseLeq(element, minElem, type)) { + switch (type->con) { + case CHANNEL_DOUBLE: + { + double * elem = (double *) element; + *elem = *((double *) minElem); + break; + } + case CHANNEL_INTEGER: + { + int * elem = (int *) element; + *elem = *((int *) minElem); + break; + } + default: + mcx_log(LOG_ERROR, "RangeConversion: Unsupported type"); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} +McxStatus RangeConversionMaxValueRefConversion(void * element, size_t idx, ChannelType * type, void * ctx) { + ChannelValue * max = (ChannelValue *) ctx; + void * maxElem = mcx_array_get_elem_reference(&max->value.a, idx); + if (RangeConversionElemwiseGeq(element, maxElem, type)) { + switch (type->con) + { + case CHANNEL_DOUBLE: + { + double * elem = (double *) element; + *elem = *((double *)maxElem); + break; + } + case CHANNEL_INTEGER: + { + int * elem = (int *) element; + *elem = *((int *)maxElem); + break; + } + default: + mcx_log(LOG_ERROR, "RangeConversion: Unsupported type"); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +static McxStatus RangeConversionConvertValueRef(RangeConversion * conversion, ChannelValueReference * ref) { + RangeConversion * rangeConversion = (RangeConversion *) conversion; McxStatus retVal = RETURN_OK; - if (ChannelValueType(value) != rangeConversion->type) { - mcx_log(LOG_ERROR, "Range conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(rangeConversion->type)); + if (!ChannelTypeEq(ChannelValueReferenceGetType(ref), rangeConversion->type)) { + mcx_log(LOG_ERROR, + "Range conversion: Value has wrong type %s, expected: %s", + ChannelTypeToString(ChannelValueReferenceGetType(ref)), + ChannelTypeToString(rangeConversion->type)); return RETURN_ERROR; } - if (rangeConversion->min && ChannelValueLeq(value, rangeConversion->min)) { - retVal = ChannelValueSet(value, rangeConversion->min); + if (rangeConversion->min) { + retVal = ChannelValueReferenceElemMap(ref, RangeConversionMinValueRefConversion, rangeConversion->min); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Range conversion: Set value to min failed"); return RETURN_ERROR; } - } else if (rangeConversion->max && ChannelValueGeq(value, rangeConversion->max)) { - retVal = ChannelValueSet(value, rangeConversion->max); + } + + if (rangeConversion->max) { + retVal = ChannelValueReferenceElemMap(ref, RangeConversionMaxValueRefConversion, rangeConversion->max); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Range conversion: Set value to max failed"); return RETURN_ERROR; @@ -62,12 +179,85 @@ static McxStatus RangeConversionConvert(Conversion * conversion, ChannelValue * return RETURN_OK; } +McxStatus ConvertRange(ChannelValue * min, ChannelValue * max, ChannelValue * value, ChannelDimension * slice) { + RangeConversion * rangeConv = NULL; + ChannelValue * minToUse = NULL; + ChannelValue * maxToUse = NULL; + + McxStatus retVal = RETURN_OK; + + if (!ChannelTypeEq(ChannelTypeBaseType(value->type), &ChannelTypeDouble) && !ChannelTypeEq(ChannelTypeBaseType(value->type), &ChannelTypeInteger)) { + return RETURN_OK; + } + + rangeConv = (RangeConversion *) object_create(RangeConversion); + if (!rangeConv) { + mcx_log(LOG_ERROR, "ConvertRange: Not enough memory"); + return RETURN_ERROR; + } + + maxToUse = max ? ChannelValueClone(max) : NULL; + if (max && !maxToUse) { + mcx_log(LOG_ERROR, "ConvertRange: Not enough memory for max"); + retVal = RETURN_ERROR; + goto cleanup; + } + + minToUse = min ? ChannelValueClone(min) : NULL; + if (min && !minToUse) { + mcx_log(LOG_ERROR, "ConvertRange: Not enough memory for min"); + retVal = RETURN_ERROR; + goto cleanup; + } + + retVal = rangeConv->Setup(rangeConv, minToUse, maxToUse); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "ConvertRange: Conversion setup failed"); + goto cleanup; + } + + minToUse = NULL; + maxToUse = NULL; + + if (rangeConv->IsEmpty(rangeConv)) { + object_destroy(rangeConv); + } + + if (rangeConv) { + if (slice) { + ChannelValueReference * ref = MakeChannelValueReference(value, slice); + retVal = RangeConversionConvertValueRef(rangeConv, ref); + DestroyChannelValueReference(ref); + } else { + retVal = RangeConversionConvert(rangeConv, value); + } + + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "ConvertRange: Conversion failed"); + goto cleanup; + } + } + +cleanup: + if (minToUse) { + mcx_free(minToUse); + } + + if (maxToUse) { + mcx_free(maxToUse); + } + + object_destroy(rangeConv); + + return retVal; +} + static McxStatus RangeConversionSetup(RangeConversion * conversion, ChannelValue * min, ChannelValue * max) { if (!min && !max) { return RETURN_OK; } - if (min && max && ChannelValueType(min) != ChannelValueType(max)) { + if (min && max && !ChannelTypeEq(ChannelValueType(min), ChannelValueType(max))) { mcx_log(LOG_ERROR, "Range conversion: Types of max value and min value do not match"); return RETURN_ERROR; } @@ -77,40 +267,64 @@ static McxStatus RangeConversionSetup(RangeConversion * conversion, ChannelValue return RETURN_ERROR; } - if (min) { - conversion->type = ChannelValueType(min); - } else { - conversion->type = ChannelValueType(max); - } + conversion->type = ChannelTypeClone(ChannelValueType(min ? min : max)); - if (!(conversion->type == CHANNEL_DOUBLE - || conversion->type == CHANNEL_INTEGER)) { + if (!(ChannelTypeEq(ChannelTypeBaseType(conversion->type), &ChannelTypeDouble) || + ChannelTypeEq(ChannelTypeBaseType(conversion->type), &ChannelTypeInteger))) + { mcx_log(LOG_ERROR, "Range conversion is not defined for type %s", ChannelTypeToString(conversion->type)); return RETURN_ERROR; } - conversion->min = min; - conversion->max = max; + conversion->min = min ? ChannelValueClone(min) : NULL; + conversion->max = max ? ChannelValueClone(max) : NULL; return RETURN_OK; } +static int RangeConversionElementEqualsMin(void * element, ChannelType * type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) element == (-DBL_MAX); + case CHANNEL_INTEGER: + return *(int *) element == INT_MIN; + default: + return 0; + } +} + +static int RangeConversionElementEqualsMax(void * element, ChannelType * type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) element == DBL_MAX; + case CHANNEL_INTEGER: + return *(int *) element == INT_MAX; + default: + return 0; + } +} + static int RangeConversionIsEmpty(RangeConversion * conversion) { - switch (conversion->type) { - case CHANNEL_DOUBLE: - return - (!conversion->min || * (double *) ChannelValueReference(conversion->min) == (-DBL_MAX)) && - (!conversion->max || * (double *) ChannelValueReference(conversion->max) == DBL_MAX); - case CHANNEL_INTEGER: - return - (!conversion->min || * (int *) ChannelValueReference(conversion->min) == INT_MIN) && - (!conversion->max || * (int *) ChannelValueReference(conversion->max) == INT_MAX); - default: - return 1; + switch (conversion->type->con) { + case CHANNEL_DOUBLE: + return (!conversion->min || *(double *) ChannelValueDataPointer(conversion->min) == (-DBL_MAX)) && + (!conversion->max || *(double *) ChannelValueDataPointer(conversion->max) == DBL_MAX); + case CHANNEL_INTEGER: + return (!conversion->min || *(int *) ChannelValueDataPointer(conversion->min) == INT_MIN) && + (!conversion->max || *(int *) ChannelValueDataPointer(conversion->max) == INT_MAX); + case CHANNEL_ARRAY: + return (!conversion->min || mcx_array_all(&conversion->min->value.a, RangeConversionElementEqualsMin)) && + (!conversion->max || mcx_array_all(&conversion->max->value.a, RangeConversionElementEqualsMax)); + default: + return 1; } } static void RangeConversionDestructor(RangeConversion * rangeConversion) { + if (rangeConversion->type) { + ChannelTypeDestructor(rangeConversion->type); + } + if (rangeConversion->min) { mcx_free(rangeConversion->min); } @@ -127,7 +341,7 @@ static RangeConversion * RangeConversionCreate(RangeConversion * rangeConversion rangeConversion->Setup = RangeConversionSetup; rangeConversion->IsEmpty = RangeConversionIsEmpty; - rangeConversion->type = CHANNEL_UNKNOWN; + rangeConversion->type = &ChannelTypeUnknown; rangeConversion->min = NULL; rangeConversion->max = NULL; @@ -140,17 +354,18 @@ OBJECT_CLASS(RangeConversion, Conversion); // ---------------------------------------------------------------------- // Unit Conversion +static double UnitConversionConvertValue(UnitConversion * conversion, double value) { + value = (value + conversion->source.offset) * conversion->source.factor; + value = (value / conversion->target.factor) - conversion->target.offset; + + return value; +} static void UnitConversionConvertVector(UnitConversion * unitConversion, double * vector, size_t vectorLength) { size_t i; if (!unitConversion->IsEmpty(unitConversion)) { for (i = 0; i < vectorLength; i++) { - double val = vector[i]; - - val = (val + unitConversion->source.offset) * unitConversion->source.factor; - val = (val / unitConversion->target.factor) - unitConversion->target.offset; - - vector[i] = val; + vector[i] = UnitConversionConvertValue(unitConversion, vector[i]); } } } @@ -158,23 +373,53 @@ static void UnitConversionConvertVector(UnitConversion * unitConversion, double static McxStatus UnitConversionConvert(Conversion * conversion, ChannelValue * value) { UnitConversion * unitConversion = (UnitConversion *) conversion; - double val = 0.0; - - if (ChannelValueType(value) != CHANNEL_DOUBLE) { - mcx_log(LOG_ERROR, "Unit conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_DOUBLE)); + if (!ChannelTypeEq(ChannelTypeBaseType(ChannelValueType(value)), &ChannelTypeDouble)) { + mcx_log(LOG_ERROR, "Unit conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(&ChannelTypeDouble)); return RETURN_ERROR; } - val = * (double *) ChannelValueReference(value); + if (ChannelTypeIsArray(value->type)) { + size_t i = 0; + + for (i = 0; i < mcx_array_num_elements(&value->value.a); i++) { + double * elem = (double *)mcx_array_get_elem_reference(&value->value.a, i); + if (!elem) { + return RETURN_ERROR; + } + + *elem = UnitConversionConvertValue(conversion, *elem); + } + } else { + double val = UnitConversionConvertValue(unitConversion, *(double *) ChannelValueDataPointer(value)); + if (RETURN_OK != ChannelValueSetFromReference(value, &val)) { + return RETURN_ERROR; + } + } + + return RETURN_OK; +} - val = (val + unitConversion->source.offset) * unitConversion->source.factor; - val = (val / unitConversion->target.factor) - unitConversion->target.offset; +McxStatus UnitConversionValueRefConversion(void * element, size_t idx, ChannelType * type, void * ctx) { + double * elem = (double *) element; + UnitConversion * conversion = (UnitConversion *) ctx; - ChannelValueSetFromReference(value, &val); + *elem = UnitConversionConvertValue(conversion, *elem); return RETURN_OK; } +static McxStatus UnitConversionConvertValueRef(UnitConversion * conversion, ChannelValueReference * ref) { + if (!ChannelTypeEq(ChannelTypeBaseType(ChannelValueReferenceGetType(ref)), &ChannelTypeDouble)) { + mcx_log(LOG_ERROR, + "Unit conversion: Value has wrong type %s, expected: %s", + ChannelTypeToString(ChannelTypeBaseType(ChannelValueReferenceGetType(ref))), + ChannelTypeToString(&ChannelTypeDouble)); + return RETURN_ERROR; + } + + return ChannelValueReferenceElemMap(ref, UnitConversionValueRefConversion, conversion); +} + static McxStatus UnitConversionSetup(UnitConversion * conversion, const char * fromUnit, const char * toUnit) { @@ -213,6 +458,48 @@ static int UnitConversionIsEmpty(UnitConversion * conversion) { || (conversion->target.factor == 0.0 && conversion->target.offset == 0.0); } +McxStatus ConvertUnit(const char * fromUnit, const char * toUnit, ChannelValue * value, ChannelDimension * slice) { + UnitConversion * unitConv = NULL; + + McxStatus retVal = RETURN_OK; + + unitConv = (UnitConversion *) object_create(UnitConversion); + if (!unitConv) { + mcx_log(LOG_ERROR, "ConvertUnit: Not enough memory"); + return RETURN_ERROR; + } + + retVal = unitConv->Setup(unitConv, fromUnit, toUnit); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ConvertUnit: Conversion setup failed"); + goto cleanup; + } + + if (unitConv->IsEmpty(unitConv)) { + object_destroy(unitConv); + } + + if (unitConv) { + if (slice) { + ChannelValueReference * ref = MakeChannelValueReference(value, slice); + retVal = UnitConversionConvertValueRef(unitConv, ref); + DestroyChannelValueReference(ref); + } else { + retVal = UnitConversionConvert(unitConv, value); + } + + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "ConvertUnit: Conversion failed"); + goto cleanup; + } + } + +cleanup: + object_destroy(unitConv); + + return retVal; +} + static void UnitConversionDestructor(UnitConversion * conversion) { } @@ -222,6 +509,7 @@ static UnitConversion * UnitConversionCreate(UnitConversion * unitConversion) { conversion->convert = UnitConversionConvert; unitConversion->convertVector = UnitConversionConvertVector; + unitConversion->ConvertValueReference = UnitConversionConvertValueRef; unitConversion->Setup = UnitConversionSetup; unitConversion->IsEmpty = UnitConversionIsEmpty; @@ -240,7 +528,6 @@ OBJECT_CLASS(UnitConversion, Conversion); // ---------------------------------------------------------------------- // Linear Conversion - static McxStatus LinearConversionConvert(Conversion * conversion, ChannelValue * value) { LinearConversion * linearConversion = (LinearConversion *) conversion; @@ -265,51 +552,236 @@ static McxStatus LinearConversionConvert(Conversion * conversion, ChannelValue * return RETURN_OK; } +McxStatus LinearConversionScaleValueRefConversion(void * element, size_t idx, ChannelType * type, void * ctx) { + ChannelValue * factor = (ChannelValue *) ctx; + void * factorElem = mcx_array_get_elem_reference(&factor->value.a, idx); + + if (!ChannelTypeEq(type, factor->type)) { + mcx_log(LOG_ERROR, "Port: Scale: Mismatching types. Value type: %s, factor type: %s", + ChannelTypeToString(type), ChannelTypeToString(ChannelValueType(factor))); + return RETURN_ERROR; + } + + switch (type->con) { + case CHANNEL_DOUBLE: + { + double * elem = (double *) element; + *elem = *elem * *((double *)factorElem); + break; + } + case CHANNEL_INTEGER: + { + int * elem = (int *) element; + *elem = *elem * *((int *)factorElem); + break; + } + default: + mcx_log(LOG_ERROR, "Linear conversion: Unsupported type"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +McxStatus LinearConversionOffsetValueRefConversion(void * element, size_t idx, ChannelType * type, void * ctx) { + ChannelValue * offset = (ChannelValue *) ctx; + void * offsetElem = mcx_array_get_elem_reference(&offset->value.a, idx); + + if (!ChannelTypeEq(type, offset->type)) { + mcx_log(LOG_ERROR, "Port: Scale: Mismatching types. Value type: %s, factor type: %s", + ChannelTypeToString(type), ChannelTypeToString(ChannelValueType(offset))); + return RETURN_ERROR; + } + + switch (type->con) { + case CHANNEL_DOUBLE: + { + double * elem = (double *) element; + *elem = *elem + *((double *)offsetElem); + break; + } + case CHANNEL_INTEGER: + { + int * elem = (int *) element; + *elem = *elem + *((int *)offsetElem); + break; + } + default: + mcx_log(LOG_ERROR, "Linear conversion: Unsupported type"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +static McxStatus LinearConversionConvertValueRef(LinearConversion * linearConversion, ChannelValueReference * ref) { + McxStatus retVal = RETURN_OK; + + if (linearConversion->factor) { + retVal = ChannelValueReferenceElemMap(ref, LinearConversionScaleValueRefConversion, linearConversion->factor); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Linear conversion: Port value scaling failed"); + return RETURN_ERROR; + } + } + + if (linearConversion->offset) { + retVal = ChannelValueReferenceElemMap(ref, LinearConversionOffsetValueRefConversion, linearConversion->offset); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Linear conversion: Adding offset failed"); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + static McxStatus LinearConversionSetup(LinearConversion * conversion, ChannelValue * factor, ChannelValue * offset) { if (!factor && !offset) { return RETURN_OK; } - if (factor && offset && ChannelValueType(factor) != ChannelValueType(offset)) { - mcx_log(LOG_WARNING, "Linear conversion: Types of factor value (%s) and offset value (%s) do not match", - ChannelTypeToString(ChannelValueType(factor)), ChannelTypeToString(ChannelValueType(offset))); + if (factor && offset && !ChannelTypeEq(ChannelValueType(factor), ChannelValueType(offset))) { + mcx_log(LOG_WARNING, + "Linear conversion: Types of factor value (%s) and offset value (%s) do not match", + ChannelTypeToString(ChannelValueType(factor)), + ChannelTypeToString(ChannelValueType(offset))); return RETURN_ERROR; } - if (factor) { - conversion->type = ChannelValueType(factor); - } else { - conversion->type = ChannelValueType(offset); - } + conversion->type = ChannelTypeClone(ChannelValueType(factor ? factor : offset)); - if (!(conversion->type == CHANNEL_DOUBLE - || conversion->type == CHANNEL_INTEGER)) { + if (!(ChannelTypeEq(ChannelTypeBaseType(conversion->type), &ChannelTypeDouble) || + ChannelTypeEq(ChannelTypeBaseType(conversion->type), &ChannelTypeInteger))) + { mcx_log(LOG_WARNING, "Linear conversion is not defined for type %s", ChannelTypeToString(conversion->type)); return RETURN_ERROR; } - conversion->factor = factor; - conversion->offset = offset; + conversion->factor = factor ? ChannelValueClone(factor) : NULL; + conversion->offset = offset ? ChannelValueClone(offset) : NULL; return RETURN_OK; } +static int LinearConversionElementEqualsOne(void* element, ChannelType* type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) element == 1.0; + case CHANNEL_INTEGER: + return *(int *) element == 1; + default: + return 0; + } +} + +static int LinearConversionElementEqualsZero(void * element, ChannelType * type) { + switch (type->con) { + case CHANNEL_DOUBLE: + return *(double *) element == 0.0; + case CHANNEL_INTEGER: + return *(int *) element == 0; + default: + return 0; + } +} + static int LinearConversionIsEmpty(LinearConversion * conversion) { - switch (conversion->type) { + switch (conversion->type->con) { case CHANNEL_DOUBLE: return - (!conversion->factor || * (double *) ChannelValueReference(conversion->factor) == 1.0) && - (!conversion->offset || * (double *) ChannelValueReference(conversion->offset) == 0.0); + (!conversion->factor || * (double *) ChannelValueDataPointer(conversion->factor) == 1.0) && + (!conversion->offset || * (double *) ChannelValueDataPointer(conversion->offset) == 0.0); case CHANNEL_INTEGER: return - (!conversion->factor || * (int *) ChannelValueReference(conversion->factor) == 1) && - (!conversion->offset || * (int *) ChannelValueReference(conversion->offset) == 0); + (!conversion->factor || * (int *) ChannelValueDataPointer(conversion->factor) == 1) && + (!conversion->offset || * (int *) ChannelValueDataPointer(conversion->offset) == 0); + case CHANNEL_ARRAY: + return (!conversion->factor || mcx_array_all(&conversion->factor->value.a, LinearConversionElementEqualsOne)) && + (!conversion->offset || mcx_array_all(&conversion->offset->value.a, LinearConversionElementEqualsZero)); default: return 1; } } +McxStatus ConvertLinear(ChannelValue * factor, ChannelValue * offset, ChannelValue * value, ChannelDimension * slice) { + LinearConversion * linearConv = NULL; + ChannelValue * factorToUse = NULL; + ChannelValue * offsetToUse = NULL; + + McxStatus retVal = RETURN_OK; + + if (!ChannelTypeEq(ChannelTypeBaseType(value->type), &ChannelTypeDouble) && !ChannelTypeEq(ChannelTypeBaseType(value->type), &ChannelTypeInteger)) { + return RETURN_OK; + } + + linearConv = (LinearConversion *) object_create(LinearConversion); + if (!linearConv) { + mcx_log(LOG_ERROR, "ConvertLinear: Not enough memory"); + return RETURN_ERROR; + } + + factorToUse = factor ? ChannelValueClone(factor) : NULL; + if (factor && !factorToUse) { + mcx_log(LOG_ERROR, "ConvertLinear: Not enough memory for factor"); + retVal = RETURN_ERROR; + goto cleanup; + } + + offsetToUse = offset ? ChannelValueClone(offset) : NULL; + if (offset && !offsetToUse) { + mcx_log(LOG_ERROR, "ConvertLinear: Not enough memory for offset"); + retVal = RETURN_ERROR; + goto cleanup; + } + + retVal = linearConv->Setup(linearConv, factorToUse, offsetToUse); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "ConvertLinear: Conversion setup failed"); + goto cleanup; + } + + factorToUse = NULL; + offsetToUse = NULL; + + if (linearConv->IsEmpty(linearConv)) { + object_destroy(linearConv); + } + + if (linearConv) { + if (slice) { + ChannelValueReference * ref = MakeChannelValueReference(value, slice); + retVal = LinearConversionConvertValueRef(linearConv, ref); + DestroyChannelValueReference(ref); + } else { + retVal = LinearConversionConvert(linearConv, value); + } + + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "ConvertLinear: Conversion failed"); + goto cleanup; + } + } + +cleanup: + if (factorToUse) { + mcx_free(factorToUse); + } + + if (offsetToUse) { + mcx_free(offsetToUse); + } + + object_destroy(linearConv); + + return retVal; +} + static void LinearConversionDestructor(LinearConversion * linearConversion) { + if (linearConversion->type) { + ChannelTypeDestructor(linearConversion->type); + } + if (linearConversion->factor) { mcx_free(linearConversion->factor); } @@ -325,7 +797,7 @@ static LinearConversion * LinearConversionCreate(LinearConversion * linearConver linearConversion->Setup = LinearConversionSetup; linearConversion->IsEmpty = LinearConversionIsEmpty; - linearConversion->type = CHANNEL_UNKNOWN; + linearConversion->type = &ChannelTypeUnknown; linearConversion->factor = NULL; linearConversion->offset = NULL; @@ -338,132 +810,725 @@ OBJECT_CLASS(LinearConversion, Conversion); // ---------------------------------------------------------------------- // Type Conversion +McxStatus ConvertType(ChannelValue * dest, ChannelDimension * destSlice, ChannelValue * src, ChannelDimension * srcSlice) { + TypeConversion * typeConv = NULL; + ChannelValueReference * ref = NULL; + + McxStatus retVal = RETURN_OK; -static McxStatus TypeConversionConvertIntDouble(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_INTEGER) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_INTEGER)); + typeConv = (TypeConversion *) object_create(TypeConversion); + if (!typeConv) { + mcx_log(LOG_ERROR, "ConvertType: Converter allocation failed"); return RETURN_ERROR; } - value->type = CHANNEL_DOUBLE; - value->value.d = (double)value->value.i; + retVal = typeConv->Setup(typeConv, src->type, srcSlice, dest->type, destSlice); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "ConvertType: Setup failed"); + goto cleanup; + } + + ref = MakeChannelValueReference(dest, destSlice); + if (!ref) { + mcx_log(LOG_ERROR, "ConvertType: Value reference allocation failed"); + goto cleanup; + } + + ChannelValueReferenceSetFromPointer(ref, ChannelValueDataPointer(src), srcSlice, typeConv); - return RETURN_OK; +cleanup: + object_destroy(typeConv); + DestroyChannelValueReference(ref); + + return retVal; } -static McxStatus TypeConversionConvertDoubleInt(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_DOUBLE) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_DOUBLE)); +static McxStatus CheckTypesValidForConversion(ChannelType * destType, + ChannelType * expectedDestType) +{ + if (!ChannelTypeEq(destType, expectedDestType)) { + mcx_log(LOG_ERROR, + "Type conversion: Destination value has wrong type %s, expected: %s", + ChannelTypeToString(destType), + ChannelTypeToString(expectedDestType)); return RETURN_ERROR; } - value->type = CHANNEL_INTEGER; - value->value.i = (int)floor(value->value.d + 0.5); - return RETURN_OK; } -static McxStatus TypeConversionConvertBoolDouble(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_BOOL) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_BOOL)); +static McxStatus CheckArrayReferencingOnlyOneElement(ChannelValueReference * dest, ChannelType * expectedDestType) { + if (!ChannelTypeIsArray(ChannelValueReferenceGetType(dest))) { + mcx_log(LOG_ERROR, "Type conversion: Destination value is not an array"); + return RETURN_ERROR; + } + + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelTypeBaseType(ChannelValueReferenceGetType(dest)), expectedDestType)) { return RETURN_ERROR; } - value->type = CHANNEL_DOUBLE; - value->value.d = (value->value.d != 0) ? 1. : 0.; + // check only one element referenced + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + if (ChannelTypeNumElements(dest->ref.value->type) != 1) { + mcx_log(LOG_ERROR, "Type conversion: Destination value is not an array of size 1"); + return RETURN_ERROR; + } + } else { + if (ChannelDimensionNumElements(dest->ref.slice.dimension) != 1) { + mcx_log(LOG_ERROR, "Type conversion: Destination value is not an array of size 1"); + return RETURN_ERROR; + } + } return RETURN_OK; } -static McxStatus TypeConversionConvertDoubleBool(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_DOUBLE) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_DOUBLE)); +static McxStatus ArraysValidForConversion(ChannelValueReference * dest, + ChannelType * expectedDestType, + mcx_array * src, + ChannelDimension * srcDimension) { + if (!ChannelTypeIsArray(ChannelValueReferenceGetType(dest))) { + mcx_log(LOG_ERROR, "Type conversion: Destination value is not an array"); + return RETURN_ERROR; + } + + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelTypeBaseType(ChannelValueReferenceGetType(dest)), expectedDestType)) { return RETURN_ERROR; } - value->type = CHANNEL_BOOL; - value->value.i = (value->value.d > 0) ? 1 : 0; + // check dimensions match + if (srcDimension) { + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + return ChannelDimensionConformsTo(srcDimension, dest->ref.value->type->ty.a.dims, dest->ref.value->type->ty.a.numDims) ? RETURN_OK : RETURN_ERROR; + } else { + return ChannelDimensionConformsToDimension(dest->ref.slice.dimension, srcDimension) ? RETURN_OK : RETURN_ERROR; + } + } else { + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + return mcx_array_dims_match(&dest->ref.value->value.a, src) ? RETURN_OK : RETURN_ERROR; + } else { + return ChannelDimensionConformsTo(dest->ref.slice.dimension, src->dims, src->numDims) ? RETURN_OK : RETURN_ERROR; + } + } return RETURN_OK; } -static McxStatus TypeConversionConvertBoolInteger(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_BOOL) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_BOOL)); +static McxStatus TypeConversionConvertIntDouble(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeDouble)) { return RETURN_ERROR; } - value->type = CHANNEL_INTEGER; - value->value.i = (value->value.i != 0) ? 1 : 0; + dest->ref.value->value.d = (double) *((int *) src); return RETURN_OK; } -static McxStatus TypeConversionConvertIntegerBool(Conversion * conversion, ChannelValue * value) { - if (ChannelValueType(value) != CHANNEL_INTEGER) { - mcx_log(LOG_ERROR, "Type conversion: Value has wrong type %s, expected: %s", ChannelTypeToString(ChannelValueType(value)), ChannelTypeToString(CHANNEL_INTEGER)); +static McxStatus TypeConversionConvertDoubleInt(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeInteger)) { return RETURN_ERROR; } - value->type = CHANNEL_BOOL; - value->value.i = (value->value.i != 0) ? 1 : 0; + dest->ref.value->value.i = (int) floor(*((double *) src) + 0.5); return RETURN_OK; } -static McxStatus TypeConversionConvertId(Conversion * conversion, ChannelValue * value) { +static McxStatus TypeConversionConvertBoolDouble(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + dest->ref.value->value.d = *((int *) src) != 0 ? 1. : 0.; + return RETURN_OK; } -static McxStatus TypeConversionSetup(TypeConversion * typeConversion, - ChannelType fromType, - ChannelType toType) { - Conversion * conversion = (Conversion *) typeConversion; - - if (fromType == toType) { - conversion->convert = TypeConversionConvertId; - } else if (fromType == CHANNEL_INTEGER && toType == CHANNEL_DOUBLE) { - conversion->convert = TypeConversionConvertIntDouble; - } else if (fromType == CHANNEL_DOUBLE && toType == CHANNEL_INTEGER) { - conversion->convert = TypeConversionConvertDoubleInt; - } else if (fromType == CHANNEL_BOOL && toType == CHANNEL_DOUBLE) { - conversion->convert = TypeConversionConvertBoolDouble; - } else if (fromType == CHANNEL_DOUBLE && toType == CHANNEL_BOOL) { - conversion->convert = TypeConversionConvertDoubleBool; - } else if (fromType == CHANNEL_BOOL && toType == CHANNEL_INTEGER) { - conversion->convert = TypeConversionConvertBoolInteger; - } else if (fromType == CHANNEL_INTEGER && toType == CHANNEL_BOOL) { - conversion->convert = TypeConversionConvertIntegerBool; - } else { - mcx_log(LOG_ERROR, "Setup type conversion: Illegal conversion selected"); +static McxStatus TypeConversionConvertDoubleBool(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeBool)) { return RETURN_ERROR; } + dest->ref.value->value.i = *((double *) src) > 0 ? 1 : 0; + return RETURN_OK; } -static int TypeConversionIsEmpty(TypeConversion * typeConversion) { - Conversion * conversion = (Conversion *) typeConversion; - - return (conversion->convert == TypeConversionConvertId); -} +static McxStatus TypeConversionConvertBoolInteger(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeInteger)) { + return RETURN_ERROR; + } -static void TypeConversionDestructor(TypeConversion * conversion) { + dest->ref.value->value.i = *((int *) src) != 0 ? 1 : 0; + return RETURN_OK; } -static TypeConversion * TypeConversionCreate(TypeConversion * typeConversion) { - Conversion * conversion = (Conversion *) typeConversion; +static McxStatus TypeConversionConvertIntegerBool(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeBool)) { + return RETURN_ERROR; + } - conversion->convert = TypeConversionConvertId; + dest->ref.value->value.i = *((int *) src) != 0 ? 1 : 0; - typeConversion->Setup = TypeConversionSetup; - typeConversion->IsEmpty = TypeConversionIsEmpty; + return RETURN_OK; +} - return typeConversion; +static McxStatus TypeConversionConvertArrayDoubleToDouble(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.d = *((double *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]); + } else { + dest->ref.value->value.d = *(double *) ((mcx_array *) src)->data; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayIntegerToDouble(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.d = (double) *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]); + } else { + dest->ref.value->value.d = (double) *(int *) ((mcx_array *) src)->data; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayBoolToDouble(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.d = *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]) != 0 ? 1. : 0.; + } else { + dest->ref.value->value.d = *(int *) ((mcx_array *) src)->data != 0 ? 1. : 0.; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayDoubleToInteger(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = (int) floor(*((double *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]) + 0.5); + } else { + dest->ref.value->value.i = (int) floor(*(double *) ((mcx_array *) src)->data + 0.5); + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayIntegerToInteger(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]); + } else { + dest->ref.value->value.i = *(int *) ((mcx_array *) src)->data; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayBoolToInteger(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]) != 0 ? 1 : 0; + } else { + dest->ref.value->value.i = *(int *) ((mcx_array *) src)->data != 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayDoubleToBool(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = *((double *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]) > 0 ? 1 : 0; + } else { + dest->ref.value->value.i = *(double *) ((mcx_array *) src)->data > 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayIntegerToBool(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]) != 0 ? 1 : 0; + } else { + dest->ref.value->value.i = *(int *) ((mcx_array *) src)->data != 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayBoolToBool(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckTypesValidForConversion(ChannelValueReferenceGetType(dest), &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (conversion->sourceSlice) { + dest->ref.value->value.i = *((int *) ((mcx_array *) src)->data + conversion->sourceSlice->startIdxs[0]); + } else { + dest->ref.value->value.i = *(int *) ((mcx_array *) src)->data; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertDoubleToArrayDouble(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(double *) dest->ref.value->value.a.data = *(double *) src; + } else { + double * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *(double *) src; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertIntegerToArrayDouble(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(double *) dest->ref.value->value.a.data = (double) *((int *) src); + } else { + double * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = (double) *((int *) src); + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertBoolToArrayDouble(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeDouble)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(double *) dest->ref.value->value.a.data = *((int *) src) != 0 ? 1. : 0.; + } else { + double * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *((int *) src) != 0 ? 1. : 0.; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertDoubleToArrayInteger(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = (int) floor(*((double *) src) + 0.5); + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = (int) floor(*((double *) src) + 0.5); + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertIntegerToArrayInteger(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = *(int *) src; + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *(int *) src; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertBoolToArrayInteger(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeInteger)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = *((int *) src) != 0 ? 1 : 0; + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *((int *) src) != 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertDoubleToArrayBool(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = *((double *) src) > 0 ? 1 : 0; + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *((double *) src) > 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertIntegerToArrayBool(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = *((int *) src) != 0 ? 1 : 0; + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *((int *) src) != 0 ? 1 : 0; + } + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertBoolToArrayBool(Conversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_ERROR == CheckArrayReferencingOnlyOneElement(dest, &ChannelTypeBool)) { + return RETURN_ERROR; + } + + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + *(int *) dest->ref.value->value.a.data = *(int *) src; + } else { + int * data = dest->ref.slice.ref->value.a.data; + *(data + dest->ref.slice.dimension->startIdxs[0]) = *(int *) src; + } + + return RETURN_OK; +} + +static size_t IndexOfElemInSrcArray(size_t dest_idx, mcx_array * src_array, ChannelDimension * src_dim, ChannelValueReference * dest) { + if (src_dim) { + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + return ChannelDimensionGetIndex(src_dim, dest_idx, src_array->dims); + } else { + size_t idx = ChannelDimensionGetSliceIndex(dest->ref.slice.dimension, dest_idx, dest->ref.slice.ref->type->ty.a.dims); + return ChannelDimensionGetIndex(src_dim, idx, src_array->dims); + } + } else { + if (dest->type == CHANNEL_VALUE_REF_VALUE) { + return dest_idx; + } else { + return ChannelDimensionGetSliceIndex(dest->ref.slice.dimension, dest_idx, dest->ref.slice.ref->type->ty.a.dims); + } + } +} + +typedef struct Array2ArrayCtx { + mcx_array * src_array; + ChannelDimension * src_dim; + ChannelValueReference * dest; +} Array2ArrayCtx; + +static McxStatus IntegerArrayToDouble(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(double *) element = (double) *((int *) src_elem); + + return RETURN_OK; +} + +static McxStatus BoolArrayToDouble(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(double *) element = *((int *) src_elem) != 0 ? 1. : 0.; + + return RETURN_OK; +} + +static McxStatus BoolArrayToInteger(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(int *) element = *((int *) src_elem) != 0 ? 1 : 0; + + return RETURN_OK; +} + +static McxStatus DoubleArrayToInteger(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(int *) element = (int) floor(*((double *) src_elem) + 0.5); + + return RETURN_OK; +} + +static McxStatus DoubleArrayToBool(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(int *) element = *((double *) src_elem) > 0 ? 1 : 0; + + return RETURN_OK; +} + +static McxStatus IntegerArrayToBool(void * element, size_t idx, ChannelType * type, void * ctx) { + Array2ArrayCtx * context = (Array2ArrayCtx *) ctx; + size_t i = IndexOfElemInSrcArray(idx, context->src_array, context->src_dim, context->dest); + void * src_elem = mcx_array_get_elem_reference(context->src_array, i); + + if (!src_elem) { + return RETURN_ERROR; + } + + *(int *) element = *((int *) src_elem) != 0 ? 1 : 0; + + return RETURN_OK; +} + +static McxStatus TypeConversionConvertArrayIntegerToArrayDouble(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeDouble, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, IntegerArrayToDouble, &ctx); +} + +static McxStatus TypeConversionConvertArrayBoolToArrayDouble(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeDouble, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, BoolArrayToDouble, &ctx); +} + +static McxStatus TypeConversionConvertArrayDoubleToArrayInteger(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeInteger, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, DoubleArrayToInteger, &ctx); +} + +static McxStatus TypeConversionConvertArrayBoolToArrayInteger(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeInteger, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, BoolArrayToInteger, &ctx); +} + +static McxStatus TypeConversionConvertArrayDoubleToArrayBool(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeBool, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, DoubleArrayToBool, &ctx); +} + +static McxStatus TypeConversionConvertArrayIntegerToArrayBool(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + if (RETURN_OK != ArraysValidForConversion(dest, &ChannelTypeBool, (mcx_array *) src, conversion->sourceSlice)) { + return RETURN_ERROR; + } + + Array2ArrayCtx ctx = {src, conversion->sourceSlice, dest}; + return ChannelValueReferenceElemMap(dest, IntegerArrayToBool, &ctx); +} + +static McxStatus TypeConversionConvertId(TypeConversion * conversion, ChannelValueReference * dest, void * src) { + return ChannelValueReferenceSetFromPointer(dest, src, conversion->sourceSlice, NULL); +} + +static int DimensionsMatch(ChannelType * fromType, ChannelDimension * fromDimension, ChannelType * toType, ChannelDimension * toDimension) { + if (fromDimension) { + if (!toDimension) { + return ChannelDimensionConformsTo(fromDimension, toType->ty.a.dims, toType->ty.a.numDims); + } else { + return ChannelDimensionConformsToDimension(toDimension, fromDimension); + } + } else { + if (!toDimension) { + size_t i = 0; + if (fromType->ty.a.numDims != toType->ty.a.numDims) { + return 0; + } + + for (i = 0; i < fromType->ty.a.numDims; i++) { + if (fromType->ty.a.dims[i] != toType->ty.a.dims[i]) { + return 0; + } + } + + return 1; + } else { + return ChannelDimensionConformsTo(toDimension, fromType->ty.a.dims, fromType->ty.a.numDims); + } + } +} + +static McxStatus TypeConversionSetup(TypeConversion * conversion, + ChannelType * fromType, + ChannelDimension * fromDimension, + ChannelType * toType, + ChannelDimension * toDimension) { + conversion->sourceSlice = fromDimension; + + if (ChannelTypeConformable(fromType, fromDimension, toType, toDimension)) { + conversion->Convert = TypeConversionConvertId; + /* scalar <-> scalar */ + } else if (ChannelTypeEq(fromType, &ChannelTypeInteger) && ChannelTypeEq(toType, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertIntDouble; + } else if (ChannelTypeEq(fromType, &ChannelTypeDouble) && ChannelTypeEq(toType, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertDoubleInt; + } else if (ChannelTypeEq(fromType, &ChannelTypeBool) && ChannelTypeEq(toType, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertBoolDouble; + } else if (ChannelTypeEq(fromType, &ChannelTypeDouble) && ChannelTypeEq(toType, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertDoubleBool; + } else if (ChannelTypeEq(fromType, &ChannelTypeBool) && ChannelTypeEq(toType, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertBoolInteger; + } else if (ChannelTypeEq(fromType, &ChannelTypeInteger) && ChannelTypeEq(toType, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertIntegerBool; + /* scalar <-> array */ + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeDouble) && ChannelTypeEq(toType, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertArrayDoubleToDouble; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeInteger) && ChannelTypeEq(toType, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertArrayIntegerToDouble; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeBool) && ChannelTypeEq(toType, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertArrayBoolToDouble; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeDouble) && ChannelTypeEq(toType, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertArrayDoubleToBool; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeInteger) && ChannelTypeEq(toType, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertArrayIntegerToBool; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeBool) && ChannelTypeEq(toType, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertArrayBoolToBool; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeDouble) && ChannelTypeEq(toType, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertArrayDoubleToInteger; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeInteger) && ChannelTypeEq(toType, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertArrayIntegerToInteger; + } else if (ChannelTypeIsArray(fromType) && ChannelTypeEq(fromType->ty.a.inner, &ChannelTypeBool) && ChannelTypeEq(toType, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertArrayBoolToInteger; + } else if (ChannelTypeEq(fromType, &ChannelTypeDouble) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertDoubleToArrayDouble; + } else if (ChannelTypeEq(fromType, &ChannelTypeInteger) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertIntegerToArrayDouble; + } else if (ChannelTypeEq(fromType, &ChannelTypeBool) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertBoolToArrayDouble; + } else if (ChannelTypeEq(fromType, &ChannelTypeDouble) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertDoubleToArrayInteger; + } else if (ChannelTypeEq(fromType, &ChannelTypeInteger) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertIntegerToArrayInteger; + } else if (ChannelTypeEq(fromType, &ChannelTypeBool) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertBoolToArrayInteger; + } else if (ChannelTypeEq(fromType, &ChannelTypeDouble) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertDoubleToArrayBool; + } else if (ChannelTypeEq(fromType, &ChannelTypeInteger) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertIntegerToArrayBool; + } else if (ChannelTypeEq(fromType, &ChannelTypeBool) && ChannelTypeIsArray(toType) && ChannelTypeEq(toType->ty.a.inner, &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertBoolToArrayBool; + /* array <-> array */ + } else if (ChannelTypeIsArray(fromType) && ChannelTypeIsArray(toType)) { + if (!DimensionsMatch(fromType, fromDimension, toType, toDimension)) { + mcx_log(LOG_ERROR, "Setup type conversion: Array dimensions do not match"); + return RETURN_ERROR; + } + + if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeInteger) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertArrayIntegerToArrayDouble; + } else if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeBool) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeDouble)) { + conversion->Convert = TypeConversionConvertArrayBoolToArrayDouble; + } else if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeDouble) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertArrayDoubleToArrayInteger; + } else if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeBool) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeInteger)) { + conversion->Convert = TypeConversionConvertArrayBoolToArrayInteger; + } else if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeDouble) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertArrayDoubleToArrayBool; + } else if (ChannelTypeEq(ChannelTypeBaseType(fromType), &ChannelTypeInteger) && ChannelTypeEq(ChannelTypeBaseType(toType), &ChannelTypeBool)) { + conversion->Convert = TypeConversionConvertArrayIntegerToArrayBool; + } else { + mcx_log(LOG_ERROR, "Setup type conversion: Illegal conversion between array types selected"); + return RETURN_ERROR; + } + } else { + mcx_log(LOG_ERROR, "Setup type conversion: Illegal conversion selected"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +static void TypeConversionDestructor(TypeConversion * conversion) { + +} + +static TypeConversion * TypeConversionCreate(TypeConversion * conversion) { + conversion->Setup = TypeConversionSetup; + conversion->Convert = NULL; + + return conversion; } -OBJECT_CLASS(TypeConversion, Conversion); +OBJECT_CLASS(TypeConversion, Object); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/Conversion.h b/src/core/Conversion.h index 4b3a1d6..1c2d3ed 100644 --- a/src/core/Conversion.h +++ b/src/core/Conversion.h @@ -12,11 +12,16 @@ #define MCX_CORE_CONVERSION_H #include "units/Units.h" +#include "core/channels/ChannelDimension.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ + +typedef struct ChannelValueReference ChannelValueReference; + typedef struct Conversion Conversion; typedef McxStatus (* fConversion)(Conversion * conversion, ChannelValue * value); @@ -47,13 +52,15 @@ typedef struct RangeConversion { fRangeConversionSetup Setup; fRangeConversionIsEmpty IsEmpty; - ChannelType type; + ChannelType * type; ChannelValue * min; ChannelValue * max; } RangeConversion; +McxStatus ConvertRange(ChannelValue * min, ChannelValue * max, ChannelValue * value, ChannelDimension * slice); + // ---------------------------------------------------------------------- // Unit Conversion @@ -63,6 +70,7 @@ typedef void(*fUnitConversionVector)(UnitConversion * conversion, double * value typedef McxStatus (* fUnitConversionSetup)(UnitConversion * conversion, const char * fromUnit, const char * toUnit); typedef int (* fUnitConversionIsEmpty)(UnitConversion * conversion); +typedef McxStatus (*fUnitConversionConvertValueRef)(UnitConversion * conversion, ChannelValueReference * ref); extern const struct ObjectClass _UnitConversion; @@ -71,6 +79,7 @@ struct UnitConversion { fUnitConversionSetup Setup; fUnitConversionIsEmpty IsEmpty; + fUnitConversionConvertValueRef ConvertValueReference; si_def source; si_def target; @@ -78,6 +87,8 @@ struct UnitConversion { fUnitConversionVector convertVector; }; +McxStatus ConvertUnit(const char * fromUnit, const char * toUnit, ChannelValue * value, ChannelDimension * slice); + // ---------------------------------------------------------------------- // Linear Conversion @@ -95,31 +106,44 @@ typedef struct LinearConversion { fLinearConversionSetup Setup; fLinearConversionIsEmpty IsEmpty; - ChannelType type; + ChannelType * type; ChannelValue * factor; ChannelValue * offset; } LinearConversion; +McxStatus ConvertLinear(ChannelValue * factor, ChannelValue * offset, ChannelValue * value, ChannelDimension * slice); + // ---------------------------------------------------------------------- // Type Conversion - typedef struct TypeConversion TypeConversion; -typedef McxStatus (* fTypeConversionSetup)(TypeConversion * conversion, ChannelType fromType, ChannelType toType); -typedef int (* fTypeConversionIsEmpty)(TypeConversion * conversion); +typedef McxStatus (*fTypeConversionSetup)(TypeConversion * conversion, + const ChannelType * fromType, + ChannelDimension * fromDimension, + const ChannelType * toType, + ChannelDimension * toDimension); + +// TODO: Ideally the `src` argument would also be ChannelValueReference, but that requires quite of lot of changes +// in the API of databus definition (i.e. DatabusSetIn(Out)Reference) +typedef McxStatus (*fTypeConversionConvert)(TypeConversion * conversion, ChannelValueReference * dest, void * src); extern const struct ObjectClass _TypeConversion; struct TypeConversion { - Conversion _; + Object _; fTypeConversionSetup Setup; - fTypeConversionIsEmpty IsEmpty; + fTypeConversionConvert Convert; + + ChannelDimension * sourceSlice; }; +McxStatus ConvertType(ChannelValue * dest, ChannelDimension * destSlice, ChannelValue * src, ChannelDimension * srcSlice); + + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ diff --git a/src/core/Databus.c b/src/core/Databus.c index e08a004..7e920e7 100644 --- a/src/core/Databus.c +++ b/src/core/Databus.c @@ -22,6 +22,8 @@ #include "core/connections/FilteredConnection.h" +#include "objects/Vector.h" + #include "util/stdlib.h" // private headers, see "Object-oriented programming in ANSI-C", Hanser 1994 @@ -35,374 +37,256 @@ extern "C" { // DatabusInfo static void DatabusInfoDataDestructor(DatabusInfoData * data) { - data->infos->DestroyObjects(data->infos); object_destroy(data->infos); - data->origInfos->DestroyObjects(data->origInfos); - object_destroy(data->origInfos); } static DatabusInfoData * DatabusInfoDataCreate(DatabusInfoData * data) { - data->infos = (ObjectContainer *) object_create(ObjectContainer); - data->origInfos = (ObjectContainer *) object_create(ObjectContainer); + data->infos = (Vector *) object_create(Vector); + data->infos->Setup(data->infos, sizeof(ChannelInfo), ChannelInfoInit, ChannelInfoSetFrom, ChannelInfoDestroy); return data; } OBJECT_CLASS(DatabusInfoData, Object); - -char * CreateIndexedName(const char * name, unsigned i) { - size_t len = 0; - char * buffer = NULL; - - len = strlen(name) + (mcx_digits10(i) + 1) + 2 + 1; - - buffer = (char *) mcx_calloc(len, sizeof(char)); - if (!buffer) { - return NULL; - } - - snprintf(buffer, len, "%s[%d]", name, i); - - return buffer; -} - - - -static ObjectContainer * DatabusReadPortInput(PortInput * input) { +static ChannelInfo * DatabusReadPortInput(PortInput * input) { McxStatus retVal = RETURN_OK; - ObjectContainer * list = NULL; - VectorChannelInfo * vector = NULL; - list = (ObjectContainer *) object_create(ObjectContainer); - if (!list) { - retVal = RETURN_ERROR; - goto cleanup_0; + ChannelInfo * info = (ChannelInfo *)mcx_calloc(1, sizeof(ChannelInfo)); + if (!info) { + return NULL; } - vector = (VectorChannelInfo *)object_create(VectorChannelInfo); - if (!vector) { - retVal = RETURN_ERROR; + retVal = ChannelInfoInit(info); + if (RETURN_ERROR == retVal) { goto cleanup_0; } if (input->type == PORT_VECTOR) { - /* vector of channels: Copy info and add "[i]" to name, nameInTool and id */ - ChannelValue ** mins = NULL; - ChannelValue ** maxs = NULL; - ChannelValue ** scales = NULL; - ChannelValue ** offsets = NULL; - ChannelValue ** defaults = NULL; - ChannelValue ** initials = NULL; - int * writeResults = NULL; - - int startIndex = 0; - int endIndex = 0; - - int i = 0; - VectorPortInput * vectorPortInput = input->port.vectorPort; InputElement * vectorPortElement = (InputElement *) vectorPortInput; - ChannelType expectedType = vectorPortInput->type; - size_t expectedLen = 0; + int startIdx = 0; + int endIdx = 0; - if (!vector) { - retVal = RETURN_ERROR; - goto cleanup_1; - } - - startIndex = vectorPortInput->startIndex; - if (startIndex < 0) { + startIdx = vectorPortInput->startIndex; + if (startIdx < 0) { input_element_error(vectorPortElement, "start index must not be smaller than 0"); retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - endIndex = vectorPortInput->endIndex; - if (endIndex < startIndex) { + endIdx = vectorPortInput->endIndex; + if (endIdx < startIdx) { input_element_error(vectorPortElement, "end index must not be smaller than start index"); retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - expectedLen = endIndex - startIndex + 1; - - retVal = vector->Setup(vector, vectorPortInput->name, vectorPortInput->nameInModel, FALSE, (size_t) startIndex, (size_t) endIndex); - if (RETURN_ERROR == retVal) { - goto cleanup_1; - } - - mins = ArrayToChannelValueArray(vectorPortInput->min, expectedLen, expectedType); - if (vectorPortInput->min && !mins) { + info->dimension = MakeChannelDimension(); + if (!info->dimension) { retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - maxs = ArrayToChannelValueArray(vectorPortInput->max, expectedLen, expectedType); - if (vectorPortInput->max && !maxs) { + if (RETURN_OK != ChannelDimensionSetup(info->dimension, 1)) { + mcx_log(LOG_ERROR, "Could not setup ChannelDimension"); retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - scales = ArrayToChannelValueArray(vectorPortInput->scale, expectedLen, expectedType); - if (vectorPortInput->scale && !scales) { + if (RETURN_OK != ChannelDimensionSetDimension(info->dimension, 0, (size_t) startIdx, (size_t) endIdx)) { + mcx_log(LOG_ERROR, "Could not SetDimension"); retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - offsets = ArrayToChannelValueArray(vectorPortInput->offset, expectedLen, expectedType); - if (vectorPortInput->offset && !offsets) { - retVal = RETURN_ERROR; - goto cleanup_1; - } + size_t dims[1] = { endIdx - startIdx + 1 }; - defaults = ArrayToChannelValueArray(vectorPortInput->default_, expectedLen, expectedType); - if (vectorPortInput->default_ && !defaults) { + if (RETURN_OK != ChannelInfoSetup(info, + vectorPortInput->name, + vectorPortInput->nameInModel, + vectorPortInput->description, + vectorPortInput->unit, + ChannelTypeArray(vectorPortInput->type, 1, dims), + vectorPortInput->id)) { + mcx_log(LOG_ERROR, "Could not Init ChannelInfo"); retVal = RETURN_ERROR; - goto cleanup_1; + goto vector_cleanup_0; } - initials = ArrayToChannelValueArray(vectorPortInput->initial, expectedLen, expectedType); - if (vectorPortInput->initial && !initials) { - retVal = RETURN_ERROR; - goto cleanup_1; - } - - writeResults = vectorPortInput->writeResults; - - for (i = startIndex; i <= endIndex; i++) { - char * name = NULL; - char * nameInTool = NULL; - char * id = NULL; - - ChannelInfo * copy = NULL; - - if (!(name = CreateIndexedName(vectorPortInput->name, i))) { + if (vectorPortInput->min) { + info->min = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->min); + if (!info->min) { retVal = RETURN_ERROR; - goto cleanup_2; - } - if (vectorPortInput->nameInModel) { // optional - if (!(nameInTool = CreateIndexedName(vectorPortInput->nameInModel, i))) { - retVal = RETURN_ERROR; - goto cleanup_2; - } - } - if (vectorPortInput->id) { // optional - if (!(id = CreateIndexedName(vectorPortInput->id, i))) { - retVal = RETURN_ERROR; - goto cleanup_2; - } + goto vector_cleanup_0; } + } - copy = object_create(ChannelInfo); - if (!copy) { + if (vectorPortInput->max) { + info->max = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->max); + if (!info->max) { retVal = RETURN_ERROR; - goto cleanup_2; - } - - copy->SetName(copy, name); - copy->SetNameInTool(copy, nameInTool); - copy->SetID(copy, id); - - copy->SetDescription(copy, vectorPortInput->description); - copy->SetType(copy, vectorPortInput->type); - - if (!copy->IsBinary(copy)) { - copy->SetUnit(copy, vectorPortInput->unit); - } else { - copy->SetUnit(copy, "-"); - } - - copy->SetVector(copy, (VectorChannelInfo *) object_strong_reference(vector)); - - if (mins) { - copy->SetMin(copy, mins[i - startIndex]); - } - if (maxs) { - copy->SetMax(copy, maxs[i - startIndex]); - } - - if (scales) { - copy->SetScale(copy, scales[i - startIndex]); - } - if (offsets) { - copy->SetOffset(copy, offsets[i - startIndex]); - } - - if (defaults) { - copy->SetDefault(copy, defaults[i - startIndex]); - } - if (initials) { - copy->SetInitial(copy, initials[i - startIndex]); - } - if (writeResults) { - copy->SetWriteResult(copy, writeResults[i - startIndex]); + goto vector_cleanup_0; } + } - retVal = vector->AddElement(vector, copy, i); - if (RETURN_ERROR == retVal) { - goto cleanup_2; + if (vectorPortInput->scale) { + info->scale = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->scale); + if (!info->scale) { + retVal = RETURN_ERROR; + goto vector_cleanup_0; } + } - list->PushBack(list, (Object *) copy); - - cleanup_2: - - if (name) { - mcx_free(name); - } - if (nameInTool) { - mcx_free(nameInTool); - } - if (id) { - mcx_free(id); - } - if (RETURN_ERROR == retVal) { - goto cleanup_1; + if (vectorPortInput->offset) { + info->offset = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->offset); + if (!info->offset) { + retVal = RETURN_ERROR; + goto vector_cleanup_0; } } - cleanup_1: - - if (mins) { - mcx_free(mins); - } - if (maxs) { - mcx_free(maxs); + if (vectorPortInput->initial) { + info->initialValue = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->initial); + if (!info->initialValue) { + retVal = RETURN_ERROR; + goto vector_cleanup_0; + } } - if (scales) { - mcx_free(scales); - } - if (offsets) { - mcx_free(offsets); + if (vectorPortInput->default_) { + info->defaultValue = ChannelValueNewArray(1, dims, vectorPortInput->type, vectorPortInput->default_); + if (!info->defaultValue) { + retVal = RETURN_ERROR; + goto vector_cleanup_0; + } } - if (defaults) { - mcx_free(defaults); - } - if (initials) { - mcx_free(initials); - } - if (writeResults) { - // writeResults was taken from vectorPortInput + if (vectorPortInput->writeResults.defined) { + info->writeResult = vectorPortInput->writeResults.value; } - if (RETURN_ERROR == retVal) { + vector_cleanup_0: + if (retVal == RETURN_ERROR) { goto cleanup_0; } } else { ScalarPortInput * scalarPortInput = input->port.scalarPort; - ChannelInfo * info = object_create(ChannelInfo); - if (!info) { - retVal = RETURN_ERROR; - goto cleanup_0; + retVal = ChannelInfoInit(info); + if (RETURN_ERROR == retVal) { + goto cleanup_else_1; } - info->SetName(info, scalarPortInput->name); - info->SetNameInTool(info, scalarPortInput->nameInModel); - info->SetDescription(info, scalarPortInput->description); - info->SetID(info, scalarPortInput->id); - info->SetType(info, scalarPortInput->type); + ChannelInfoSetName(info, scalarPortInput->name); + ChannelInfoSetNameInTool(info, scalarPortInput->nameInModel); + ChannelInfoSetDescription(info, scalarPortInput->description); + ChannelInfoSetID(info, scalarPortInput->id); + ChannelInfoSetType(info, scalarPortInput->type); - if (!info->IsBinary(info)) { - info->SetUnit(info, scalarPortInput->unit); + if (!ChannelInfoIsBinary(info)) { + ChannelInfoSetUnit(info, scalarPortInput->unit); } else { - info->SetUnit(info, "-"); + ChannelInfoSetUnit(info, "-"); } - ChannelType expectedType = info->GetType(info); - + ChannelType * expectedType = info->type; ChannelValue value; - ChannelValueInit(&value, expectedType); + ChannelValueInit(&value, ChannelTypeClone(expectedType)); if (scalarPortInput->min.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->min.value); - info->SetMin(info, ChannelValueClone(&value)); - if (!info->GetMin(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->min.value)) { + goto cleanup_else_1; + } + info->min = ChannelValueClone(&value); + if (!info->min) { goto cleanup_else_1; } } if (scalarPortInput->max.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->max.value); - info->SetMax(info, ChannelValueClone(&value)); - if (!info->GetMax(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->max.value)) { + goto cleanup_else_1; + } + info->max = ChannelValueClone(&value); + if (!info->max) { goto cleanup_else_1; } } if (scalarPortInput->scale.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->scale.value); - info->SetScale(info, ChannelValueClone(&value)); - if (!info->GetScale(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->scale.value)) { + goto cleanup_else_1; + } + info->scale = ChannelValueClone(&value); + if (!info->scale) { goto cleanup_else_1; } } if (scalarPortInput->offset.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->offset.value); - info->SetOffset(info, ChannelValueClone(&value)); - if (!info->GetOffset(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->offset.value)) { + goto cleanup_else_1; + } + info->offset = ChannelValueClone(&value); + if (!info->offset) { goto cleanup_else_1; } } if (scalarPortInput->default_.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->default_.value); - info->SetDefault(info, ChannelValueClone(&value)); - if (!info->GetDefault(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->default_.value)) { + goto cleanup_else_1; + } + info->defaultValue = ChannelValueClone(&value); + if (!info->defaultValue) { goto cleanup_else_1; } } if (scalarPortInput->initial.defined) { - ChannelValueSetFromReference(&value, &scalarPortInput->initial.value); - info->SetInitial(info, ChannelValueClone(&value)); - if (!info->GetInitialValue(info)) { + if (RETURN_OK != ChannelValueSetFromReference(&value, &scalarPortInput->initial.value)) { + goto cleanup_else_1; + } + info->initialValue = ChannelValueClone(&value); + if (!info->initialValue) { goto cleanup_else_1; } } if (scalarPortInput->writeResults.defined) { - info->SetWriteResult(info, scalarPortInput->writeResults.value); - } - - retVal = vector->Setup(vector, info->GetName(info), info->GetNameInTool(info), TRUE, -1, -1); - if (RETURN_ERROR == retVal) { - goto cleanup_else_1; + info->writeResult = scalarPortInput->writeResults.value; } - info->SetVector(info, (VectorChannelInfo *) object_strong_reference(vector)); - - retVal = vector->AddElement(vector, info, 0); - if (RETURN_ERROR == retVal) { - goto cleanup_else_1; - } - - list->PushBack(list, (Object *) object_strong_reference(info)); cleanup_else_1: - object_destroy(info); ChannelValueDestructor(&value); goto cleanup_0; } cleanup_0: if (RETURN_ERROR == retVal) { - object_destroy(list); + object_destroy(info); } - object_destroy(vector); + return info; +} + +static int ChannelInfoSameNamePred(void * elem, const char * name) { + ChannelInfo * info = (ChannelInfo *) elem; - return list; + return 0 == strcmp(ChannelInfoGetName(info), name); } +static int ChannelInfosGetNameIdx(Vector * infos, const char * name) { + size_t idx = infos->FindIdx(infos, ChannelInfoSameNamePred, name); + + return idx == SIZE_T_ERROR ? -1 : (int)idx; +} int DatabusInfoGetChannelID(DatabusInfo * info, const char * name) { - return info->data->infos->GetNameIndex(info->data->infos, name); + return ChannelInfosGetNameIdx(info->data->infos, name); } McxStatus DatabusInfoRead(DatabusInfo * dbInfo, @@ -417,76 +301,86 @@ McxStatus DatabusInfoRead(DatabusInfo * dbInfo, size_t numChildren = input->ports->Size(input->ports); - ObjectContainer * allChannels = dbInfo->data->origInfos; - if (NULL == allChannels) { - mcx_log(LOG_ERROR, "Ports: Read port infos: Container of vector ports missing"); - return RETURN_ERROR; + Vector * dbInfos = dbInfo->data->infos; + size_t requiredSize = 0; + StringContainer * portNames = StringContainerCreate(numChildren); + + if (!portNames) { + mcx_log(LOG_ERROR, "Ports: Port name container allocation failed"); + retVal = RETURN_ERROR; + goto cleanup; } for (i = 0; i < numChildren; i++) { PortInput * portInput = (PortInput *) input->ports->At(input->ports, i); - - ObjectContainer * dbInfos = dbInfo->data->infos; - ObjectContainer * infos = NULL; - - infos = DatabusReadPortInput(portInput); - if (!infos) { - mcx_log(LOG_ERROR, "Ports: Read port infos: Could not read info of port %d", i); - return RETURN_ERROR; + if (portInput->type == PORT_SCALAR) { + requiredSize++; + } else { + requiredSize += portInput->port.vectorPort->endIndex - portInput->port.vectorPort->startIndex + 1; } - { - ChannelInfo * chInfo = (ChannelInfo *) infos->At(infos, 0); - allChannels->PushBack(allChannels, (Object *) object_strong_reference(chInfo->vector)); + ChannelInfo * info = DatabusReadPortInput(portInput); + if (!info) { + mcx_log(LOG_ERROR, "Ports: Read port infos: Could not read info of port %zu", i); + retVal = RETURN_ERROR; + goto cleanup; } - for (j = 0; j < infos->Size(infos); j++) { - ChannelInfo * info = (ChannelInfo *) infos->At(infos, j); - const char * name = info->GetName(info); - int n = dbInfos->GetNameIndex(dbInfos, name); + info->mode = mode; - if (n >= 0) { // key already exists - mcx_log(LOG_ERROR, "Ports: Duplicate port %s", name); - infos->DestroyObjects(infos); - object_destroy(infos); - return RETURN_ERROR; - } + const char * name = ChannelInfoGetName(info); + if (info->dimension) { + mcx_log(LOG_DEBUG, " Port: \"%s[%zu:%zu]\"", name, info->dimension->startIdxs[0], info->dimension->endIdxs[0]); + } else { mcx_log(LOG_DEBUG, " Port: \"%s\"", name); - infos->SetElementName(infos, j, name); + } - info->SetMode(info, mode); + { + // check for duplicates + int n = StringContainerGetIndex(portNames, name); + if (n >= 0) { // key already exists + mcx_log(LOG_ERROR, "Ports: Duplicate port %s", name); + retVal = RETURN_ERROR; + goto cleanup; + } } - if (infos->Size(infos) == 1 && SpecificRead) { - ChannelInfo * info = (ChannelInfo *) infos->At(infos, infos->Size(infos) - 1); + if (SpecificRead) { retVal = SpecificRead(comp, info, portInput, i); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Ports: Read port infos: Could not read element specific data of port %d", i); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Read port infos: Could not read element specific data of port %zu", i); + goto cleanup; } } - retVal = dbInfos->Append(dbInfos, infos); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Ports: Read port infos: Could not append info of port %d", i); - object_destroy(infos); - return RETURN_ERROR; + if (RETURN_OK != dbInfos->PushBack(dbInfos, info)) { + mcx_log(LOG_ERROR, "Ports: Read port infos: Could not append info of port %zu", i); + retVal = RETURN_ERROR; + goto cleanup; + } + + retVal = StringContainerAddString(portNames, name); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Ports: Storing port name failed"); + goto cleanup; } - object_destroy(infos); } - return RETURN_OK; + +cleanup: + StringContainerDestroy(portNames); + + return retVal; } -static int IsWriteResults(Object * obj) { - ChannelInfo * info = (ChannelInfo *) obj; +static int IsWriteResults(void * elem, void * ignore) { + ChannelInfo * info = (ChannelInfo *) elem; - return info->GetWriteResultFlag(info); + return info->writeResult; } size_t DatabusInfoGetNumWriteChannels(DatabusInfo * dbInfo) { - ObjectContainer * infos = dbInfo->data->infos; - - ObjectContainer * writeInfos = infos->Filter(infos, IsWriteResults); + Vector * infos = dbInfo->data->infos; + Vector * writeInfos = infos->FilterRef(infos, IsWriteResults, NULL); size_t num = writeInfos->Size(writeInfos); @@ -527,6 +421,9 @@ static void DatabusDataDestructor(DatabusData * data) { } mcx_free(data->in); } + if (data->inConnected) { + mcx_free(data->inConnected); + } if (data->out) { size_t num = DatabusInfoGetChannelNum(data->outInfo); @@ -570,6 +467,9 @@ static void DatabusDataDestructor(DatabusData * data) { static DatabusData * DatabusDataCreate(DatabusData * data) { data->in = NULL; + data->inConnected = NULL; + data->numInConnected = 0; + data->out = NULL; data->local = NULL; data->rtfactor = NULL; @@ -599,6 +499,24 @@ static DatabusData * DatabusDataCreate(DatabusData * data) { OBJECT_CLASS(DatabusData, Object); +McxStatus DatabusUpdateInConnected(Databus * db) { + size_t i = 0; + size_t numIn = DatabusInfoGetChannelNum(DatabusGetInInfo(db)); + + db->data->numInConnected = 0; + + for (i = 0; i < numIn; i++) { + ChannelIn * chIn = db->data->in[i]; + Channel * ch = (Channel *) chIn; + + if (ch->IsConnected(ch)) { + db->data->inConnected[db->data->numInConnected] = db->data->in[i]; + db->data->numInConnected++; + } + } + + return RETURN_OK; +} McxStatus DatabusSetup(Databus * db, DatabusInfo * in, DatabusInfo * out, Config * config) { @@ -617,6 +535,13 @@ McxStatus DatabusSetup(Databus * db, DatabusInfo * in, DatabusInfo * out, Config mcx_log(LOG_ERROR, "Ports: Memory allocation for inports failed"); return RETURN_ERROR; } + + db->data->inConnected = (ChannelIn **)mcx_calloc(numIn, sizeof(ChannelIn *)); + if (db->data->inConnected == NULL) { + mcx_log(LOG_ERROR, "Ports: Memory allocation for connected inports failed"); + return RETURN_ERROR; + } + for (i = 0; i < numIn; i++) { db->data->in[i] = (ChannelIn *) object_create(ChannelIn); if (!db->data->in[i]) { @@ -686,8 +611,8 @@ McxStatus DatabusTriggerOutChannels(Databus *db, TimeInterval * time) { out = (Channel *) db->data->out[i]; retVal = out->Update(out, time); if (RETURN_OK != retVal) { - ChannelInfo * info = out->GetInfo(out); - mcx_log(LOG_ERROR, "Could not update outport %s", info->GetName(info)); + ChannelInfo * info = &out->info; + mcx_log(LOG_ERROR, "Could not update outport %s", ChannelInfoGetName(info)); return RETURN_ERROR; } } @@ -695,6 +620,30 @@ McxStatus DatabusTriggerOutChannels(Databus *db, TimeInterval * time) { return RETURN_OK; } + +McxStatus DatabusTriggerConnectedInConnections(Databus * db, TimeInterval * consumerTime) { + if (!db) { + mcx_log(LOG_ERROR, "Ports: Trigger inports: Invalid structure"); + return RETURN_ERROR; + } + size_t i = 0; + + McxStatus retVal = RETURN_OK; + + for (i = 0; i < db->data->numInConnected; i++) { + Channel * channel = (Channel *)db->data->inConnected[i]; + retVal = channel->Update(channel, consumerTime); + if (RETURN_OK != retVal) { + ChannelInfo * info = &channel->info; + mcx_log(LOG_ERROR, "Could not update inport %s", ChannelInfoGetName(info)); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + + McxStatus DatabusTriggerInConnections(Databus * db, TimeInterval * consumerTime) { if (!db) { mcx_log(LOG_ERROR, "Ports: Trigger inports: Invalid structure"); @@ -707,11 +656,11 @@ McxStatus DatabusTriggerInConnections(Databus * db, TimeInterval * consumerTime) for (i = 0; i < numIn; i++) { Channel * channel = (Channel *) db->data->in[i]; - if (channel->IsValid(channel)) { + if (channel->IsConnected(channel) || channel->info.defaultValue) { retVal = channel->Update(channel, consumerTime); if (RETURN_OK != retVal) { - ChannelInfo * info = channel->GetInfo(channel); - mcx_log(LOG_ERROR, "Could not update inport %s", info->GetName(info)); + ChannelInfo * info = &channel->info; + mcx_log(LOG_ERROR, "Could not update inport %s", ChannelInfoGetName(info)); return RETURN_ERROR; } } @@ -735,8 +684,8 @@ Connection * DatabusCreateConnection(Databus * db, ConnectionInfo * info) { ChannelOut * outChannel = NULL; ChannelIn * inChannel = NULL; - size_t outChannelID = info->GetSourceChannelID(info); - size_t inChannelID = info->GetTargetChannelID(info); + size_t outChannelID = info->sourceChannel; + size_t inChannelID = info->targetChannel; char * connStr = NULL; @@ -750,7 +699,7 @@ Connection * DatabusCreateConnection(Databus * db, ConnectionInfo * info) { outChannel = db->data->out[outChannelID]; - target = info->GetTargetComponent(info); + target = info->targetComponent; // get inChannel inDb = target->GetDatabus(target); @@ -761,7 +710,7 @@ Connection * DatabusCreateConnection(Databus * db, ConnectionInfo * info) { inChannel = inDb->data->in[inChannelID]; - connStr = info->ConnectionString(info); + connStr = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, " Connection: %s", connStr); if (connStr) { mcx_free(connStr); @@ -777,7 +726,7 @@ Connection * DatabusCreateConnection(Databus * db, ConnectionInfo * info) { retVal = connection->Setup(connection, outChannel, inChannel, info); if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); if (buffer) { mcx_log(LOG_ERROR, "Create connection: Could not setup connection %s", buffer); mcx_free(buffer); @@ -840,14 +789,22 @@ size_t DatabusInfoGetChannelNum(DatabusInfo * info) { return info->data->infos->Size(info->data->infos); } -// Only returns SIZE_T_ERROR if info was NULL -size_t DatabusInfoGetVectorChannelNum(DatabusInfo * info) { - if (!info) { - mcx_log(LOG_ERROR, "Ports: Get vector port number: Invalid structure"); - return SIZE_T_ERROR; +size_t DatabusInfoGetChannelElemNum(DatabusInfo * info) { + size_t numInfos = info->data->infos->Size(info->data->infos); + size_t i = 0; + size_t numElems = 0; + + for (i = 0; i < numInfos; i++) { + ChannelInfo * chInfo = (ChannelInfo*)info->data->infos->At(info->data->infos, i); + if (chInfo->dimension) { + // array + numElems += ChannelDimensionNumElements(chInfo->dimension); + } else { + numElems += 1; + } } - return info->data->origInfos->Size(info->data->origInfos); + return numElems; } ChannelInfo * DatabusInfoGetChannel(DatabusInfo * info, size_t i) { @@ -864,20 +821,13 @@ ChannelInfo * DatabusInfoGetChannel(DatabusInfo * info, size_t i) { return (ChannelInfo *) info->data->infos->At(info->data->infos, i); } -static VectorChannelInfo * DatabusInfoGetVectorChannelInfo(DatabusInfo * info, size_t i) { - if (!info) { - mcx_log(LOG_ERROR, "Ports: Get vector port info: Invalid structure"); - return NULL; - } - - if (i >= info->data->origInfos->Size(info->data->origInfos)) { - mcx_log(LOG_ERROR, "Ports: Get vector port info: Unknown port %d", i); - return NULL; - } - - return (VectorChannelInfo *) info->data->origInfos->At(info->data->origInfos, i); +int DatabusInChannelsDefined(Databus * db) { + return db->data->in != NULL; } +int DatabusOutChannelsDefined(Databus* db) { + return db->data->out != NULL; +} ChannelIn * DatabusGetInChannel(Databus * db, size_t i) { DatabusInfo * info = NULL; @@ -983,26 +933,6 @@ size_t DatabusGetInChannelsNum(Databus * db) { return DatabusInfoGetChannelNum(DatabusGetInInfo(db)); } -// Only returns SIZE_T_ERROR if db was NULL -size_t DatabusGetOutVectorChannelsNum(Databus * db) { - if (!db) { - mcx_log(LOG_ERROR, "Ports: Get outport number: Invalid structure"); - return SIZE_T_ERROR; - } - - return DatabusInfoGetVectorChannelNum(DatabusGetOutInfo(db)); -} - -// Only returns SIZE_T_ERROR if db was NULL -size_t DatabusGetInVectorChannelsNum(Databus * db) { - if (!db) { - mcx_log(LOG_ERROR, "Ports: Get inport number: Invalid structure"); - return SIZE_T_ERROR; - } - - return DatabusInfoGetVectorChannelNum(DatabusGetInInfo(db)); -} - // Only returns SIZE_T_ERROR if db was NULL size_t DatabusGetLocalChannelsNum(Databus * db) { if (!db) { @@ -1023,8 +953,16 @@ size_t DatabusGetRTFactorChannelsNum(Databus * db) { return DatabusInfoGetChannelNum(DatabusGetRTFactorInfo(db)); } +size_t DatabusGetOutChannelsElemNum(Databus * db) { + return DatabusInfoGetChannelElemNum(DatabusGetOutInfo(db)); +} + +size_t DatabusGetInChannelsElemNum(Databus * db) { + return DatabusInfoGetChannelElemNum(DatabusGetInInfo(db)); +} + -McxStatus DatabusSetOutReference(Databus * db, size_t channel, const void * reference, ChannelType type) { +McxStatus DatabusSetOutReference(Databus * db, size_t channel, const void * reference, ChannelType * type) { ChannelOut * out = NULL; if (!db) { @@ -1042,14 +980,14 @@ McxStatus DatabusSetOutReference(Databus * db, size_t channel, const void * refe return RETURN_ERROR; } - if (CHANNEL_UNKNOWN != type) { - ChannelInfo * info = ((Channel *)out)->GetInfo((Channel *) out); - if (info->GetType(info) != type) { - if (info->IsBinary(info) && (type == CHANNEL_BINARY || type == CHANNEL_BINARY_REFERENCE)) { + if (ChannelTypeIsValid(type)) { + ChannelInfo * info = &((Channel *)out)->info; + if (!ChannelTypeEq(info->type, type)) { + if (ChannelInfoIsBinary(info) && ChannelTypeIsBinary(type)) { // ok } else { mcx_log(LOG_ERROR, "Ports: Set out reference: Port %s has mismatching type %s, given: %s", - info->GetName(info), ChannelTypeToString(info->GetType(info)), ChannelTypeToString(type)); + ChannelInfoGetName(info), ChannelTypeToString(info->type), ChannelTypeToString(type)); return RETURN_ERROR; } } @@ -1058,7 +996,7 @@ McxStatus DatabusSetOutReference(Databus * db, size_t channel, const void * refe return out->SetReference(out, reference, type); } -McxStatus DatabusSetOutReferenceFunction(Databus * db, size_t channel, const void * reference, ChannelType type) { +McxStatus DatabusSetOutReferenceFunction(Databus * db, size_t channel, const void * reference, ChannelType * type) { ChannelOut * out = NULL; ChannelInfo * info = NULL; @@ -1077,13 +1015,13 @@ McxStatus DatabusSetOutReferenceFunction(Databus * db, size_t channel, const voi return RETURN_ERROR; } - info = ((Channel *)out)->GetInfo((Channel *) out); - if (info->GetType(info) != type) { + info = &((Channel *)out)->info; + if (!ChannelTypeEq(info->type, type)) { mcx_log(LOG_ERROR, "Ports: Set out reference function: Port %s has mismatching type %s, given: %s", - info->GetName(info), ChannelTypeToString(info->GetType(info)), ChannelTypeToString(type)); + ChannelInfoGetName(info), ChannelTypeToString(info->type), ChannelTypeToString(type)); return RETURN_ERROR; } - if (info->IsBinary(info)) { + if (ChannelInfoIsBinary(info)) { mcx_log(LOG_ERROR, "Ports: Set out reference function: Illegal type: Binary"); return RETURN_ERROR; } @@ -1091,123 +1029,7 @@ McxStatus DatabusSetOutReferenceFunction(Databus * db, size_t channel, const voi return out->SetReferenceFunction(out, (const proc *) reference, type); } -McxStatus DatabusSetOutRefVectorChannel(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, ChannelValue * value) -{ - VectorChannelInfo * vInfo = NULL; - size_t i = 0; - size_t ii = 0; - ChannelType type = ChannelValueType(value); - - if (startIdx > endIdx) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Start index %d bigger than end index %d", startIdx, endIdx); - return RETURN_ERROR; - } - if (CHANNEL_UNKNOWN == type) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Type of vector needs to be specified"); - return RETURN_ERROR; - } - - if (channel > DatabusGetOutVectorChannelsNum(db)) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector port %d does not exist (numer of vector ports=%d)", channel, DatabusGetOutVectorChannelsNum(db)); - return RETURN_ERROR; - } - - vInfo = DatabusGetOutVectorChannelInfo(db, channel); - for (i = startIdx; i <= endIdx; i++) { - McxStatus retVal = RETURN_OK; - const void * ref = NULL; - ChannelOut * chOut = NULL; - ChannelInfo * chInfo = vInfo->GetElement(vInfo, i); - if (!chInfo) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector Port does not exist"); - return RETURN_ERROR; - } - chOut = (ChannelOut *) chInfo->channel; - if (!chOut) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector Port not initialized"); - return RETURN_ERROR; - } - ii = i - startIdx; - ref = (const void *) ( &((ChannelValue*)value + ii)->value ); - - retVal = chOut->SetReference(chOut, ref, type); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Reference could not be set"); - return RETURN_ERROR; - } - } - - return RETURN_OK; -} - -McxStatus DatabusSetOutRefVector(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, const void * reference, ChannelType type) -{ - VectorChannelInfo * vInfo = NULL; - size_t i = 0; - size_t ii = 0; - - if (startIdx > endIdx) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Start index %d bigger than end index %d", startIdx, endIdx); - return RETURN_ERROR; - } - if (CHANNEL_UNKNOWN == type) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Type of vector needs to be specified"); - return RETURN_ERROR; - } - - if (channel > DatabusGetOutVectorChannelsNum(db)) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector port %d does not exist (numer of vector ports=%d)", channel, DatabusGetOutVectorChannelsNum(db)); - return RETURN_ERROR; - } - - vInfo = DatabusGetOutVectorChannelInfo(db, channel); - for (i = startIdx; i <= endIdx; i++) { - McxStatus retVal = RETURN_OK; - const void * ref = NULL; - ChannelOut * chOut = NULL; - ChannelInfo * chInfo = vInfo->GetElement(vInfo, i); - if (!chInfo) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector Port does not exist"); - return RETURN_ERROR; - } - chOut = (ChannelOut *) chInfo->channel; - if (!chOut) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Vector Port not initialized"); - return RETURN_ERROR; - } - ii = i - startIdx; - switch (type) { - case CHANNEL_DOUBLE: - ref = (const void *) (((double *) reference) + ii); - break; - case CHANNEL_INTEGER: - ref = (const void *) (((int *) reference) + ii); - break; - case CHANNEL_BOOL: - ref = (const void *) (((int *) reference) + ii); - break; - case CHANNEL_BINARY: - case CHANNEL_BINARY_REFERENCE: - ref = (const void *) (((binary_string *) reference) + ii); - break; - default: - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Type of vector not allowed"); - return RETURN_ERROR; - } - - retVal = chOut->SetReference(chOut, ref, type); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Ports: Set out reference vector: Reference could not be set"); - return RETURN_ERROR; - } - } - - return RETURN_OK; -} - -McxStatus DatabusSetInReference(Databus * db, size_t channel, void * reference, ChannelType type) { +McxStatus DatabusSetInReference(Databus * db, size_t channel, void * reference, ChannelType * type) { ChannelIn * in = NULL; ChannelInfo * info = NULL; @@ -1226,14 +1048,15 @@ McxStatus DatabusSetInReference(Databus * db, size_t channel, void * reference, return RETURN_ERROR; } - if (CHANNEL_UNKNOWN != type) { - info = ((Channel *)in)->GetInfo((Channel *)in); - if (info->GetType(info) != type) { - if (info->IsBinary(info) && (type == CHANNEL_BINARY || type == CHANNEL_BINARY_REFERENCE)) { + if (ChannelTypeIsValid(type)) { + info = &((Channel *)in)->info; + if (!ChannelTypeEq(info->type, type)) { + // TODO: Remove ChannelInfoIsBinary, use ChannelTypeIsBinary instead? + if (ChannelInfoIsBinary(info) && ChannelTypeIsBinary(type)) { // ok } else { mcx_log(LOG_ERROR, "Ports: Set in-reference: Port %s has mismatching type %s, given: %s", - info->GetName(info), ChannelTypeToString(info->GetType(info)), ChannelTypeToString(type)); + ChannelInfoGetName(info), ChannelTypeToString(info->type), ChannelTypeToString(type)); return RETURN_ERROR; } } @@ -1242,109 +1065,6 @@ McxStatus DatabusSetInReference(Databus * db, size_t channel, void * reference, return in->SetReference(in, reference, type); } -McxStatus DatabusSetInRefVector(Databus * db, size_t channel, size_t startIdx, size_t endIdx, void * reference, ChannelType type) -{ - VectorChannelInfo * vInfo = NULL; - size_t i = 0; - size_t ii = 0; - if (startIdx > endIdx) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Start index %d bigger than end index %d", startIdx, endIdx); - return RETURN_ERROR; - } - if (CHANNEL_UNKNOWN == type) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Type of vector needs to be specified"); - return RETURN_ERROR; - } - if (channel > DatabusGetInVectorChannelsNum(db)) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector port %d does not exist (numer of vector ports=%d)", channel, DatabusGetOutVectorChannelsNum(db)); - return RETURN_ERROR; - } - - vInfo = DatabusGetInVectorChannelInfo(db, channel); - for (i = startIdx; i <= endIdx; i++) { - McxStatus retVal = RETURN_OK; - void * ref = NULL; - ChannelIn * chIn = NULL; - ChannelInfo * chInfo = vInfo->GetElement(vInfo, i); - if (!chInfo) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector Port does not exist"); - return RETURN_ERROR; - } - chIn = (ChannelIn *) chInfo->channel; - if (!chIn) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector Port not initialized"); - return RETURN_ERROR; - } - ii = i - startIdx; - if (CHANNEL_DOUBLE == type) { - ref = (void *) (((double *) reference) + ii); - } else if (CHANNEL_INTEGER == type) { - ref = (void *) (((int *) reference) + ii); - } else if (CHANNEL_BOOL == type) { - ref = (void *) (((int *) reference) + ii); - } else { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Type of vector not allowed"); - return RETURN_ERROR; - } - retVal = chIn->SetReference(chIn, ref, type); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Reference could not be set"); - return RETURN_ERROR; - } - } - - return RETURN_OK; -} - -McxStatus DatabusSetInRefVectorChannel(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, ChannelValue * value) -{ - VectorChannelInfo * vInfo = NULL; - size_t i = 0; - size_t ii = 0; - ChannelType type = ChannelValueType(value); - - if (startIdx > endIdx) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Start index %d bigger than end index %d", startIdx, endIdx); - return RETURN_ERROR; - } - if (CHANNEL_UNKNOWN == type) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Type of vector needs to be specified"); - return RETURN_ERROR; - } - if (channel > DatabusGetInVectorChannelsNum(db)) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector port %d does not exist (numer of vector ports=%d)", channel, DatabusGetInVectorChannelsNum(db)); - return RETURN_ERROR; - } - - vInfo = DatabusGetInVectorChannelInfo(db, channel); - for (i = startIdx; i <= endIdx; i++) { - McxStatus retVal = RETURN_OK; - void * ref = NULL; - ChannelIn * chIn = NULL; - ChannelInfo * chInfo = vInfo->GetElement(vInfo, i); - if (!chInfo) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector Port does not exist"); - return RETURN_ERROR; - } - chIn = (ChannelIn *) chInfo->channel; - if (!chIn) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Vector Port not initialized"); - return RETURN_ERROR; - } - ii = i - startIdx; - ref = (void *) ( &((ChannelValue*)value + ii)->value ); - - retVal = chIn->SetReference(chIn, ref, type); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Ports: Set in reference vector: Reference could not be set"); - return RETURN_ERROR; - } - } - - return RETURN_OK; -} - static char * DatabusGetUniqueChannelName(Databus * db, const char * name) { #define SUFFIX_LEN 5 @@ -1352,19 +1072,19 @@ static char * DatabusGetUniqueChannelName(Databus * db, const char * name) { size_t suffix = 1; char suffixStr[SUFFIX_LEN] = ""; - ObjectContainer * inInfos = db->data->inInfo->data->infos; - ObjectContainer * outInfos = db->data->outInfo->data->infos; - ObjectContainer * localInfos = db->data->localInfo->data->infos; - ObjectContainer * rtfactorInfos = db->data->rtfactorInfo->data->infos; + Vector * inInfos = db->data->inInfo->data->infos; + Vector * outInfos = db->data->outInfo->data->infos; + Vector * localInfos = db->data->localInfo->data->infos; + Vector * rtfactorInfos = db->data->rtfactorInfo->data->infos; /* Make name unique by adding " %d" suffix */ uniqueName = (char *) mcx_calloc(strlen(name) + SUFFIX_LEN + 1, sizeof(char)); strcpy(uniqueName, name); strcat(uniqueName, suffixStr); - while (inInfos->GetNameIndex(inInfos, uniqueName) > -1 - || outInfos->GetNameIndex(outInfos, uniqueName) > -1 - || localInfos->GetNameIndex(localInfos, uniqueName) > -1) { + while (ChannelInfosGetNameIdx(inInfos, uniqueName) > -1 + || ChannelInfosGetNameIdx(outInfos, uniqueName) > -1 + || ChannelInfosGetNameIdx(localInfos, uniqueName) > -1) { int len = snprintf(suffixStr, SUFFIX_LEN," %zu", suffix); strcpy(uniqueName, name); strcat(uniqueName, suffixStr); @@ -1381,62 +1101,71 @@ static McxStatus DatabusAddLocalChannelInternal(Databus * db, const char * id, const char * unit, const void * reference, - ChannelType type) { - ChannelInfo * chInfo = NULL; + ChannelType * type) { + ChannelInfo chInfo = { 0 }; ChannelLocal * local = NULL; Channel * channel = NULL; + size_t infoDataSize = 0; char * uniqueName = NULL; McxStatus retVal = RETURN_OK; - chInfo = (ChannelInfo *) object_create(ChannelInfo); - if (!chInfo) { + + retVal = ChannelInfoInit(&chInfo); + if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Ports: Set local-reference: Create port info for %s failed", name); return RETURN_ERROR; } uniqueName = DatabusGetUniqueChannelName(db, name); - retVal = chInfo->Init(chInfo, uniqueName, NULL, unit, type, id); + retVal = ChannelInfoSetup(&chInfo, uniqueName, uniqueName, NULL, unit, type, id); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Initializing ChannelInfo for %s failed", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Setting up ChannelInfo for %s failed", ChannelInfoGetName(&chInfo)); + goto cleanup; } mcx_free(uniqueName); - retVal = infoData->infos->PushBack(infoData->infos, (Object *) chInfo); + retVal = infoData->infos->PushBack(infoData->infos, &chInfo); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Storing ChannelInfo for %s failed", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Storing ChannelInfo for %s failed", ChannelInfoGetName(&chInfo)); + goto cleanup; } + infoDataSize = infoData->infos->Size(infoData->infos); + local = (ChannelLocal *) object_create(ChannelLocal); if (!local) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Create port %s failed", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Create port %s failed", ChannelInfoGetName(&chInfo)); + retVal = RETURN_ERROR; + goto cleanup; } channel = (Channel *) local; - retVal = channel->Setup(channel, chInfo); + retVal = channel->Setup(channel, infoData->infos->At(infoData->infos, infoDataSize - 1)); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Could not setup port %s", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Could not setup port %s", ChannelInfoGetName(&chInfo)); + goto cleanup; } retVal = local->SetReference(local, reference, type); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Setting reference to %s failed", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Setting reference to %s failed", ChannelInfoGetName(&chInfo)); + goto cleanup; } - *dbDataChannel = (ChannelLocal * *) mcx_realloc(*dbDataChannel, infoData->infos->Size(infoData->infos) * sizeof(Channel *)); + *dbDataChannel = (ChannelLocal * *) mcx_realloc(*dbDataChannel, infoDataSize * sizeof(Channel *)); if (!*dbDataChannel) { - mcx_log(LOG_ERROR, "Ports: Set local-reference: Memory reallocation for adding %s to ports failed", chInfo->GetName(chInfo)); - return RETURN_ERROR; + mcx_log(LOG_ERROR, "Ports: Set local-reference: Memory reallocation for adding %s to ports failed", ChannelInfoGetName(&chInfo)); + retVal = RETURN_ERROR; + goto cleanup; } - (*dbDataChannel)[infoData->infos->Size(infoData->infos) - 1] = (ChannelLocal *) channel; + (*dbDataChannel)[infoDataSize - 1] = (ChannelLocal *) channel; - return RETURN_OK; +cleanup: + ChannelInfoDestroy(&chInfo); + + return retVal; } McxStatus DatabusAddLocalChannel(Databus * db, @@ -1444,7 +1173,7 @@ McxStatus DatabusAddLocalChannel(Databus * db, const char * id, const char * unit, const void * reference, - ChannelType type) { + ChannelType * type) { DatabusData * dbData = db->data; DatabusInfoData * infoData = dbData->localInfo->data; @@ -1473,7 +1202,7 @@ McxStatus DatabusAddRTFactorChannel(Databus * db, const char * id, const char * unit, const void * reference, - ChannelType type) { + ChannelType * type) { DatabusData * dbData = db->data; DatabusInfoData * infoData = dbData->rtfactorInfo->data; @@ -1565,143 +1294,61 @@ ChannelInfo * DatabusGetLocalChannelInfo(Databus * db, size_t channel) { return (ChannelInfo *) data->infos->At(data->infos, channel); } -ChannelInfo * DatabusGetRTFactorChannelInfo(Databus * db, size_t channel) { - DatabusInfoData * data = db->data->rtfactorInfo->data; - - if (channel >= data->infos->Size(data->infos)) { - mcx_log(LOG_ERROR, "Ports: Get rtfactor-info: Unknown port %d", channel); - return NULL; - } - - return (ChannelInfo *) data->infos->At(data->infos, channel); -} - -VectorChannelInfo * DatabusGetInVectorChannelInfo(Databus * db, size_t channel) { - DatabusInfo * inInfo = NULL; - if (!db) { - mcx_log(LOG_ERROR, "Ports: Get in-info: Invalid structure"); - return NULL; - } - - inInfo = DatabusGetInInfo(db); - - return DatabusInfoGetVectorChannelInfo(inInfo, channel); -} - -VectorChannelInfo * DatabusGetOutVectorChannelInfo(Databus * db, size_t channel) { - DatabusInfo * outInfo = NULL; - if (!db) { - mcx_log(LOG_ERROR, "Ports: Get out-info: Invalid structure"); - return NULL; - } - - outInfo = DatabusGetOutInfo(db); - - return DatabusInfoGetVectorChannelInfo(outInfo, channel); -} - -int DatabusChannelInIsValid(Databus * db, size_t channel) { - Channel * in = NULL; - - if (!db) { - return FALSE; - } - - in = (Channel *) DatabusGetInChannel(db, channel); - if (!in) { - return FALSE; - } - - return in->IsValid(in); -} - -int DatabusChannelInIsConnected(struct Databus * db, size_t channel) { - Channel * in = NULL; - - if (!db) { - return FALSE; - } - - in = (Channel *) DatabusGetInChannel(db, channel); - if (!in) { - return FALSE; - } - - return in->IsConnected(in); -} - -int DatabusChannelOutIsValid(Databus * db, size_t channel) { - Channel * out = NULL; - - if (!db) { - return FALSE; - } - - out = (Channel *) DatabusGetOutChannel(db, channel); - if (!out) { - return FALSE; - } - - return out->IsValid(out); -} - -int DatabusChannelLocalIsValid(Databus * db, size_t channel) { - Channel * local = NULL; +McxStatus DatabusCollectModeSwitchData(Databus * db) { + Vector * infos = db->data->outInfo->data->infos; + size_t size = infos->Size(infos); + size_t i = 0, j = 0, idx = 0; + db->modeSwitchDataSize = 0; - if (!db) { - return FALSE; + // determine cache size + for (i = 0; i < size; i++) { + ChannelOut * out = db->data->out[i]; + ConnectionList * conns = out->GetConnections(out); + db->modeSwitchDataSize += conns->numConnections; } - local = (Channel *) DatabusGetLocalChannel(db, channel); - if (!local) { - return FALSE; + // allocate cache + db->modeSwitchData = (ModeSwitchData *)mcx_calloc(db->modeSwitchDataSize, sizeof(ModeSwitchData)); + if (!db->modeSwitchData) { + return RETURN_ERROR; } - return local->IsValid(local); -} - -int DatabusChannelRTFactorIsValid(Databus * db, size_t channel) { - Channel * rtfactor = NULL; + // fill up the cache + for (i = 0, idx = 0; i < size; i++) { + ChannelOut * out = db->data->out[i]; + ConnectionList * conns = out->GetConnections(out); + size_t connSize = conns->numConnections; - if (!db) { - return FALSE; - } + for (j = 0; j < connSize; j++, idx++) { + Connection * connection = conns->connections[j]; + ConnectionInfo * info = connection->GetInfo(connection); + Component * target = info->targetComponent; + Component * source = info->sourceComponent; + double targetTimeStepSize = target->GetTimeStep(target); + double sourceTimeStepSize = source->GetTimeStep(source); - rtfactor = (Channel *) DatabusGetRTFactorChannel(db, channel); - if (!rtfactor) { - return FALSE; + db->modeSwitchData[idx].connection = connection; + db->modeSwitchData[idx].sourceTimeStepSize = sourceTimeStepSize; + db->modeSwitchData[idx].targetTimeStepSize = targetTimeStepSize; + } } - return rtfactor->IsValid(rtfactor); + return RETURN_OK; } McxStatus DatabusEnterCouplingStepMode(Databus * db, double timeStepSize) { size_t i = 0; - size_t j = 0; - McxStatus retVal = RETURN_OK; - ObjectContainer * infos = db->data->outInfo->data->infos; - size_t size = infos->Size(infos); - - for (i = 0; i < size; i++) { - ChannelOut * out = db->data->out[i]; - ObjectContainer * conns = out->GetConnections(out); - - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); - ConnectionInfo * info = connection->GetInfo(connection); - Component * target = info->GetTargetComponent(info); - Component * source = info->GetSourceComponent(info); - double targetTimeStepSize = target->GetTimeStep(target); - double sourceTimeStepSize = source->GetTimeStep(source); - retVal = connection->EnterCouplingStepMode(connection, timeStepSize, sourceTimeStepSize, targetTimeStepSize); - if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); - mcx_log(LOG_ERROR, "Ports: Cannot enter coupling step mode of connection %s", buffer); - mcx_free(buffer); - return RETURN_ERROR; - } + for (i = 0; i < db->modeSwitchDataSize; i++) { + ModeSwitchData data = db->modeSwitchData[i]; + retVal = data.connection->EnterCouplingStepMode(data.connection, timeStepSize, data.sourceTimeStepSize, data.targetTimeStepSize); + if (RETURN_OK != retVal) { + ConnectionInfo * info = data.connection->GetInfo(data.connection); + char * buffer = ConnectionInfoConnectionString(info); + mcx_log(LOG_ERROR, "Ports: Cannot enter coupling step mode of connection %s", buffer); + mcx_free(buffer); + return RETURN_ERROR; } } @@ -1710,28 +1357,17 @@ McxStatus DatabusEnterCouplingStepMode(Databus * db, double timeStepSize) { McxStatus DatabusEnterCommunicationMode(Databus * db, double time) { size_t i = 0; - size_t j = 0; - McxStatus retVal = RETURN_OK; - ObjectContainer * infos = db->data->outInfo->data->infos; - size_t size = infos->Size(infos); - - for (i = 0; i < size; i++) { - ChannelOut * out = db->data->out[i]; - ObjectContainer * conns = out->GetConnections(out); - - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); - ConnectionInfo * info = connection->GetInfo(connection); - - retVal = connection->EnterCommunicationMode(connection, time); - if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); - mcx_log(LOG_ERROR, "Ports: Cannot enter communication mode of connection %s", buffer); - mcx_free(buffer); - return RETURN_ERROR; - } + for (i = 0; i < db->modeSwitchDataSize; i++) { + ModeSwitchData data = db->modeSwitchData[i]; + retVal = data.connection->EnterCommunicationMode(data.connection, time); + if (RETURN_OK != retVal) { + ConnectionInfo * info = data.connection->GetInfo(data.connection); + char * buffer = ConnectionInfoConnectionString(info); + mcx_log(LOG_ERROR, "Ports: Cannot enter communication mode of connection %s", buffer); + mcx_free(buffer); + return RETURN_ERROR; } } @@ -1739,13 +1375,15 @@ McxStatus DatabusEnterCommunicationMode(Databus * db, double time) { } /* The container connections may only contain connections outgoing from this db */ -McxStatus DatabusEnterCommunicationModeForConnections(Databus * db, ObjectContainer * connections, double time) { +McxStatus DatabusEnterCommunicationModeForConnections(Databus * db, ObjectList * connections, double time) { size_t i = 0; - for (i = 0; i < connections->Size(connections); i++) { + size_t connSize = connections->Size(connections); + + for (i = 0; i < connSize; i++) { Connection * connection = (Connection *) connections->At(connections, i); ConnectionInfo * info = connection->GetInfo(connection); - Component * comp = info->GetSourceComponent(info); + Component * comp = info->sourceComponent; Databus * connDb = comp->GetDatabus(comp); McxStatus retVal = RETURN_OK; @@ -1753,7 +1391,7 @@ McxStatus DatabusEnterCommunicationModeForConnections(Databus * db, ObjectContai if (db == connDb) { retVal = connection->EnterCommunicationMode(connection, time); if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_ERROR, "Ports: Cannot enter communication mode of connection %s", buffer); mcx_free(buffer); return RETURN_ERROR; diff --git a/src/core/Databus.h b/src/core/Databus.h index b392150..7e0df44 100644 --- a/src/core/Databus.h +++ b/src/core/Databus.h @@ -18,7 +18,6 @@ #include "core/channels/Channel.h" #include "core/connections/Connection.h" #include "core/Component.h" -#include "core/channels/VectorChannelInfo.h" #include "reader/model/ports/PortsInput.h" #ifdef __cplusplus @@ -70,6 +69,9 @@ size_t DatabusGetInChannelsNum(struct Databus * db); */ size_t DatabusGetLocalChannelsNum(struct Databus * db); +size_t DatabusGetInChannelsElemNum(Databus * db); +size_t DatabusGetOutChannelsElemNum(Databus * db); + /** * \return The number of rtfactor channels of \a db or -1 if \a db is not initialized * correctly. @@ -86,13 +88,13 @@ size_t DatabusGetRTFactorChannelsNum(struct Databus * db); McxStatus DatabusSetOutReference(struct Databus * db, size_t channel, const void * reference, - ChannelType type); + ChannelType * type); McxStatus DatabusSetOutReferenceFunction(struct Databus * db, size_t channel, const void * reference, - ChannelType type); + ChannelType * type); /** * Connects a variable of type \a type at \a reference to the in channel \a channel @@ -101,7 +103,7 @@ McxStatus DatabusSetOutReferenceFunction(struct Databus * db, * * \return \c RETURN_OK on success, or \c RETURN_ERROR otherwise. */ -McxStatus DatabusSetInReference(struct Databus * db, size_t channel, void * reference, ChannelType type); +McxStatus DatabusSetInReference(struct Databus * db, size_t channel, void * reference, ChannelType * type); /** * Adds a local channel of type \a type at \a reference to the databus \a db. @@ -111,7 +113,7 @@ McxStatus DatabusAddLocalChannel(Databus * db, const char * id, const char * unit, const void * reference, - ChannelType type); + ChannelType * type); /** * Adds a rtfactor channel of type \a type at \a reference to the databus \a db. @@ -121,27 +123,7 @@ McxStatus DatabusAddRTFactorChannel(Databus * db, const char * id, const char * unit, const void * reference, - ChannelType type); - -/* vector channel functions */ - -VectorChannelInfo * DatabusGetInVectorChannelInfo(Databus * db, size_t channel); -VectorChannelInfo * DatabusGetOutVectorChannelInfo(Databus * db, size_t channel); - -size_t DatabusGetInVectorChannelsNum(Databus * db); - -size_t DatabusGetOutVectorChannelsNum(Databus * db); - -McxStatus DatabusSetOutRefVector(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, const void * reference, ChannelType type); - -McxStatus DatabusSetOutRefVectorChannel(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, ChannelValue * value); - -McxStatus DatabusSetInRefVector(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, void * reference, ChannelType type); -McxStatus DatabusSetInRefVectorChannel(Databus * db, size_t channel, - size_t startIdx, size_t endIdx, ChannelValue * value); + ChannelType * type); /** @@ -168,37 +150,6 @@ struct ChannelInfo * DatabusGetInChannelInfo (struct Databus * db, size_t channe */ struct ChannelInfo * DatabusGetOutChannelInfo(struct Databus * db, size_t channel); -/** - * \return \c TRUE if the in channel \a channel in \a db is connected or - * provides a default value, and \c FALSE if it is not connected or \a db or \a - * channel are invalid. - */ -int DatabusChannelInIsValid(struct Databus * db, size_t channel); - -/** - * \return \c TRUE if the in channel \a channel in \a db is connected or - * and \c FALSE otherwise - */ -int DatabusChannelInIsConnected(struct Databus * db, size_t channel); - -/** - * \return \c TRUE if the out channel \a channel in \a db is connected, and \c - * FALSE if it is not connected or \a db or \a channel are invalid. - */ -int DatabusChannelOutIsValid(struct Databus * db, size_t channel); - -/** - * \return \c TRUE if the local channel \a channel in \a db has a reference, and \c - * FALSE if it has no reference or \a db or \a channel are invalid. - */ -int DatabusChannelLocalIsValid(struct Databus * db, size_t channel); - -/** - * \return \c TRUE if the rtfactor channel \a channel in \a db has a reference, and \c - * FALSE if it has no reference or \a db or \a channel are invalid. - */ -int DatabusChannelRTFactorIsValid(struct Databus * db, size_t channel); - /** private interface for Component **/ @@ -246,10 +197,14 @@ struct Connection * DatabusCreateConnection(struct Databus * db, struct Connecti * \return \c RETURN_OK on success, or \c RETURN_ERROR otherwise. */ McxStatus DatabusTriggerInConnections(struct Databus * db, TimeInterval * consumerTime); +McxStatus DatabusTriggerConnectedInConnections(struct Databus * db, TimeInterval * consumerTime); + +McxStatus DatabusUpdateInConnected(Databus * db); +McxStatus DatabusCollectModeSwitchData(Databus * db); McxStatus DatabusEnterCouplingStepMode(struct Databus * db, double timeStepSize); McxStatus DatabusEnterCommunicationMode(struct Databus * db, double time); -McxStatus DatabusEnterCommunicationModeForConnections(Databus * db, ObjectContainer * connections, double time); +McxStatus DatabusEnterCommunicationModeForConnections(Databus * db, ObjectList * connections, double time); /* private interface for Component, Model, Task */ @@ -288,6 +243,9 @@ size_t DatabusInfoGetNumWriteChannels(DatabusInfo * dbInfo); /* internal */ +int DatabusInChannelsDefined(Databus * db); +int DatabusOutChannelsDefined(Databus * db); + /** * Accessor function for the \a i-th in channel of \a db. * @@ -318,13 +276,21 @@ struct Channel * DatabusGetRTFactorChannel(Databus * db, size_t i); extern const struct ObjectClass _Databus; + +typedef struct { + Connection * connection; + double sourceTimeStepSize; + double targetTimeStepSize; +} ModeSwitchData; + typedef struct Databus { Object _; // base class struct DatabusData * data; -} Databus; -char * CreateIndexedName(const char * name, unsigned i); + ModeSwitchData * modeSwitchData; + size_t modeSwitchDataSize; +} Databus; #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/Databus_impl.h b/src/core/Databus_impl.h index 40ef811..8799e8c 100644 --- a/src/core/Databus_impl.h +++ b/src/core/Databus_impl.h @@ -11,6 +11,8 @@ #ifndef MCX_CORE_DATABUS_IMPL_H #define MCX_CORE_DATABUS_IMPL_H +#include "objects/Vector.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ @@ -27,8 +29,7 @@ extern const struct ObjectClass _DatabusInfoData; typedef struct DatabusInfoData { Object _; // base class - ObjectContainer * infos; - ObjectContainer * origInfos; + Vector * infos; } DatabusInfoData; @@ -51,6 +52,8 @@ typedef struct DatabusData { Object _; // base class struct ChannelIn ** in; /**< input channels */ + struct ChannelIn ** inConnected; /**< connected input channels */ + size_t numInConnected; struct ChannelOut ** out; /**< output channels */ struct ChannelLocal ** local; /**< local (non-connectable) channels */ struct ChannelLocal ** rtfactor; /**< rtfactor (non-connectable) channels */ diff --git a/src/core/Dependency.h b/src/core/Dependency.h index 861cca9..4a04a03 100644 --- a/src/core/Dependency.h +++ b/src/core/Dependency.h @@ -24,7 +24,7 @@ typedef enum DependencyDef { DEP_FIXED = 3, } Dependency; -struct Dependencies; +typedef struct Dependencies Dependencies; struct Dependencies * DependenciesCreate(size_t numIn, size_t numOut); diff --git a/src/core/Model.c b/src/core/Model.c index 16d1a92..e89be67 100644 --- a/src/core/Model.c +++ b/src/core/Model.c @@ -14,6 +14,7 @@ #include "steptypes/StepType.h" #include "tarjan.h" #include "components/ComponentFactory.h" +#include "components/comp_constant.h" #include "reader/model/ModelInput.h" #include "reader/model/components/ComponentsInput.h" #include "reader/model/components/ComponentInput.h" @@ -23,8 +24,9 @@ #include "core/Databus.h" #include "core/channels/Channel.h" +#include "core/channels/ChannelValueReference.h" +#include "core/channels/ChannelInfo.h" #include "core/connections/Connection.h" -#include "core/connections/ConnectionInfo_impl.h" #include "core/connections/FilteredConnection.h" #include "core/SubModel.h" @@ -42,43 +44,44 @@ extern "C" { static ChannelInfo * GetTargetChannelInfo(ConnectionInfo * info) { - Component * trg = info->GetTargetComponent(info); + Component * trg = info->targetComponent; struct Databus * trgDb = trg->GetDatabus(trg); - int trgId = info->GetTargetChannelID(info); + int trgId = info->targetChannel; return DatabusGetInChannelInfo(trgDb, trgId); } static ChannelInfo * GetSourceChannelInfo(ConnectionInfo * info) { - Component * src = info->GetSourceComponent(info); + Component * src = info->sourceComponent; struct Databus * srcDb = src->GetDatabus(src); - int srcId = info->GetSourceChannelID(info); + int srcId = info->sourceChannel; return DatabusGetOutChannelInfo(srcDb, srcId); } -static int ConnInfoWithSrc(Object * obj, void * ctx) { +static int ConnInfoWithSrc(void * elem, void * arg) { /* * TRUE if obj (ConnectionInfo) has ctx as its source ChannelInfo */ - ConnectionInfo * info = (ConnectionInfo *)obj; + ChannelInfo * chInfo = (ChannelInfo *) arg; + ConnectionInfo * info = *((ConnectionInfo **) elem); ChannelInfo * srcInfo = GetSourceChannelInfo(info); - return srcInfo == (ChannelInfo *)ctx; + return srcInfo == chInfo; } -static int IsBinaryConn(Object * obj) { +static int IsBinaryConn(void * elem, void * args) { /* * TRUE if both source and target channel infos of obj (ConnectionInfo) are binary */ - ConnectionInfo * info = (ConnectionInfo *)obj; + ConnectionInfo * info = (ConnectionInfo *) elem; ChannelInfo * srcInfo = GetSourceChannelInfo(info); ChannelInfo * trgInfo = GetTargetChannelInfo(info); - return srcInfo->IsBinary(srcInfo) && trgInfo->IsBinary(trgInfo); + return ChannelInfoIsBinary(srcInfo) && ChannelInfoIsBinary(trgInfo); } -static int CanMakeChannelsBinReferences(ObjectContainer * connInfos, Task * task) { +static int CanMakeChannelsBinReferences(Vector * connInfos, Task * task) { /* * Checks whether all binary connections in connInfos satisfy the condition * to use CHANNEL_BINARY_REFERENCE instead of CHANNEL_BINARY. @@ -93,10 +96,10 @@ static int CanMakeChannelsBinReferences(ObjectContainer * connInfos, Task * task size_t num = connInfos->Size(connInfos); for (i = 0; i < num; i++) { - ConnectionInfo * info = (ConnectionInfo *)connInfos->At(connInfos, i); + ConnectionInfo * info = *(ConnectionInfo **)connInfos->At(connInfos, i); - Component * trg = info->GetTargetComponent(info); - Component * src = info->GetSourceComponent(info); + Component * trg = info->targetComponent; + Component * src = info->sourceComponent; ChannelInfo * trgInfo = GetTargetChannelInfo(info); ChannelInfo * srcInfo = GetSourceChannelInfo(info); @@ -114,7 +117,7 @@ static int CanMakeChannelsBinReferences(ObjectContainer * connInfos, Task * task return TRUE; } -static void UpdateBinaryChannelTypes(ObjectContainer * connInfos, Task * task) { +static void UpdateBinaryChannelTypes(Vector * connInfos, Task * task) { /* * Updates the channel types of binary connections in connInfos according to the * result of `CanMakeChannelsBinReferences` (see function for more info) @@ -124,35 +127,185 @@ static void UpdateBinaryChannelTypes(ObjectContainer * connInfos, Task * task) { int canMakeReference = CanMakeChannelsBinReferences(connInfos, task); for (i = 0; i < connInfos->Size(connInfos); i++) { - ConnectionInfo * info = (ConnectionInfo *)connInfos->At(connInfos, i); + ConnectionInfo * info = *(ConnectionInfo **)connInfos->At(connInfos, i); ChannelInfo * srcInfo = GetSourceChannelInfo(info); ChannelInfo * trgInfo = GetTargetChannelInfo(info); if (canMakeReference) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, "Fast binary channel requirements fulfilled for connection %s", buffer); mcx_free(buffer); - trgInfo->type = CHANNEL_BINARY_REFERENCE; - srcInfo->type = CHANNEL_BINARY_REFERENCE; + trgInfo->type = &ChannelTypeBinaryReference; + srcInfo->type = &ChannelTypeBinaryReference; } else { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, "Using binary channels for connection %s", buffer); mcx_free(buffer); - trgInfo->type = CHANNEL_BINARY; - srcInfo->type = CHANNEL_BINARY; + trgInfo->type = &ChannelTypeBinary; + srcInfo->type = &ChannelTypeBinary; } } } +/** + * Remove connections to Constant elements from the model + * For each such connection, the value of the Constant shall be taken + * and set as the default value of the corresponding input. + * Necessary value/type conversions are done as well. + */ +static McxStatus ModelPreprocessConstConnections(Model * model) { + Vector * conns = model->connections; + Vector * filteredConns = NULL; + + size_t i = 0; + McxStatus retVal = RETURN_OK; + + filteredConns = (Vector*)object_create(Vector); + if (!filteredConns) { + mcx_log(LOG_ERROR, "Not enough memory to filter out constant connections"); + return RETURN_ERROR; + } + filteredConns->Setup(filteredConns, sizeof(ConnectionInfo), ConnectionInfoInit, ConnectionInfoSetFrom, DestroyConnectionInfo); + + for (i = 0; i < conns->Size(conns); i++) { + ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, i); + ChannelValue * src = NULL; + + Component * srcComp = info->sourceComponent; + CompConstant * srcCompConst = NULL; + Databus * srcDb = srcComp->GetDatabus(srcComp); + ChannelInfo * srcChannelInfo = DatabusGetOutChannelInfo(srcDb, info->sourceChannel); + ChannelDimension * srcDim = NULL; + + Component * trgComp = info->targetComponent; + Databus * trgDb = trgComp->GetDatabus(trgComp); + ChannelInfo * trgChannelInfo = DatabusGetInChannelInfo(trgDb, info->targetChannel); + ChannelDimension * trgDim = NULL; + + // if not a const conn, add to the filtered conns + if (0 != strcmp(compConstantTypeString, srcComp->GetType(srcComp))) { + filteredConns->PushBack(filteredConns, info); + continue; + } + + if (!ChannelDimensionEq(trgChannelInfo->dimension, info->targetDimension)) { + filteredConns->PushBack(filteredConns, info); + continue; + } + + // else kick the connection and update the channel default value + srcCompConst = (CompConstant *) srcComp; + src = (ChannelValue *) mcx_calloc(1, sizeof(ChannelValue)); + + if (!src) { + mcx_log(LOG_ERROR, "ModelPreprocessConstConnections: Not enough memory"); + goto cleanup_1; + } + + ChannelValueInit(src, ChannelTypeClone(srcChannelInfo->type)); + retVal = ChannelValueSet(src, srcCompConst->GetValue(srcCompConst, info->sourceChannel)); + if (retVal == RETURN_ERROR) { + goto cleanup_1; + } + + if (!trgChannelInfo->defaultValue) { + trgChannelInfo->defaultValue = (ChannelValue *) mcx_calloc(1, sizeof(ChannelValue)); + ChannelValueInit(trgChannelInfo->defaultValue, ChannelTypeClone(trgChannelInfo->type)); + } + + // prepare slice dimensions + srcDim = CloneChannelDimension(info->sourceDimension); + if (info->sourceDimension && !srcDim) { + mcx_log(LOG_ERROR, "ModelPreprocessConstConnections: Source dimension slice allocation failed"); + goto cleanup_1; + } + + retVal = ChannelDimensionAlignIndicesWithZero(srcDim, srcChannelInfo->dimension); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ModelPreprocessConstConnections: Source dimension normalization failed"); + goto cleanup_1; + } + + trgDim = CloneChannelDimension(info->targetDimension); + if (info->targetDimension && !trgDim) { + mcx_log(LOG_ERROR, "ModelPreprocessConstConnections: Target dimension slice allocation failed"); + goto cleanup_1; + } + + retVal = ChannelDimensionAlignIndicesWithZero(trgDim, trgChannelInfo->dimension); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ModelPreprocessConstConnections: Target dimension normalization failed"); + goto cleanup_1; + } + + // out channel range and linear conversions + retVal = ConvertRange(srcChannelInfo->min, srcChannelInfo->max, src, srcDim); + if (retVal == RETURN_ERROR) { + goto cleanup_1; + } + + retVal = ConvertLinear(srcChannelInfo->scale, srcChannelInfo->offset, src, srcDim); + if (retVal == RETURN_ERROR) { + goto cleanup_1; + } + + // type conversion + retVal = ConvertType(trgChannelInfo->defaultValue, trgDim, src, srcDim); + if (retVal == RETURN_ERROR) { + goto cleanup_1; + } + + // unit conversion + retVal = ConvertUnit(srcChannelInfo->unitString, trgChannelInfo->unitString, trgChannelInfo->defaultValue, trgDim); + if (retVal == RETURN_ERROR) { + goto cleanup_1; + } + + object_destroy(srcDim); + object_destroy(trgDim); + + continue; + +cleanup_1: + if (src) { + ChannelValueDestructor(src); + mcx_free(src); + } + + object_destroy(srcDim); + object_destroy(trgDim); + + retVal = RETURN_ERROR; + goto cleanup; + } + +cleanup: + if (retVal == RETURN_ERROR) { + object_destroy(filteredConns); + + return RETURN_ERROR; + } + + object_destroy(conns); + model->connections = filteredConns; + + return RETURN_OK; +} + +static int ConnInfoContained(void * elem, void * arg) { + ConnectionInfo * info = *(ConnectionInfo **) elem; + return info == (ConnectionInfo *) arg; +} + static McxStatus ModelPreprocessBinaryConnections(Model * model) { - ObjectContainer * conns = model->connections; + Vector * conns = model->connections; size_t connsSize = conns->Size(conns); - ObjectContainer * binConnInfos = NULL; - ObjectContainer * processedConnInfos = NULL; + Vector * binConnInfos = NULL; + Vector * processedConnInfos = NULL; size_t i = 0; @@ -164,30 +317,32 @@ static McxStatus ModelPreprocessBinaryConnections(Model * model) { return RETURN_OK; } - // filter all binary connection - binConnInfos = conns->Filter(conns, IsBinaryConn); + binConnInfos = conns->FilterRef(conns, IsBinaryConn, NULL); if (!binConnInfos) { mcx_log(LOG_ERROR, "Not enough memory for binary connections"); retVal = RETURN_ERROR; goto cleanup; } - processedConnInfos = (ObjectContainer *)object_create(ObjectContainer); + processedConnInfos = (Vector*)object_create(Vector); if (!processedConnInfos) { mcx_log(LOG_ERROR, "Not enough memory for processed binary connections"); retVal = RETURN_ERROR; goto cleanup; } + processedConnInfos->Setup(processedConnInfos, sizeof(ConnectionInfo*), NULL, NULL, NULL); + for (i = 0; i < binConnInfos->Size(binConnInfos); i++) { - ConnectionInfo * info = (ConnectionInfo *)binConnInfos->At(binConnInfos, i); + ConnectionInfo * info = *(ConnectionInfo **)binConnInfos->At(binConnInfos, i); + ChannelInfo * srcInfo = GetSourceChannelInfo(info); + Vector* connInfos = NULL; - if (processedConnInfos->Contains(processedConnInfos, (Object *)info)) { + if (processedConnInfos->FindIdx(processedConnInfos, ConnInfoContained, info) != SIZE_T_ERROR) { continue; } - ChannelInfo * srcInfo = GetSourceChannelInfo(info); - ObjectContainer * connInfos = binConnInfos->FilterCtx(binConnInfos, ConnInfoWithSrc, srcInfo); + connInfos = binConnInfos->Filter(binConnInfos, ConnInfoWithSrc, srcInfo); if (!connInfos) { mcx_log(LOG_ERROR, "Not enough memory for filtered binary connections"); retVal = RETURN_ERROR; @@ -213,7 +368,7 @@ static McxStatus ModelPreprocessBinaryConnections(Model * model) { } static int ComponentIsBoundaryCondition(const Component * comp) { - if (0 == strcmp("CONSTANT", comp->GetType(comp)) + if (0 == strcmp(compConstantTypeString, comp->GetType(comp)) ) { return TRUE; @@ -221,18 +376,18 @@ static int ComponentIsBoundaryCondition(const Component * comp) { return FALSE; } -static ObjectContainer * GetAllSourceConnInfos(Model * model, Component * comp) { - ObjectContainer * conns = model->connections; - ObjectContainer * comps = model->components; +static Vector * GetAllSourceConnInfoRefs(Model * model, Component * comp) { + Vector * conns = model->connections; size_t numConnections = conns->Size(conns); - ObjectContainer * sources = (ObjectContainer *) object_create(ObjectContainer); + Vector * sources = (Vector*) object_create(Vector); size_t i = 0; + sources->Setup(sources, sizeof(ConnectionInfo*), NULL, NULL, NULL); for (i = 0; i < numConnections; i++) { ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, i); - Component * target = info->GetTargetComponent(info); + Component * target = info->targetComponent; if (target == comp) { - sources->PushBack(sources, (Object *) info); + sources->PushBack(sources, &info); } } @@ -240,17 +395,16 @@ static ObjectContainer * GetAllSourceConnInfos(Model * model, Component * comp) } static ObjectContainer * GetAllSourceElements(Model * model, Component * comp) { - ObjectContainer * conns = model->connections; - ObjectContainer * comps = model->components; + Vector * conns = model->connections; size_t numConnections = conns->Size(conns); ObjectContainer * sources = (ObjectContainer *) object_create(ObjectContainer); size_t i = 0; for (i = 0; i < numConnections; i++) { ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, i); - Component * target = info->GetTargetComponent(info); + Component * target = info->targetComponent; if (target == comp) { - Component * source = info->GetSourceComponent(info); + Component * source = info->sourceComponent; if (!sources->Contains(sources, (Object *) source)) { sources->PushBack(sources, (Object *) source); } @@ -263,6 +417,12 @@ static ObjectContainer * GetAllSourceElements(Model * model, Component * comp) { static McxStatus ModelPreprocess(Model * model) { McxStatus retVal = RETURN_OK; + retVal = ModelPreprocessConstConnections(model); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Preprocessing const connections failed"); + return RETURN_ERROR; + } + retVal = ModelPreprocessBinaryConnections(model); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Model: Preprocessing binary connections failed"); @@ -287,13 +447,13 @@ static McxStatus ModelInsertAllFilters(Model * model) { for (j = 0; j < numOutChannels; j++) { ChannelOut * out = DatabusGetOutChannel(db, j); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (k = 0; k < conns->Size(conns); k++) { - Connection * connection = (Connection *) conns->At(conns, k); + for (k = 0; k < conns->numConnections; k++) { + Connection * connection = conns->connections[k]; ConnectionInfo * info = connection->GetInfo(connection); if (connection->AddFilter) { - char * connStr = info->ConnectionString(info); + char * connStr = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, " Adding filter to connection: %s", connStr); if (connStr) { mcx_free(connStr); @@ -355,6 +515,65 @@ static McxStatus ModelCreateInitSubModel(Model * model) { return retVal; } +McxStatus ModelInitInConnectedList(ObjectContainer * comps) { + size_t i = 0; + + for (i = 0; i < comps->Size(comps); i++) { + Component * comp = (Component *)comps->At(comps, i); + McxStatus retVal = DatabusUpdateInConnected(comp->GetDatabus(comp)); + if (RETURN_ERROR == retVal) { + ComponentLog(comp, LOG_ERROR, "Could not initialize the In-Connection list"); + return RETURN_ERROR; + } + } + return RETURN_OK; +} + +static McxStatus ModelSignalConnectionsDone(ObjectContainer * comps) { + size_t i = 0; + + for (i = 0; i < comps->Size(comps); i++) { + Component * comp = (Component *)comps->At(comps, i); + if (NULL != comp->OnConnectionsDone) { + if (RETURN_ERROR == comp->OnConnectionsDone(comp)) { + ComponentLog(comp, LOG_ERROR, "OnConnectionsDone callback failed"); + return RETURN_ERROR; + } + } + } + + return RETURN_OK; +} + +int ComponentsHaveVectorChannels(ObjectContainer * components) { + size_t numComps = components->Size(components); + size_t i = 0; + + for (i = 0; i < numComps; i++) { + Component * comp = (Component *) components->At(components, i); + Databus * db = comp->GetDatabus(comp); + size_t numIns = DatabusGetInChannelsNum(db); + size_t numOuts = DatabusGetOutChannelsNum(db); + size_t j = 0; + + for (j = 0; j < numIns; j++) { + ChannelInfo * info = DatabusGetInChannelInfo(db, j); + if (ChannelTypeIsArray(info->type)) { + return TRUE; + } + } + + for (j = 0; j < numOuts; j++) { + ChannelInfo* info = DatabusGetOutChannelInfo(db, j); + if (ChannelTypeIsArray(info->type)) { + return TRUE; + } + } + } + + return FALSE; +} + static McxStatus ModelConnectionsDone(Model * model) { OrderedNodes * orderedNodes = NULL; McxStatus retVal = RETURN_OK; @@ -365,10 +584,30 @@ static McxStatus ModelConnectionsDone(Model * model) { goto cleanup; } + retVal = ModelInitInConnectedList(model->components); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: In-Connection lists could not be initialized"); + goto cleanup; + } + + retVal = ModelSignalConnectionsDone(model->components); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Components could not be notified about connection completion"); + goto cleanup; + } + // determine initialization evaluation order if (model->config->cosimInitEnabled) { + // separate triggering of array elements is not supported at the moment + // therefore some models with array ports might not work + if (ComponentsHaveVectorChannels(model->components)) { + mcx_log(LOG_ERROR, "Co-Simulation initialization: Components with vector ports are not supported"); + return RETURN_ERROR; + } + retVal = ModelCreateInitSubModel(model); - if (retVal != RETURN_OK) { + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: InitSubModel could not be created"); goto cleanup; } } @@ -435,6 +674,11 @@ static McxStatus ModelConnectionsDone(Model * model) { goto cleanup; } + retVal = model->subModel->LoopComponents(model->subModel, CompCollectModeSwitchData, NULL); + if (RETURN_ERROR == retVal) { + return retVal; + } + cleanup: if (orderedNodes) { tarjan_ordered_nodes_cleanup(orderedNodes); @@ -456,10 +700,10 @@ static Connection * ModelGetConnectionFromInfo(Model * model, ConnectionInfo * i for (j = 0; j < numOutChannels; j++) { ChannelOut * out = DatabusGetOutChannel(db, j); - ObjectContainer * conns = out->GetConnections(out); + ConnectionList * conns = out->GetConnections(out); - for (k = 0; k < conns->Size(conns); k++) { - Connection * connection = (Connection *) conns->At(conns, k); + for (k = 0; k < conns->numConnections; k++) { + Connection * connection = conns->connections[k]; if (connection->GetInfo(connection) == info) { return connection; } @@ -507,7 +751,6 @@ static void ModelDestructor(void * self) { object_destroy(model->initialSubModelGenerator); object_destroy(model->subModel); object_destroy(model->initialSubModel); - } static McxStatus ModelReadComponents(void * self, ComponentsInput * input) { @@ -549,13 +792,13 @@ static McxStatus ModelReadComponents(void * self, ComponentsInput * input) { } } - mcx_log(LOG_INFO, "Read %d elements", numComps); + mcx_log(LOG_INFO, "Read %zu elements", numComps); mcx_log(LOG_INFO, " "); return RETURN_OK; } -McxStatus ReadConnections(ObjectContainer * connections, +McxStatus ReadConnections(Vector * connections, ConnectionsInput * connectionsInput, ObjectContainer * components, Component * sourceComp, @@ -566,7 +809,7 @@ McxStatus ReadConnections(ObjectContainer * connections, // loop over all connections here for (i = 0; i < connInputs->Size(connInputs); i++) { ConnectionInput * connInput = (ConnectionInput*)connInputs->At(connInputs, i); - ObjectContainer * conns = NULL; + Vector * conns = NULL; size_t connsSize = 0; size_t j = 0; @@ -581,7 +824,7 @@ McxStatus ReadConnections(ObjectContainer * connections, ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, j); char * connStr = NULL; - connStr = info->ConnectionString(info); + connStr = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, " Connection: %s", connStr); mcx_free(connStr); } @@ -590,7 +833,7 @@ McxStatus ReadConnections(ObjectContainer * connections, object_destroy(conns); } - mcx_log(LOG_INFO, "Read %d connections", connections->Size(connections)); + mcx_log(LOG_INFO, "Read %zu connections", connections->Size(connections)); mcx_log(LOG_INFO, " "); return RETURN_OK; @@ -609,13 +852,10 @@ static McxStatus ModelReadConnections(void * self, ConnectionsInput * input) { } static McxStatus ModelCheckConnectivity(Model * model) { - ObjectContainer * connections = model->connections; - McxStatus retVal = RETURN_OK; - - return CheckConnectivity(connections); + return CheckConnectivity(model->connections); } -McxStatus MakeConnections(ObjectContainer * connections, InterExtrapolatingType isInterExtrapolating) { +McxStatus MakeConnections(Vector * connections, InterExtrapolatingType isInterExtrapolating) { ConnectionInfo * info = NULL; McxStatus retVal = RETURN_OK; size_t i = 0; @@ -648,7 +888,7 @@ static McxStatus ModelMakeConnections(Model * model) { retVal = MakeConnections(model->connections, isInterExtrapolating); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Model: Creating connection %d failed", i); + mcx_log(LOG_ERROR, "Model: Creating connection %zu failed", i); return RETURN_ERROR; } mcx_log(LOG_DEBUG, "Creating connections done"); @@ -689,7 +929,7 @@ static McxStatus ModelRead(void * self, ModelInput * input) { static McxStatus ModelDoComponentNameCheck(Component * comp, void * param) { Component * comp2 = (Component *) param; if (! strcmp(comp->GetName(comp), comp2->GetName(comp2)) && (comp != comp2)) { - mcx_log(LOG_ERROR, "Model: Elements %d and %d have the same name", comp->GetID(comp), comp2->GetID(comp2)); + mcx_log(LOG_ERROR, "Model: Elements %zu and %zu have the same name", comp->GetID(comp), comp2->GetID(comp2)); return RETURN_ERROR; } @@ -715,24 +955,21 @@ static McxStatus ModelDoComponentConsistencyChecks(Component * comp, void * para for (i = 0; i < numInChannels; i++) { Channel * channel = (Channel *)DatabusGetInChannel(db, i); - ChannelInfo * info = channel->GetInfo(channel); + ChannelIn * in = (ChannelIn *) channel; + ChannelInfo * info = &channel->info; - if ((info->GetMode(info) == CHANNEL_MANDATORY) - && !channel->IsValid(channel)) { - mcx_log(LOG_ERROR, "Model: %d. inport (%s) of element %s not connected" - , i+1, info->GetName(info), comp->GetName(comp)); + if (info->mode == CHANNEL_MANDATORY && !channel->ProvidesValue(channel)) { + mcx_log(LOG_ERROR, "Model: %zu. inport (%s) of element %s not connected", i+1, ChannelInfoGetName(info), comp->GetName(comp)); return RETURN_ERROR; } } for (i = 0; i < numOutChannels; i++) { Channel * channel = (Channel *)DatabusGetOutChannel(db, i); - ChannelInfo * info = channel->GetInfo(channel); + ChannelInfo * info = &channel->info; - if ((info->GetMode(info) == CHANNEL_MANDATORY) - && !channel->IsValid(channel)) { - mcx_log(LOG_ERROR, "Model: %d. outport (%s) of element %s not connected" - , i+1, info->GetName(info), comp->GetName(comp)); + if (info->mode == CHANNEL_MANDATORY && !channel->ProvidesValue(channel)) { + mcx_log(LOG_ERROR, "Model: %zu. outport (%s) of element %s not connected", i+1, ChannelInfoGetName(info), comp->GetName(comp)); return RETURN_ERROR; } } @@ -743,7 +980,7 @@ static McxStatus ModelDoComponentConsistencyChecks(Component * comp, void * para static McxStatus ModelDoConsistencyChecks(Model * model) { SubModel * subModel = model->subModel; - ObjectContainer * conns = model->connections; + Vector * conns = model->connections; ObjectContainer * comps = model->components; Task * task = model->task; @@ -760,8 +997,7 @@ static McxStatus ModelDoConsistencyChecks(Model * model) { for (i = 0; i < conns->Size(conns); i++) { ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, i); - if ((info->GetDecouplePriority(info) > 0) - || (info->GetDecoupleType(info) != DECOUPLE_DEFAULT)) { + if (info->decouplePriority > 0 || info->decoupleType != DECOUPLE_DEFAULT) { hasDecoupleInfos = 1; } } @@ -1027,6 +1263,38 @@ static McxStatus ModelSetup(void * self) { } mcx_log(LOG_DEBUG, " "); + // Set isFullyConnected status on all channels + size_t i = 0; + size_t j = 0; + Component * comp = NULL; + Databus * db = NULL; + size_t inNum = 0; + size_t outNum = 0; + Channel * channel = NULL; + ObjectContainer * comps = model->components; + for (i = 0; i < comps->Size(comps); i++) { + comp = (Component *)comps->At(comps, i); + db = comp->GetDatabus(comp); + inNum = DatabusGetInChannelsNum(db); + for (j = 0; j < inNum; j++) { + channel = (Channel *) DatabusGetInChannel(db, j); + retVal = channel->SetIsFullyConnected(channel); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Model: Setting IsFullyConnected state for input %s failed", channel->info.name); + return RETURN_ERROR; + } + } + outNum = DatabusGetOutChannelsNum(db); + for (j = 0; j < outNum; j++) { + channel = (Channel *) DatabusGetOutChannel(db, j); + retVal = channel->SetIsFullyConnected(channel); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Model: Setting IsFullyConnected state for output %s failed", channel->info.name); + return RETURN_ERROR; + } + } + } + if (model->config->outputModel) { retVal = ModelPrint(model); if (RETURN_OK != retVal) { @@ -1127,6 +1395,35 @@ static McxStatus CompUpdateInitOutputs(CompAndGroup * compGroup, void * param) { return retVal; } +static McxStatus CompUpdateInAndOutputs(CompAndGroup * compGroup, void * param) { + Component * comp = compGroup->comp; + double startTime = comp->GetTime(comp); + TimeInterval time = { startTime, startTime }; + McxStatus retVal = RETURN_OK; + + retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &time); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Updating inports after initialization loop failed"); + return RETURN_ERROR; + } + + if (comp->UpdateInChannels) { + retVal = comp->UpdateInChannels(comp); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Updating inports failed"); + return RETURN_ERROR; + } + } + + retVal = ComponentUpdateOutChannels(comp, &time); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Updating outports after initialization loop failed"); + return RETURN_ERROR; + } + + return retVal; +} + static McxStatus CompUpdateOutputs(CompAndGroup * compGroup, void * param) { Component * comp = compGroup->comp; const Task * task = (const Task *) param; @@ -1181,6 +1478,17 @@ static McxStatus ModelInitialize(Model * model) { return retVal; } + if (model->config->patchWrongInitBehavior) { + // Additional step for faulty elements which return zeroes as out channel values during initialization. + // This makes sure that after the element exits initialization (CompExitInit), + // the output channels contain good values before they get forwarded to the filters (ModelConnectionsExitInitMode) + retVal = subModel->LoopEvaluationList(subModel, CompUpdateInAndOutputs, (void*)model->task); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Updating element channels failed"); + return RETURN_ERROR; + } + } + retVal = ModelConnectionsExitInitMode(model->components, model->task->params->time); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Model: Exiting initialization mode failed"); @@ -1194,11 +1502,22 @@ static McxStatus ModelInitialize(Model * model) { return RETURN_ERROR; } + { + McxTime rtGlobalSimStart; + mcx_time_get(&rtGlobalSimStart); + + retVal = subModel->LoopComponents(subModel, ComponentBeforeDoSteps, &rtGlobalSimStart); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Model: Initialization of elements failed"); + return retVal; + } + } + return RETURN_OK; } static const char * GetComponentAbbrev(const char * type) { - if (!strcmp(type, "CONSTANT")) { + if (!strcmp(type, compConstantTypeString)) { return "C"; } else if (!strcmp(type, "INTEGRATOR")) { return "INT"; @@ -1238,7 +1557,7 @@ McxStatus PrintComponentGraph(Component * comp, mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; j < GetDependencyNumIn(A); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); @@ -1256,7 +1575,7 @@ McxStatus PrintComponentGraph(Component * comp, mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; j < DatabusGetOutChannelsNum(db); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); @@ -1280,7 +1599,7 @@ McxStatus PrintComponentGraph(Component * comp, } GetDependency(A, i, grp, &dep); if (dep != DEP_INDEPENDENT) { - mcx_os_fprintf(dotFile, "in:in%d -> out:out%d;\n", i, j); + mcx_os_fprintf(dotFile, "in:in%zu -> out:out%zu;\n", i, j); } } } @@ -1298,7 +1617,7 @@ McxStatus PrintComponentGraph(Component * comp, return RETURN_OK; } -McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Component * inComp, Component * outComp, const char * title, const char * filename) { +McxStatus PrintModelGraph(ObjectContainer * comps, Vector * conns, Component * inComp, Component * outComp, const char * title, const char * filename) { size_t i = 0; size_t j = 0; @@ -1322,14 +1641,14 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; (int) j < DatabusGetOutChannelsNum(db); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); } mcx_os_fprintf(dotFile, " \n"); mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, ">] comp%d;\n", comps->Size(comps)); + mcx_os_fprintf(dotFile, ">] comp%zu;\n", comps->Size(comps)); } for (i = 0; i < comps->Size(comps); i++) { @@ -1345,7 +1664,7 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; (int) j < DatabusGetInChannelsNum(db); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); @@ -1359,14 +1678,14 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; (int) j < DatabusGetOutChannelsNum(db); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); } mcx_os_fprintf(dotFile, " \n"); mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, ">] comp%d;\n", c->GetID(c)); + mcx_os_fprintf(dotFile, ">] comp%zu;\n", c->GetID(c)); } if (outComp) { @@ -1381,7 +1700,7 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp mcx_os_fprintf(dotFile, " \n", tableArgs); for (j = 0; (int) j < DatabusGetInChannelsNum(db); j++) { mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, " \n", j, j); + mcx_os_fprintf(dotFile, " \n", j, j); mcx_os_fprintf(dotFile, " \n"); } mcx_os_fprintf(dotFile, "
%d%zu
\n"); @@ -1389,21 +1708,21 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp mcx_os_fprintf(dotFile, " \n"); mcx_os_fprintf(dotFile, " out\n"); mcx_os_fprintf(dotFile, " \n"); - mcx_os_fprintf(dotFile, ">] comp%d;\n", comps->Size(comps) + 1); + mcx_os_fprintf(dotFile, ">] comp%zu;\n", comps->Size(comps) + 1); } mcx_os_fprintf(dotFile, "{\n"); if (inComp && outComp) { - mcx_os_fprintf(dotFile, "comp%d -> comp%d [style=invis];\n", + mcx_os_fprintf(dotFile, "comp%zu -> comp%zu [style=invis];\n", comps->Size(comps), comps->Size(comps) + 1); } for (i = 0; i < conns->Size(conns); i++) { ConnectionInfo * info = (ConnectionInfo *) conns->At(conns, i); - Component * src = info->GetSourceComponent(info); - Component * trg = info->GetTargetComponent(info); + Component * src = info->sourceComponent; + Component * trg = info->targetComponent; size_t srcID = src->GetID(src); size_t trgID = trg->GetID(trg); @@ -1416,8 +1735,8 @@ McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Comp } mcx_os_fprintf(dotFile, "comp%zu:out%d -> comp%zu:in%d;\n", - srcID, info->GetSourceChannelID(info), - trgID, info->GetTargetChannelID(info)); + srcID, info->sourceChannel, + trgID, info->targetChannel); } mcx_os_fprintf(dotFile, "}\n"); @@ -1468,7 +1787,8 @@ static Model * ModelCreate(Model * model) { // set to default values model->components = (ObjectContainer *) object_create(ObjectContainer); - model->connections = (ObjectContainer *) object_create(ObjectContainer); + model->connections = (Vector *) object_create(Vector); + model->connections->Setup(model->connections, sizeof(ConnectionInfo), ConnectionInfoInit, ConnectionInfoSetFrom, DestroyConnectionInfo); model->factory = NULL; model->config = NULL; diff --git a/src/core/Model.h b/src/core/Model.h index 2f1cfab..a0fefb5 100644 --- a/src/core/Model.h +++ b/src/core/Model.h @@ -19,6 +19,7 @@ #include "core/SubModel.h" #include "reader/model/ModelInput.h" #include "components/ComponentFactory.h" +#include "objects/Vector.h" #ifdef __cplusplus extern "C" { @@ -63,7 +64,7 @@ struct Model { Config * config; Task * task; - ObjectContainer * connections; + Vector * connections; ObjectContainer * components; @@ -77,7 +78,7 @@ struct Model { } ; -McxStatus ReadConnections(ObjectContainer * connections, +McxStatus ReadConnections(Vector * connections, ConnectionsInput * connectionsInput, ObjectContainer * components, Component * sourceComp, @@ -86,9 +87,9 @@ McxStatus ReadConnections(ObjectContainer * connections, McxStatus SetupComponents(ObjectContainer * components, Component * leaveOutComponent); McxStatus SetupDatabusComponents(ObjectContainer * components); -McxStatus MakeConnections(ObjectContainer * connections, InterExtrapolatingType isInterExtrapolating); +McxStatus MakeConnections(Vector * connections, InterExtrapolatingType isInterExtrapolating); -McxStatus PrintModelGraph(ObjectContainer * comps, ObjectContainer * conns, Component * inComp, Component * outComp, const char * title, const char * filename); +McxStatus PrintModelGraph(ObjectContainer * comps, Vector * conns, Component * inComp, Component * outComp, const char * title, const char * filename); McxStatus PrintComponentGraph(Component * comp, const char * filename, struct Dependencies * A, DependencyType depType); @@ -96,6 +97,8 @@ McxStatus ModelConnectionsEnterInitMode(ObjectContainer * comps); McxStatus ModelConnectionsExitInitMode(ObjectContainer * comps, double time); McxStatus ModelDoConnectionsInitialization(ObjectContainer * comps, int onlyIfDecoupled); +int ComponentsHaveVectorChannels(ObjectContainer * components); + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ diff --git a/src/core/SubModel.c b/src/core/SubModel.c index 1e67fd5..e2e64d8 100644 --- a/src/core/SubModel.c +++ b/src/core/SubModel.c @@ -14,13 +14,15 @@ #include "core/SubModel.h" #include "core/Component.h" #include "core/connections/Connection.h" +#include "core/channels/ChannelInfo.h" #include "core/Databus.h" #include "core/channels/Channel.h" #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* __cplusplus */ + static McxStatus SubModelGeneratorSetComponents(SubModelGenerator * subModelGenerator, ObjectContainer * comps, DependencyType depType); @@ -80,7 +82,7 @@ static McxStatus SubModelGeneratorPrintNodeMap(SubModelGenerator * subModelGener } if (comp->OneOutputOneGroup(comp)) { ChannelInfo * info = DatabusGetOutChannelInfo(comp->GetDatabus(comp), compAndGroup->group); - mcx_log(LOG_INFO, " %s (%s, %s)", enu, comp->GetName(comp), info->GetName(info)); + mcx_log(LOG_INFO, " %s (%s, %s)", enu, comp->GetName(comp), ChannelInfoGetName(info)); mcx_log(LOG_DEBUG, " (%zu)", compAndGroup->group); } else if(depType == INITIAL_DEPENDENCIES && comp->GetNumInitialOutGroups(comp) == 1 || depType == RUNTIME_DEPENDENCIES && comp->GetNumOutGroups(comp) == 1) { @@ -89,7 +91,7 @@ static McxStatus SubModelGeneratorPrintNodeMap(SubModelGenerator * subModelGener mcx_log(LOG_INFO, " %s (%s, -)", enu, comp->GetName(comp)); } else { ChannelInfo * info = DatabusGetOutChannelInfo(comp->GetDatabus(comp), compAndGroup->group); - mcx_log(LOG_INFO, " %s (%s, %s)", enu, comp->GetName(comp), info->GetName(info)); + mcx_log(LOG_INFO, " %s (%s, %s)", enu, comp->GetName(comp), ChannelInfoGetName(info)); } } } @@ -393,6 +395,27 @@ static int SubModelIsElement(SubModel * subModel, const Component * comp) { return 0; } +static int SubModelContainsOrIsElement(SubModel * subModel, const Component * comp) { + ObjectContainer * comps = subModel->components; + size_t i = 0; + + for (i = 0; i < comps->Size(comps); i++) { + Component * iComp = (Component *) comps->At(comps, i); + if (!iComp) { + mcx_log(LOG_DEBUG, "Model: nullptr in submodel at idx %zu", i); + continue; + } + + if (comp == iComp) { + return TRUE; + } else if (iComp->ContainsComponent && iComp->ContainsComponent(iComp, comp)) { + return TRUE; + } + } + + return FALSE; +} + // only need to consider DECOUPLE_IFNEEDED since DECOUPLE_ALWAYS is handled at connection->Setup() McxStatus OrderedNodesDecoupleConnections(OrderedNodes * orderedNodes, ObjectContainer * comps) { size_t i; size_t k; @@ -422,7 +445,7 @@ McxStatus OrderedNodesDecoupleConnections(OrderedNodes * orderedNodes, ObjectCon for (ii = 0; ii < group->nodes.size && decouplePriority < INT_MAX; ii++) { for (jj = 0; jj < group->nodes.size && decouplePriority < INT_MAX; jj++) { int localDecouplePriority = -1; - ObjectContainer * connections = NULL; + ObjectList * connections = NULL; Component * fromComp = (Component *) comps->At(comps, group->nodes.values[ii]); Component * toComp = (Component *) comps->At(comps, group->nodes.values[jj]); @@ -445,18 +468,18 @@ McxStatus OrderedNodesDecoupleConnections(OrderedNodes * orderedNodes, ObjectCon Connection * conn = (Connection *) connections->At(connections, k); ConnectionInfo * info = conn->GetInfo(conn); - if (info->IsDecoupled(info)) { + if (ConnectionInfoIsDecoupled(info)) { continue; } if (fromComp->GetSequenceNumber(fromComp) > toComp->GetSequenceNumber(toComp)) { localDecouplePriority = INT_MAX; // ordering by components takes priority break; - } else if (info->GetDecoupleType(info) == DECOUPLE_IFNEEDED) { - if (info->GetDecouplePriority(info) > localDecouplePriority) { - localDecouplePriority = info->GetDecouplePriority(info); + } else if (info->decoupleType == DECOUPLE_IFNEEDED) { + if (info->decouplePriority > localDecouplePriority) { + localDecouplePriority = info->decouplePriority; } - } else if (info->GetDecoupleType(info) == DECOUPLE_NEVER) { + } else if (info->decoupleType == DECOUPLE_NEVER) { // if a connection in this bundle set to never decouple, discard this bundle localDecouplePriority = -1; break; @@ -476,7 +499,7 @@ McxStatus OrderedNodesDecoupleConnections(OrderedNodes * orderedNodes, ObjectCon // decouple connection with highest priority if (decoupleFrom != SIZE_T_ERROR && decoupleTo != SIZE_T_ERROR) { - ObjectContainer * connections = NULL; + ObjectList * connections = NULL; Component * fromComp = (Component *) comps->At(comps, group->nodes.values[decoupleFrom]); Component * toComp = (Component *) comps->At(comps, group->nodes.values[decoupleTo]); @@ -501,11 +524,11 @@ McxStatus OrderedNodesDecoupleConnections(OrderedNodes * orderedNodes, ObjectCon Connection * conn = (Connection *) connections->At(connections, k); ConnectionInfo * info = conn->GetInfo(conn); - char * connStr = info->ConnectionString(info); + char * connStr = ConnectionInfoConnectionString(info); mcx_log(LOG_INFO, "Decoupling connection %s", connStr); mcx_free(connStr); - info->SetDecoupled(info); + ConnectionInfoSetDecoupled(info); } object_destroy(connections); @@ -577,6 +600,7 @@ static SubModel * SubModelCreate(SubModel * subModel) { subModel->LoopEvaluationList = SubModelLoopEvaluationList; subModel->LoopComponents = SubModelLoopComponents; subModel->IsElement = SubModelIsElement; + subModel->ContainsOrIsElement = SubModelContainsOrIsElement; subModel->outConnections = (ObjectContainer *) object_create(ObjectContainer); if (!subModel->outConnections) { @@ -665,76 +689,101 @@ static struct Dependencies * SubModelGeneratorCreateDependencyMatrix(SubModelGen // initial inputs are always exact if (info->initialValue) { //check if connection exists (cosim init values are not deoupling connections, they only have lower priority than connection values) - ConnectionInfo * info = GetInConnectionInfo(targetComp, targetInChannelID); - if (NULL != info) { - if (info->IsDecoupled(info)) {//decoupled connection + Vector * infos = GetInConnectionInfos(targetComp, targetInChannelID); + size_t numInfos = infos->Size(infos); + size_t i = 0; + + if (numInfos == 0) { // no connections + dependency = DEP_INDEPENDENT; + } else { + int allDecoupled = TRUE; + for (i = 0; i < numInfos; i++) { + ConnectionInfo * info = *(ConnectionInfo**) infos->At(infos, i); + if (!ConnectionInfoIsDecoupled(info)) { + object_destroy(infos); + allDecoupled = FALSE; + break; + } + } + + if (allDecoupled) { // decoupled connections dependency = DEP_INDEPENDENT; } - } else {//no connection - dependency = DEP_INDEPENDENT; } + object_destroy(infos); } } if (DEP_INDEPENDENT != dependency) { - ConnectionInfo * info = GetInConnectionInfo(targetComp, targetInChannelID); - Connection * conn = GetInConnection(targetComp, targetInChannelID); - - if (info - && (info->GetDecoupleType(info) & (DECOUPLE_NEVER | DECOUPLE_IFNEEDED)) - && (!info->IsDecoupled(info)) - && conn - && conn->IsActiveDependency(conn)) - { - Component * sourceComp = info->GetSourceComponent(info); - size_t sourceOutGroup, sourceNode; - Databus * db = targetComp->GetDatabus(targetComp); - DatabusInfo * dbInfo = DatabusGetOutInfo(db); - size_t numOutChannels = DatabusInfoGetChannelNum(dbInfo); - - if (INITIAL_DEPENDENCIES == depType) { - sourceOutGroup = sourceComp->GetInitialOutGroup(sourceComp, info->GetSourceChannelID(info)); - } else { - sourceOutGroup = sourceComp->GetOutGroup(sourceComp, info->GetSourceChannelID(info)); - } + Vector * infos = GetInConnectionInfos(targetComp, targetInChannelID); + ConnectionList * conns = GetInConnections(targetComp, targetInChannelID); + size_t i = 0; + + for (i = 0; i < infos->Size(infos); i++) { + ConnectionInfo * info = *(ConnectionInfo**) infos->At(infos, i); + Connection * conn = conns->connections[i]; + + if (info && (info->decoupleType & (DECOUPLE_NEVER | DECOUPLE_IFNEEDED)) && (!ConnectionInfoIsDecoupled(info)) && + conn && conn->IsActiveDependency(conn)) + { + Component * sourceComp = info->sourceComponent; + size_t sourceOutGroup, sourceNode; + Databus * db = targetComp->GetDatabus(targetComp); + DatabusInfo * dbInfo = DatabusGetOutInfo(db); + size_t numOutChannels = DatabusInfoGetChannelNum(dbInfo); + + if (INITIAL_DEPENDENCIES == depType) { + sourceOutGroup = sourceComp->GetInitialOutGroup(sourceComp, info->sourceChannel); + } else { + sourceOutGroup = sourceComp->GetOutGroup(sourceComp, info->sourceChannel); + } - sourceNode = SubModelGeneratorGetNodeID(subModelGenerator, sourceComp, sourceOutGroup); + sourceNode = SubModelGeneratorGetNodeID(subModelGenerator, sourceComp, sourceOutGroup); - if (SIZE_T_ERROR == sourceNode) { - // source is not part of this submodel - // -> no dependency -> do nothing - continue; - } + if (SIZE_T_ERROR == sourceNode) { + // source is not part of this submodel + // -> no dependency -> do nothing + continue; + } - if (INITIAL_DEPENDENCIES == depType) { - // check if the target output has an exact initial value - ChannelInfo * info = NULL; - // check if target outputs even exits - if (0 < numOutChannels) { - info = DatabusGetOutChannelInfo(db, targetGroup); - // initial outputs are exact only if specified - if (info->initialValueIsExact && info->initialValue) { - continue; + if (INITIAL_DEPENDENCIES == depType) { + // check if the target output has an exact initial value + ChannelInfo * info = NULL; + // check if target outputs even exits + if (0 < numOutChannels) { + info = DatabusGetOutChannelInfo(db, targetGroup); + // initial outputs are exact only if specified + if (info->initialValueIsExact && info->initialValue) { + continue; + } } } - } - retVal = SetDependency(A, sourceNode, targetNode, DEP_DEPENDENT); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "SetDependency failed in SubModelGeneratorCreateDependencyMatrix"); - mcx_free(A); - return NULL; - } + retVal = SetDependency(A, sourceNode, targetNode, DEP_DEPENDENT); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "SetDependency failed in SubModelGeneratorCreateDependencyMatrix"); + mcx_free(A); + object_destroy(infos); + return NULL; + } - if (0 == numOutChannels && (INITIAL_DEPENDENCIES == depType) ) { - mcx_log(LOG_DEBUG, "(%s,%d) -> (%s,-)", - sourceComp->GetName(sourceComp), sourceOutGroup, - targetComp->GetName(targetComp) ); - } else { - mcx_log(LOG_DEBUG, "(%s,%d) -> (%s,%d)", - sourceComp->GetName(sourceComp), sourceOutGroup, - targetComp->GetName(targetComp), targetGroup); + if (0 == numOutChannels && (INITIAL_DEPENDENCIES == depType)) { + mcx_log(LOG_DEBUG, + "(%s,%zu) -> (%s,-)", + sourceComp->GetName(sourceComp), + sourceOutGroup, + targetComp->GetName(targetComp)); + } else { + mcx_log(LOG_DEBUG, + "(%s,%zu) -> (%s,%zu)", + sourceComp->GetName(sourceComp), + sourceOutGroup, + targetComp->GetName(targetComp), + targetGroup); + } } } + + object_destroy(infos); } } if (targetCompDependency) { @@ -795,6 +844,39 @@ int OrderedNodesCheckIfLoopsExist(OrderedNodes * nodes) { return FALSE; } +static size_t SubModelGetNumObservableChannels(const SubModel * subModel) { + size_t count = 0; + ObjectContainer * comps = subModel->components; + Component * comp = NULL; + size_t i = 0; + + for (i = 0; i < comps->Size(comps); i++) { + comp = (Component *) comps->At(comps, i); + count += comp->GetNumObservableChannels(comp); + } + + return count; +} + +StringContainer * SubModelGetAllObservableChannelsContainer(SubModel * subModel) { + ObjectContainer * comps = subModel->components; + size_t numObservableChannels = SubModelGetNumObservableChannels(subModel); + + StringContainer * container = StringContainerCreate(numObservableChannels); + size_t count = 0; + size_t i = 0, j = 0; + + for (i = 0; i < comps->Size(comps); i++) { + Component * comp = (Component *) comps->At(comps, i); + // TODO: make composable + comp->AddObservableChannels(comp, container, &count); + } + + StringContainerResize(container, count); + + return container; +} + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/core/SubModel.h b/src/core/SubModel.h index 4ea4f66..1a962a1 100644 --- a/src/core/SubModel.h +++ b/src/core/SubModel.h @@ -19,6 +19,7 @@ extern "C" { #endif /* __cplusplus */ + typedef enum { INITIAL_DEPENDENCIES, RUNTIME_DEPENDENCIES @@ -66,6 +67,7 @@ struct SubModel { fSubModelLoopEvaluationList LoopEvaluationList; fSubModelLoopComponents LoopComponents; fSubModelIsElement IsElement; + fSubModelIsElement ContainsOrIsElement; ObjectContainer * evaluationList; // contains CompAndGroup ObjectContainer * components; // contains Component @@ -74,6 +76,8 @@ struct SubModel { }; +StringContainer * SubModelGetAllObservableChannelsContainer(SubModel * subModel); + extern const struct ObjectClass _SubModelGenerator; struct SubModelGenerator { diff --git a/src/core/Task.c b/src/core/Task.c index b8d6bc0..fa63a9f 100644 --- a/src/core/Task.c +++ b/src/core/Task.c @@ -27,18 +27,25 @@ extern "C" { static int TaskSubmodelIsFinished(SubModel * subModel) { size_t i = 0; - ObjectContainer * eval = subModel->evaluationList; + size_t numComps = eval->Size(eval); + int modelContainsOnlyNeverFinishingComps = numComps ? TRUE : FALSE; - for (i = 0; i < eval->Size(eval); i++) { + for (i = 0; i < numComps; i++) { CompAndGroup * compAndGroup = (CompAndGroup *) eval->At(eval, i); Component * comp = (Component *) compAndGroup->comp; if (comp->GetFinishState(comp) == COMP_IS_NOT_FINISHED) { return FALSE; + } else if (comp->GetFinishState(comp) != COMP_NEVER_FINISHES) { + modelContainsOnlyNeverFinishingComps = FALSE; } } + if (modelContainsOnlyNeverFinishingComps) { + return FALSE; + } + return TRUE; } @@ -77,19 +84,25 @@ static McxStatus TaskPrepareRun(Task * task, Model * model) { McxStatus retVal = RETURN_OK; #if defined (ENABLE_STORAGE) + mcx_signal_handler_set_function("ResultsStorageSetup"); retVal = task->storage->Setup(task->storage, task->timeStart); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Could not setup storage"); return RETURN_ERROR; } + mcx_signal_handler_set_function("ResultsStorageAddModelComponents"); retVal = task->storage->AddModelComponents(task->storage, model->subModel); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Could not setup component storage"); return RETURN_ERROR; } + mcx_signal_handler_set_function("ResultsStorageSetupBackends"); retVal = task->storage->SetupBackends(task->storage); + mcx_signal_handler_unset_function(); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Could not setup storage backends"); return RETURN_ERROR; @@ -112,7 +125,7 @@ static McxStatus TaskInitialize(Task * task, Model * model) { return RETURN_ERROR; } - retVal = subModel->LoopComponents(subModel, CompPostDoUpdateState, (void *) task); + retVal = subModel->LoopComponents(subModel, CompPostDoUpdateState, (void *) stepParams); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Post update state of elements failed during initialization"); return RETURN_ERROR; @@ -122,6 +135,7 @@ static McxStatus TaskInitialize(Task * task, Model * model) { task->storage->StoreModelOut(task->storage, model->subModel, stepParams->time, STORE_SYNCHRONIZATION); task->storage->StoreModelLocal(task->storage, model->subModel, stepParams->time, STORE_SYNCHRONIZATION); + task->storage->StoreModelRTFactor(task->storage, model->subModel, stepParams->time, STORE_SYNCHRONIZATION); task->stepType->Configure(task->stepType, stepParams, subModel); @@ -147,7 +161,9 @@ static McxStatus TaskRun(Task * task, Model * model) { stepParams->timeEndStep += task->params->timeStepSize; } + mcx_signal_handler_set_function("StepTypeDoStep"); status = task->stepType->DoStep(task->stepType, stepParams, subModel); + mcx_signal_handler_unset_function(); if (status != RETURN_OK) { break; } @@ -218,12 +234,14 @@ static McxStatus TaskRead(Task * task, TaskInput * taskInput) { task->params->timeStepSize = taskInput->deltaTime.defined ? taskInput->deltaTime.value : 0.01; mcx_log(LOG_INFO, " Synchronization time step: %g s", task->params->timeStepSize); - task->params->sumTime = taskInput->sumTime.defined ? taskInput->sumTime.value : FALSE; + task->params->sumTime = taskInput->sumTime.defined ? taskInput->sumTime.value : TRUE; if (task->config && task->config->sumTimeDefined) { task->params->sumTime = task->config->sumTime; } if (task->params->sumTime) { mcx_log(LOG_DEBUG, " Using summation for time calculation"); + } else { + mcx_log(LOG_DEBUG, " Using multiplication for time calculation"); } task->stepTypeType = taskInput->stepType; @@ -274,7 +292,7 @@ static McxStatus TaskRead(Task * task, TaskInput * taskInput) { } task->rtFactorEnabled = taskInput->timingOutput.defined ? taskInput->timingOutput.value : FALSE; - retVal = task->storage->Read(task->storage, taskInput->results, task->config); + retVal = task->storage->Read(task->storage, taskInput->results, task->config, IsStepTypeMultiThreading(task->stepTypeType)); return retVal; } diff --git a/src/core/channels/Channel.c b/src/core/channels/Channel.c index be8f9e7..53a0ad4 100644 --- a/src/core/channels/Channel.c +++ b/src/core/channels/Channel.c @@ -10,77 +10,134 @@ #include "CentralParts.h" #include "core/Config.h" +#include "core/channels/ChannelValue.h" #include "core/connections/Connection.h" #include "core/Conversion.h" #include "core/channels/ChannelInfo.h" +#include "core/channels/ChannelValueReference.h" #include "core/channels/Channel.h" +#include "core/channels/ChannelValue.h" #include "core/channels/Channel_impl.h" +#include +#include + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -// ---------------------------------------------------------------------- -// Channel -static ChannelData * ChannelDataCreate(ChannelData * data) { - /* create dummy info*/ - data->info = (ChannelInfo *) object_create(ChannelInfo); - if (!data->info) { - return NULL; +static McxStatus ReportConnStringError(ChannelInfo * chInfo, const char * prefixFmt, ConnectionInfo * connInfo, const char * fmt, ...) { + // create format string + const char * portPrefix = "Port %s: "; + char * connString = NULL; + char * formatString = NULL; + char * prefix = NULL; + + if (connInfo) { + char * connString = ConnectionInfoConnectionString(connInfo); + + prefix = (char *) mcx_calloc(strlen(portPrefix) - 2 /* format specifier %s */ + + strlen(prefixFmt) - (connInfo == NULL ? 0 : 2 /* format specifier %s */) + + (connInfo == NULL ? 0 : connString ? strlen(connString) : strlen("(null)")) + + strlen(ChannelInfoGetLogName(chInfo)) + 1 /* \0 at the end of the string */, + sizeof(char)); + if (!prefix) { + goto cleanup; + } + + sprintf(prefix, portPrefix, ChannelInfoGetLogName(chInfo)); + sprintf(prefix + strlen(prefix), prefixFmt, connString); + } else { + prefix = (char *) mcx_calloc(strlen(portPrefix) - 2 /* format specifier %s */ + strlen(prefixFmt) + + strlen(ChannelInfoGetLogName(chInfo)) + 1 /* \0 at the end of the string */, + sizeof(char)); + if (!prefix) { + goto cleanup; + } + + sprintf(prefix, portPrefix, ChannelInfoGetLogName(chInfo)); } - data->isDefinedDuringInit = FALSE; - data->internalValue = NULL; - ChannelValueInit(&data->value, CHANNEL_UNKNOWN); + formatString = (char *) mcx_calloc(strlen(fmt) + strlen(prefix) + 1, sizeof(char)); + if (!formatString) { + goto cleanup; + } - return data; -} + strcat(formatString, prefix); + strcat(formatString, fmt); + + // log error message + va_list args; + va_start(args, fmt); + + mcx_vlog(LOG_ERROR, formatString, args); + + va_end(args); + +cleanup: + // free connection string + if (connString) { + mcx_free(connString); + } -static void ChannelDataDestructor(ChannelData * data) { - // Note: This is done in Databus - // object_destroy(data->info); + if (prefix) { + mcx_free(prefix); + } + + if (formatString) { + mcx_free(formatString); + } - ChannelValueDestructor(&data->value); + return RETURN_ERROR; } -OBJECT_CLASS(ChannelData, Object); +// ---------------------------------------------------------------------- +// Channel +static int ChannelIsFullyConnected(Channel * channel) { + if (channel->isFullyConnected_ == INVALID_CONNECTION_STATUS) { + channel->SetIsFullyConnected(channel); + } + return channel->isFullyConnected_ == CHANNEL_FULLY_CONNECTED; +} static int ChannelIsDefinedDuringInit(Channel * channel) { - return channel->data->isDefinedDuringInit; + return channel->isDefinedDuringInit; } static void ChannelSetDefinedDuringInit(Channel * channel) { - channel->data->isDefinedDuringInit = TRUE; -} - -static ChannelInfo * ChannelGetInfo(Channel * channel) { - return channel->data->info; + channel->isDefinedDuringInit = TRUE; } static McxStatus ChannelSetup(Channel * channel, ChannelInfo * info) { - if (channel->data->info) { - object_destroy(channel->data->info); - } - channel->data->info = info; + McxStatus retVal = RETURN_OK; + info->channel = channel; + retVal = ChannelInfoSetFrom(&channel->info, info); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + return RETURN_OK; } static void ChannelDestructor(Channel * channel) { - object_destroy(channel->data); + ChannelInfoDestroy(&channel->info); + ChannelValueDestructor(&channel->value); } static Channel * ChannelCreate(Channel * channel) { - channel->data = (ChannelData *) object_create(ChannelData); - if (!channel->data) { + if (RETURN_ERROR == ChannelInfoInit(&channel->info)) { return NULL; } - channel->GetInfo = ChannelGetInfo; + channel->isDefinedDuringInit = FALSE; + channel->internalValue = NULL; + ChannelValueInit(&channel->value, &ChannelTypeUnknown); + channel->Setup = ChannelSetup; channel->IsDefinedDuringInit = ChannelIsDefinedDuringInit; channel->SetDefinedDuringInit = ChannelSetDefinedDuringInit; @@ -88,9 +145,11 @@ static Channel * ChannelCreate(Channel * channel) { // virtual functions channel->GetValueReference = NULL; channel->Update = NULL; - channel->IsValid = NULL; + channel->ProvidesValue = NULL; channel->IsConnected = NULL; + channel->isFullyConnected_ = INVALID_CONNECTION_STATUS; + channel->IsFullyConnected = ChannelIsFullyConnected; return channel; } @@ -102,238 +161,240 @@ static Channel * ChannelCreate(Channel * channel) { // object that is stored in target component that stores // the channel connection +static void DestroyChannelValueReferencePtr(ChannelValueReference ** ptr) { + DestroyChannelValueReference(*ptr); +} + +static McxStatus ChannelInDataInit(ChannelInData * data) { + data->increment = 2; + + data->connList.connections = (Connection * *) mcx_malloc(sizeof(Connection *)); + if (!data->connList.connections) { + mcx_log(LOG_ERROR, "ChannelInDataInit: Allocating space for connections failed"); + return RETURN_ERROR; + } + data->connList.capacity = 1; + data->connList.numConnections = 0; + + data->valueReferences = (ChannelValueReference * *) mcx_malloc(sizeof(ChannelValueReference *)); + if (!data->valueReferences) { + mcx_log(LOG_ERROR, "ChannelInDataInit: Allocating space for value references failed"); + return RETURN_ERROR; + } -static ChannelInData * ChannelInDataCreate(ChannelInData * data) { - data->connection = NULL; data->reference = NULL; + data->type = ChannelTypeClone(&ChannelTypeUnknown); + if (!data->type) { + mcx_log(LOG_ERROR, "ChannelInDataInit: Cloning ChannelType failed"); + return RETURN_ERROR; + } - data->unitConversion = NULL; - data->typeConversion = NULL; + data->typeConversions = (TypeConversion * *) mcx_malloc(sizeof(TypeConversion *)); + if (!data->typeConversions) { + mcx_log(LOG_ERROR, "ChannelInDataInit: Allocating space for type conversion objects failed"); + return RETURN_ERROR; + } + data->unitConversions = (UnitConversion * *) mcx_malloc(sizeof(UnitConversion *)); + if (!data->unitConversions) { + mcx_log(LOG_ERROR, "ChannelInDataInit: Allocating space for unit conversion objects failed"); + return RETURN_ERROR; + } data->linearConversion = NULL; data->rangeConversion = NULL; data->isDiscrete = FALSE; - return data; + return RETURN_OK; } static void ChannelInDataDestructor(ChannelInData * data) { - if (data->unitConversion) { - object_destroy(data->unitConversion); - } - if (data->typeConversion) { - object_destroy(data->typeConversion); - } + if (data->linearConversion) { object_destroy(data->linearConversion); } if (data->rangeConversion) { object_destroy(data->rangeConversion); } -} - -OBJECT_CLASS(ChannelInData, Object); + if (data->type) { + ChannelTypeDestructor(data->type); + } + if (data->valueReferences) { + mcx_free((void *) data->valueReferences); + } + if (data->connList.connections) { + mcx_free((void *) data->connList.connections); + } + if (data->typeConversions) { + for (int j = 0; j < data->connList.numConnections; j++) { + object_destroy(data->typeConversions[j]); + } + mcx_free((void *) data->typeConversions); + } + if (data->unitConversions) { + for (int j = 0; j < data->connList.numConnections; j++) { + object_destroy(data->unitConversions[j]); + } + mcx_free((void *) data->unitConversions); + } +} -static McxStatus ChannelInSetReference(ChannelIn * in, void * reference, ChannelType type) { +static McxStatus ChannelInSetReference(ChannelIn * in, void * reference, ChannelType * type) { Channel * ch = (Channel *) in; - ChannelInfo * info = ch->GetInfo(ch); + ChannelInfo * info = &ch->info; if (!in) { mcx_log(LOG_ERROR, "Port: Set inport reference: Invalid port"); return RETURN_ERROR; } - if (in->data->reference) { - mcx_log(LOG_ERROR, "Port %s: Set inport reference: Reference already set", info->GetLogName(info)); + if (in->data.reference) { + mcx_log(LOG_ERROR, "Port %s: Set inport reference: Reference already set", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - if (CHANNEL_UNKNOWN != type) { + if (ChannelTypeIsValid(type)) { if (!info) { - mcx_log(LOG_ERROR, "Port %s: Set inport reference: Port not set up", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Set inport reference: Port not set up", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - if (info->GetType(info) != type) { - if (info->IsBinary(info) && (type == CHANNEL_BINARY || type == CHANNEL_BINARY_REFERENCE)) { + if (!ChannelTypeEq(info->type, type)) { + if (ChannelInfoIsBinary(info) && ChannelTypeIsBinary(type)) { // ok } else { - mcx_log(LOG_ERROR, "Port %s: Set inport reference: Mismatching types", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Set inport reference: Mismatching types", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } } - in->data->reference = reference; + in->data.reference = reference; + in->data.type = ChannelTypeClone(type); return RETURN_OK; } static const void * ChannelInGetValueReference(Channel * channel) { ChannelIn * in = (ChannelIn *) channel; - if (!channel->IsValid(channel)) { + if (!channel->ProvidesValue(channel)) { const static int maxCountError = 10; static int i = 0; if (i < maxCountError) { - ChannelInfo * info = channel->GetInfo(channel); + ChannelInfo * info = &channel->info; i++; - mcx_log(LOG_ERROR, "Port %s: Get value reference: No value reference for inport", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Get value reference: No value reference for inport", ChannelInfoGetLogName(info)); if (i == maxCountError) { - mcx_log(LOG_ERROR, "Port %s: Get value reference: No value reference for inport - truncated", info->GetLogName(info)) ; + mcx_log(LOG_ERROR, "Port %s: Get value reference: No value reference for inport - truncated", ChannelInfoGetLogName(info)) ; } } return NULL; } - return ChannelValueReference(&channel->data->value); + return ChannelValueDataPointer(&channel->value); } static McxStatus ChannelInUpdate(Channel * channel, TimeInterval * time) { ChannelIn * in = (ChannelIn *) channel; - ChannelInfo * info = channel->GetInfo(channel); - Connection * conn = in->data->connection; + ChannelInfo * info = &channel->info; McxStatus retVal = RETURN_OK; /* if no connection is present we have nothing to update*/ - if (conn) { - ConnectionInfo * connInfo = NULL; - ChannelValue * val = &channel->data->value; - - connInfo = conn->GetInfo(conn); - - ChannelValueDestructor(val); - ChannelValueInit(val, connInfo->GetType(connInfo)); + size_t i = 0; + size_t numConns = in->data.connList.numConnections; + for (i = 0; i < numConns; i++) { + Connection * conn = (Connection *) in->data.connList.connections[i]; + ConnectionInfo * connInfo = &conn->info; + TypeConversion * typeConv = in->data.typeConversions[i]; + UnitConversion * unitConv = in->data.unitConversions[i]; + ChannelValueReference * valueRef = in->data.valueReferences[i]; /* Update the connection for the current time */ - conn->UpdateToOutput(conn, time); - ChannelValueSetFromReference(val, conn->GetValueReference(conn)); - - //type - if (in->data->typeConversion) { - Conversion * conversion = (Conversion *) in->data->typeConversion; - retVal = conversion->convert(conversion, val); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute type conversion", info->GetLogName(info)); - return RETURN_ERROR; - } + if (RETURN_OK != conn->UpdateToOutput(conn, time)) { + return ReportConnStringError(info, "Update inport for connection %s: ", connInfo, "UpdateToOutput failed"); } - } + // TODO: ideally make conn->GetValueReference return ChannelValueReference + if (RETURN_OK != ChannelValueReferenceSetFromPointer(valueRef, conn->GetValueReference(conn), conn->GetValueDimension(conn), typeConv)) { + return ReportConnStringError(info, "Update inport for connection %s: ", connInfo, "ChannelValueReferenceSetFromPointer failed"); + } - if (info->GetType(info) == CHANNEL_DOUBLE) { - ChannelValue * val = &channel->data->value; - // unit - if (in->data->unitConversion) { - Conversion * conversion = (Conversion *) in->data->unitConversion; - retVal = conversion->convert(conversion, val); + // unit conversion + if (unitConv) { + retVal = unitConv->ConvertValueReference(unitConv, valueRef); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute unit conversion", info->GetLogName(info)); - return RETURN_ERROR; + return ReportConnStringError(info, "Update inport for connection %s: ", connInfo, "Unit conversion failed"); } } } - if (info->GetType(info) == CHANNEL_DOUBLE || - info->GetType(info) == CHANNEL_INTEGER) { - ChannelValue * val = &channel->data->value; + + // Conversions + if (numConns > 0) { + ChannelValue * val = &channel->value; // linear - if (in->data->linearConversion) { - Conversion * conversion = (Conversion *) in->data->linearConversion; + if (in->data.linearConversion) { + Conversion * conversion = (Conversion *) in->data.linearConversion; retVal = conversion->convert(conversion, val); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute linear conversion", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute linear conversion", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } // range - if (in->data->rangeConversion) { - Conversion * conversion = (Conversion *) in->data->rangeConversion; + if (in->data.rangeConversion) { + Conversion * conversion = (Conversion *) in->data.rangeConversion; retVal = conversion->convert(conversion, val); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute range conversion", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Update inport: Could not execute range conversion", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } } /* no reference from the component was set, skip updating*/ - if (!in->data->reference || !channel->GetValueReference(channel)) { + if (!in->data.reference || !channel->GetValueReference(channel)) { return RETURN_OK; } - - switch (info->GetType(info)) { - case CHANNEL_DOUBLE: #ifdef MCX_DEBUG - if (time->startTime < MCX_DEBUG_LOG_TIME) { - MCX_DEBUG_LOG("[%f] CH IN (%s) (%f, %f)", time->startTime, info->GetLogName(info), time->startTime, * (double *) channel->GetValueReference(channel)); - } + if (time->startTime < MCX_DEBUG_LOG_TIME && ChannelTypeEq(info->type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("[%f] CH IN (%s) (%f, %f)", time->startTime, ChannelInfoGetLogName(info), time->startTime, * (double *) channel->GetValueReference(channel)); + } #endif // MCX_DEBUG - * (double *) in->data->reference = * (double *) channel->GetValueReference(channel); - break; - case CHANNEL_INTEGER: - * (int *) in->data->reference = * (int *) channel->GetValueReference(channel); - break; - case CHANNEL_BOOL: - * (int *) in->data->reference = * (int *) channel->GetValueReference(channel); - break; - case CHANNEL_STRING: - { - const void * reference = channel->GetValueReference(channel); - if (NULL != reference && NULL != * (const char * *) reference ) { - if (* (char * *) in->data->reference) { - mcx_free(* (char * *) in->data->reference); - } - * (char * *) in->data->reference = (char *) mcx_calloc(strlen(* (const char **) reference) + 1, sizeof(char)); - if (* (char * *) in->data->reference) { - strncpy(* (char * *) in->data->reference, * (const char **)reference, strlen(* (const char **)reference) + 1); - } - } - break; + if (RETURN_OK != ChannelValueDataSetFromReference(in->data.reference, in->data.type, channel->GetValueReference(channel))) { + return RETURN_ERROR; } - case CHANNEL_BINARY: - { - const void * reference = channel->GetValueReference(channel); - if (NULL != reference && NULL != ((const binary_string *) reference)->data) { - if (((binary_string *) in->data->reference)->data) { - mcx_free(((binary_string *) in->data->reference)->data); - } - ((binary_string *) in->data->reference)->len = ((const binary_string *) reference)->len; - ((binary_string *) in->data->reference)->data = (char *) mcx_malloc(((binary_string *) in->data->reference)->len); - if (((binary_string *) in->data->reference)->data) { - memcpy(((binary_string *) in->data->reference)->data, ((const binary_string *) reference)->data, ((binary_string *) in->data->reference)->len); - } - } - break; - } - case CHANNEL_BINARY_REFERENCE: - { - const void * reference = channel->GetValueReference(channel); + return RETURN_OK; +} - if (NULL != reference && NULL != ((binary_string *) reference)->data) { - ((binary_string *) in->data->reference)->len = ((binary_string *) reference)->len; - ((binary_string *) in->data->reference)->data = ((binary_string *) reference)->data; - } - break; - } - default: - break; +static McxStatus ChannelInSetIsFullyConnected(Channel * channel) { + ChannelIn * in = (ChannelIn *) channel; + size_t i = 0; + size_t connectedElems = 0; + size_t channelNumElems = channel->info.dimension ? ChannelDimensionNumElements(channel->info.dimension) : 1; + + for (i = 0; i < in->data.connList.numConnections; i++) { + Connection * conn = (Connection *) in->data.connList.connections[i]; + ConnectionInfo * info = &conn->info; + + connectedElems += info->targetDimension ? ChannelDimensionNumElements(info->targetDimension) : 1; } + channel->isFullyConnected_ = connectedElems == channelNumElems; + return RETURN_OK; } -static int ChannelInIsValid(Channel * channel) { - - if (channel->IsConnected(channel)) { +static int ChannelInProvidesValue(Channel * channel) { + if (channel->IsFullyConnected(channel)) { return TRUE; } else { - ChannelInfo * info = channel->GetInfo(channel); + ChannelInfo * info = &channel->info; if (info && NULL != info->defaultValue) { return TRUE; } @@ -342,19 +403,19 @@ static int ChannelInIsValid(Channel * channel) { } static void ChannelInSetDiscrete(ChannelIn * in) { - in->data->isDiscrete = TRUE; + in->data.isDiscrete = TRUE; } static int ChannelInIsDiscrete(ChannelIn * in) { - return in->data->isDiscrete; + return in->data.isDiscrete; } static int ChannelInIsConnected(Channel * channel) { - if (channel->data->info && channel->data->info->connected) { + if (ChannelTypeIsValid(channel->info.type) && channel->info.connected) { return TRUE; } else { ChannelIn * in = (ChannelIn *) channel; - if (NULL != in->data->connection) { + if (in->data.connList.numConnections > 0) { return TRUE; } } @@ -362,64 +423,108 @@ static int ChannelInIsConnected(Channel * channel) { return FALSE; } -static ConnectionInfo * ChannelInGetConnectionInfo(ChannelIn * in) { - if (in->data->connection) { - return in->data->connection->GetInfo(in->data->connection); - } else { +static Vector * ChannelInGetConnectionInfos(ChannelIn * in) { + Vector * infos = (Vector*) object_create(Vector); + size_t numConns = in->data.connList.numConnections; + size_t i = 0; + + if (!infos) { return NULL; } -} -static Connection * ChannelInGetConnection(ChannelIn * in) { - if (in->data->connection) { - return in->data->connection; - } else { - return NULL; + infos->Setup(infos, sizeof(ConnectionInfo*), NULL, NULL, NULL); + + for (i = 0; i < numConns; i++) { + Connection * conn = in->data.connList.connections[i]; + ConnectionInfo * connInfo = &conn->info; + if (RETURN_ERROR == infos->PushBack(infos, &connInfo)) { + object_destroy(infos); + return NULL; + } } + + return infos; +} + +static ConnectionList * ChannelInGetConnections(ChannelIn * in) { + return &in->data.connList; } -static McxStatus ChannelInSetConnection(ChannelIn * in, Connection * connection, const char * unit, ChannelType type -) { +static McxStatus ChannelInRegisterConnection(ChannelIn * in, Connection * connection, const char * unit, ChannelType * type) { + ConnectionInfo * connInfo = &connection->info; Channel * channel = (Channel *) in; - ChannelInfo * inInfo = NULL; + ChannelInfo * inInfo = &channel->info; + ChannelValueReference * valRef = NULL; + ConnectionList * connList = &in->data.connList; - McxStatus retVal; + McxStatus retVal = RETURN_OK; - in->data->connection = connection; - channel->data->internalValue = connection->GetValueReference(connection); + while (connList->capacity <= connList->numConnections) { + connList->capacity *= in->data.increment; + connList->connections = mcx_realloc(connList->connections, sizeof(Connection *) * connList->capacity); + in->data.typeConversions = mcx_realloc(in->data.typeConversions, sizeof(TypeConversion *) * connList->capacity); + in->data.unitConversions = mcx_realloc(in->data.unitConversions, sizeof(UnitConversion *) * connList->capacity); + in->data.valueReferences = mcx_realloc(in->data.valueReferences, sizeof(ChannelValueReference *) * connList->capacity); + if (!connList->connections || !in->data.typeConversions || !in->data.unitConversions || !in->data.valueReferences) { + mcx_log(LOG_ERROR, "ChannelInRegisterConnection: (Re-)Allocation of connection related data failed"); + return RETURN_ERROR; + } + } + connList->connections[connList->numConnections] = connection; + connList->numConnections++; - // setup unit conversion - inInfo = channel->GetInfo(channel); + ChannelDimension * dimension = connInfo->targetDimension; + if (dimension && !ChannelDimensionEq(dimension, inInfo->dimension)) { + ChannelDimension * slice = CloneChannelDimension(dimension); - if (inInfo->GetType(inInfo) == CHANNEL_DOUBLE) { - in->data->unitConversion = (UnitConversion *) object_create(UnitConversion); - retVal = in->data->unitConversion->Setup(in->data->unitConversion, - unit, - inInfo->GetUnit(inInfo)); - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Set inport connection: Could not setup unit conversion", inInfo->GetLogName(inInfo)); + retVal = ChannelDimensionAlignIndicesWithZero(slice, inInfo->dimension); + if (retVal == RETURN_ERROR) { + ReportConnStringError(inInfo, "Register inport connection %s: ", connInfo, "Normalizing array slice dimension failed"); return RETURN_ERROR; } - if (in->data->unitConversion->IsEmpty(in->data->unitConversion)) { - object_destroy(in->data->unitConversion); + valRef = MakeChannelValueReference(&channel->value, slice); + } else { + valRef = MakeChannelValueReference(&channel->value, NULL); + } + + in->data.valueReferences[connList->numConnections - 1] = valRef; + + if (ChannelTypeEq(ChannelTypeBaseType(inInfo->type), &ChannelTypeDouble)) { + UnitConversion * conversion = (UnitConversion *) object_create(UnitConversion); + + retVal = conversion->Setup(conversion, unit, inInfo->unitString); + if (RETURN_ERROR == retVal) { + return ReportConnStringError(inInfo, "Register inport connection %s: ", connInfo, "Could not set up unit conversion"); + } + + if (conversion->IsEmpty(conversion)) { + object_destroy(conversion); } + + in->data.unitConversions[connList->numConnections - 1] = conversion; + } else { + in->data.unitConversions[connList->numConnections - 1] = NULL; } // setup type conversion - if (inInfo->GetType(inInfo) != type) { - in->data->typeConversion = (TypeConversion *) object_create(TypeConversion); - retVal = in->data->typeConversion->Setup(in->data->typeConversion, - type, - inInfo->GetType(inInfo)); + if (!ChannelTypeConformable(inInfo->type, inInfo->dimension, connection->GetValueType(connection), connection->GetValueDimension(connection))) { + TypeConversion * typeConv = (TypeConversion *) object_create(TypeConversion); + retVal = typeConv->Setup(typeConv, + connection->GetValueType(connection), + connection->GetValueDimension(connection), + inInfo->type, + connInfo->targetDimension); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Set connection: Could not setup type conversion", inInfo->GetLogName(inInfo)); - return RETURN_ERROR; + return ReportConnStringError(inInfo, "Register inport connection %s: ", connInfo, "Could not set up type conversion"); } - } - return RETURN_OK; + in->data.typeConversions[connList->numConnections - 1] = typeConv; + } else { + in->data.typeConversions[connList->numConnections - 1] = NULL; + } + return retVal; } static McxStatus ChannelInSetup(ChannelIn * in, ChannelInfo * info) { @@ -429,52 +534,63 @@ static McxStatus ChannelInSetup(ChannelIn * in, ChannelInfo * info) { retVal = channel->Setup(channel, info); // call base-class function // types - if (info->type == CHANNEL_UNKNOWN) { - mcx_log(LOG_ERROR, "Port %s: Setup inport: Unknown type", info->GetLogName(info)); + if (!ChannelTypeIsValid(info->type)) { + mcx_log(LOG_ERROR, "Port %s: Setup inport: Unknown type", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - ChannelValueInit(&channel->data->value, info->type); + ChannelValueInit(&channel->value, ChannelTypeClone(info->type)); // default value if (info->defaultValue) { - ChannelValueSet(&channel->data->value, info->defaultValue); + ChannelValueSet(&channel->value, info->defaultValue); + + // apply range and linear conversions immediately + retVal = ConvertRange(info->min, info->max, &channel->value, NULL); + if (retVal == RETURN_ERROR) { + return RETURN_ERROR; + } + + retVal = ConvertLinear(info->scale, info->offset, &channel->value, NULL); + if (retVal == RETURN_ERROR) { + return RETURN_ERROR; + } + channel->SetDefinedDuringInit(channel); - channel->data->internalValue = ChannelValueReference(&channel->data->value); } // unit conversion is setup when a connection is set // min/max conversions are only used for double types - if (info->GetType(info) == CHANNEL_DOUBLE - || info->GetType(info) == CHANNEL_INTEGER) + if (ChannelTypeEq(ChannelTypeBaseType(info->type), &ChannelTypeDouble) || + ChannelTypeEq(ChannelTypeBaseType(info->type), &ChannelTypeInteger)) { - ChannelValue * min = info->GetMin(info); - ChannelValue * max = info->GetMax(info); + ChannelValue * min = info->min; + ChannelValue * max = info->max; - ChannelValue * scale = info->GetScale(info); - ChannelValue * offset = info->GetOffset(info); + ChannelValue * scale = info->scale; + ChannelValue * offset = info->offset; - in->data->rangeConversion = (RangeConversion *) object_create(RangeConversion); - retVal = in->data->rangeConversion->Setup(in->data->rangeConversion, min, max); + in->data.rangeConversion = (RangeConversion *) object_create(RangeConversion); + retVal = in->data.rangeConversion->Setup(in->data.rangeConversion, min, max); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Setup inport: Could not setup range conversion", info->GetLogName(info)); - object_destroy(in->data->rangeConversion); + mcx_log(LOG_ERROR, "Port %s: Setup inport: Could not setup range conversion", ChannelInfoGetLogName(info)); + object_destroy(in->data.rangeConversion); return RETURN_ERROR; } else { - if (in->data->rangeConversion->IsEmpty(in->data->rangeConversion)) { - object_destroy(in->data->rangeConversion); + if (in->data.rangeConversion->IsEmpty(in->data.rangeConversion)) { + object_destroy(in->data.rangeConversion); } } - in->data->linearConversion = (LinearConversion *) object_create(LinearConversion); - retVal = in->data->linearConversion->Setup(in->data->linearConversion, scale, offset); + in->data.linearConversion = (LinearConversion *) object_create(LinearConversion); + retVal = in->data.linearConversion->Setup(in->data.linearConversion, scale, offset); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Setup inport: Could not setup linear conversion", info->GetLogName(info)); - object_destroy(in->data->linearConversion); + mcx_log(LOG_ERROR, "Port %s: Setup inport: Could not setup linear conversion", ChannelInfoGetLogName(info)); + object_destroy(in->data.linearConversion); return RETURN_ERROR; } else { - if (in->data->linearConversion->IsEmpty(in->data->linearConversion)) { - object_destroy(in->data->linearConversion); + if (in->data.linearConversion->IsEmpty(in->data.linearConversion)) { + object_destroy(in->data.linearConversion); } } } @@ -483,30 +599,33 @@ static McxStatus ChannelInSetup(ChannelIn * in, ChannelInfo * info) { } static void ChannelInDestructor(ChannelIn * in) { - object_destroy(in->data); + ChannelInDataDestructor(&in->data); } static ChannelIn * ChannelInCreate(ChannelIn * in) { Channel * channel = (Channel *) in; + McxStatus retVal = RETURN_OK; - in->data = (ChannelInData *) object_create(ChannelInData); - if (!in->data) { + retVal = ChannelInDataInit(&in->data); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "ChannelInCreate: ChannelInDataInit failed"); return NULL; } // virtual functions channel->GetValueReference = ChannelInGetValueReference; - channel->IsValid = ChannelInIsValid; + channel->ProvidesValue = ChannelInProvidesValue; channel->Update = ChannelInUpdate; channel->IsConnected = ChannelInIsConnected; + channel->SetIsFullyConnected = ChannelInSetIsFullyConnected; in->Setup = ChannelInSetup; in->SetReference = ChannelInSetReference; - in->GetConnectionInfo = ChannelInGetConnectionInfo; + in->GetConnectionInfos = ChannelInGetConnectionInfos; - in->GetConnection = ChannelInGetConnection; - in->SetConnection = ChannelInSetConnection; + in->GetConnections = ChannelInGetConnections; + in->RegisterConnection = ChannelInRegisterConnection; in->IsDiscrete = ChannelInIsDiscrete; in->SetDiscrete = ChannelInSetDiscrete; @@ -518,14 +637,23 @@ static ChannelIn * ChannelInCreate(ChannelIn * in) { // ---------------------------------------------------------------------- // ChannelOut -static ChannelOutData * ChannelOutDataCreate(ChannelOutData * data) { +static McxStatus ChannelOutDataInit(ChannelOutData * data) { data->valueFunction = NULL; + ChannelValueInit(&data->valueFunctionRes, ChannelTypeClone(&ChannelTypeUnknown)); data->rangeConversion = NULL; data->linearConversion = NULL; data->rangeConversionIsActive = TRUE; - data->connections = (ObjectContainer *) object_create(ObjectContainer); + data->increment = 2; + + data->connList.numConnections = 0; + data->connList.capacity = 1; + data->connList.connections = (Connection * *) mcx_malloc(sizeof(Connection *)); + if (!data->connList.connections) { + mcx_log(LOG_ERROR, "ChannelOutDataInit: Allocation of connections failed"); + return RETURN_ERROR; + } data->nanCheck = NAN_CHECK_ALWAYS; @@ -533,11 +661,10 @@ static ChannelOutData * ChannelOutDataCreate(ChannelOutData * data) { data->maxNumNaNCheckWarning = 0; - return data; + return RETURN_OK; } static void ChannelOutDataDestructor(ChannelOutData * data) { - ObjectContainer * conns = data->connections; size_t i = 0; if (data->rangeConversion) { @@ -547,129 +674,182 @@ static void ChannelOutDataDestructor(ChannelOutData * data) { object_destroy(data->linearConversion); } - for (i = 0; i < conns->Size(conns); i++) { - object_destroy(conns->elements[i]); + if (data->connList.connections) { + for (i = 0; i < data->connList.numConnections; i++) { + if (data->connList.connections[i]) { + object_destroy(data->connList.connections[i]); + } + } + mcx_free(data->connList.connections); } - object_destroy(data->connections); -} - -OBJECT_CLASS(ChannelOutData, Object); - + ChannelValueDestructor(&data->valueFunctionRes); +} static McxStatus ChannelOutSetup(ChannelOut * out, ChannelInfo * info, Config * config) { Channel * channel = (Channel *) out; - ChannelValue * min = info->GetMin(info); - ChannelValue * max = info->GetMax(info); + ChannelValue * min = info->min; + ChannelValue * max = info->max; - ChannelValue * scale = info->GetScale(info); - ChannelValue * offset = info->GetOffset(info); + ChannelValue * scale = info->scale; + ChannelValue * offset = info->offset; McxStatus retVal; retVal = channel->Setup(channel, info); // call base-class function // default value - if (info->type == CHANNEL_UNKNOWN) { - mcx_log(LOG_ERROR, "Port %s: Setup outport: Unknown type", info->GetLogName(info)); + if (!ChannelTypeIsValid(info->type)) { + mcx_log(LOG_ERROR, "Port %s: Setup outport: Unknown type", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - ChannelValueInit(&channel->data->value, info->type); + ChannelValueInit(&channel->value, ChannelTypeClone(info->type)); // default value if (info->defaultValue) { - channel->data->internalValue = ChannelValueReference(info->defaultValue); + channel->internalValue = ChannelValueDataPointer(channel->info.defaultValue); } // min/max conversions are only used for double types - if (info->GetType(info) == CHANNEL_DOUBLE - || info->GetType(info) == CHANNEL_INTEGER) + if (ChannelTypeEq(ChannelTypeBaseType(info->type), &ChannelTypeDouble) + || ChannelTypeEq(ChannelTypeBaseType(info->type), &ChannelTypeInteger)) { - out->data->rangeConversion = (RangeConversion *) object_create(RangeConversion); - retVal = out->data->rangeConversion->Setup(out->data->rangeConversion, min, max); + out->data.rangeConversion = (RangeConversion *) object_create(RangeConversion); + retVal = out->data.rangeConversion->Setup(out->data.rangeConversion, min, max); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Setup outport: Could not setup range conversion", info->GetLogName(info)); - object_destroy(out->data->rangeConversion); + mcx_log(LOG_ERROR, "Port %s: Setup outport: Could not setup range conversion", ChannelInfoGetLogName(info)); + object_destroy(out->data.rangeConversion); return RETURN_ERROR; } else { - if (out->data->rangeConversion->IsEmpty(out->data->rangeConversion)) { - object_destroy(out->data->rangeConversion); + if (out->data.rangeConversion->IsEmpty(out->data.rangeConversion)) { + object_destroy(out->data.rangeConversion); } } - out->data->linearConversion = (LinearConversion *) object_create(LinearConversion); - retVal = out->data->linearConversion->Setup(out->data->linearConversion, scale, offset); + out->data.linearConversion = (LinearConversion *) object_create(LinearConversion); + retVal = out->data.linearConversion->Setup(out->data.linearConversion, scale, offset); if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Port %s: Setup outport: Could not setup linear conversion", info->GetLogName(info)); - object_destroy(out->data->linearConversion); + mcx_log(LOG_ERROR, "Port %s: Setup outport: Could not setup linear conversion", ChannelInfoGetLogName(info)); + object_destroy(out->data.linearConversion); return RETURN_ERROR; } else { - if (out->data->linearConversion->IsEmpty(out->data->linearConversion)) { - object_destroy(out->data->linearConversion); + if (out->data.linearConversion->IsEmpty(out->data.linearConversion)) { + object_destroy(out->data.linearConversion); } } } if (!config) { - mcx_log(LOG_DEBUG, "Port %s: Setup outport: No config available", info->GetLogName(info)); + mcx_log(LOG_DEBUG, "Port %s: Setup outport: No config available", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - out->data->nanCheck = config->nanCheck; - out->data->maxNumNaNCheckWarning = config->nanCheckNumMessages; + out->data.nanCheck = config->nanCheck; + out->data.maxNumNaNCheckWarning = config->nanCheckNumMessages; return RETURN_OK; } static McxStatus ChannelOutRegisterConnection(ChannelOut * out, Connection * connection) { - ObjectContainer * conns = out->data->connections; + ChannelInfo * outInfo = &((Channel *) out)->info; + ConnectionInfo * connInfo = &connection->info; + ConnectionList * connList = &out->data.connList; + + // TODO: do we have to check that channelout and connection match + // in type/dimension? + + while (connList->capacity <= connList->numConnections) { + connList->capacity *= out->data.increment; + connList->connections = mcx_realloc(connList->connections, connList->capacity * sizeof(Connection *)); + if (!connList->connections) { + return ReportConnStringError(outInfo, "Register outport connection %s: ", connInfo, "Could not set up connections (realloc failed)"); + } + } + connList->connections[connList->numConnections] = connection; + connList->numConnections++; - return conns->PushBack(conns, (Object *) connection); + return RETURN_OK; } static const void * ChannelOutGetValueReference(Channel * channel) { ChannelOut * out = (ChannelOut *) channel; - ChannelInfo * info = channel->GetInfo(channel); + ChannelInfo * info = &channel->info; // check if out is initialized - if (!channel->IsValid(channel)) { - mcx_log(LOG_ERROR, "Port %s: Get value reference: No Value Reference", info->GetLogName(info)); + if (!channel->ProvidesValue(channel)) { + mcx_log(LOG_ERROR, "Port %s: Get value reference: No Value Reference", ChannelInfoGetLogName(info)); return NULL; } - return ChannelValueReference(&channel->data->value); + return ChannelValueDataPointer(&channel->value); } static const proc * ChannelOutGetFunction(ChannelOut * out) { - return out->data->valueFunction; + return out->data.valueFunction; } -static ObjectContainer * ChannelOutGetConnections(ChannelOut * out) { - return out->data->connections; +static ConnectionList * ChannelOutGetConnections(ChannelOut * out) { + return &out->data.connList; } -static int ChannelOutIsValid(Channel * channel) { - return (NULL != channel->data->internalValue); +static int ChannelOutProvidesValue(Channel * channel) { + return (NULL != channel->internalValue); } static int ChannelOutIsConnected(Channel * channel) { - if (channel->data->info->connected) { + if (channel->info.connected) { return TRUE; } else { ChannelOut * out = (ChannelOut *) channel; - if (NULL != out->data->connections) { - if (out->data->connections->Size(out->data->connections)) { - return TRUE; - } + if (out->data.connList.numConnections) { + return TRUE; } } return FALSE; } -static McxStatus ChannelOutSetReference(ChannelOut * out, const void * reference, ChannelType type) { +static McxStatus ChannelOutSetIsFullyConnected(Channel * channel) { + ChannelOut * out = (ChannelOut *) channel; + + if (ChannelTypeIsArray(channel->info.type)) { + ConnectionList * conns = &out->data.connList; + size_t i = 0; + size_t num_elems = ChannelDimensionNumElements(channel->info.dimension); + + int * connected = (int *) mcx_calloc(num_elems, sizeof(int)); + if (!connected) { + mcx_log(LOG_ERROR, "ChannelOutIsFullyConnected: Not enough memory"); + return RETURN_ERROR; + } + + for (i = 0; i < conns->numConnections; i++) { + Connection * conn = out->data.connList.connections[i]; + ConnectionInfo * info = &conn->info; + size_t j = 0; + + for (j = 0; j < ChannelDimensionNumElements(info->sourceDimension); j++) { + size_t idx = ChannelDimensionGetIndex(info->sourceDimension, j, channel->info.type->ty.a.dims); + connected[idx - info->sourceDimension->startIdxs[0]] = 1; + } + } + + channel->isFullyConnected_ = CHANNEL_FULLY_CONNECTED; + for (i = 0; i < num_elems; i++) { + if (!connected[i]) { + channel->isFullyConnected_ = CHANNEL_ONLY_PARTIALLY_CONNETED; + } + } + } else { + channel->isFullyConnected_ = ChannelOutIsConnected(channel); + } + + return RETURN_OK; +} + +static McxStatus ChannelOutSetReference(ChannelOut * out, const void * reference, ChannelType * type) { Channel * channel = (Channel *) out; ChannelInfo * info = NULL; @@ -677,33 +857,33 @@ static McxStatus ChannelOutSetReference(ChannelOut * out, const void * reference mcx_log(LOG_ERROR, "Port: Set outport reference: Invalid port"); return RETURN_ERROR; } - info = channel->GetInfo(channel); + info = &channel->info; if (!info) { - mcx_log(LOG_ERROR, "Port %s: Set outport reference: Port not set up", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Set outport reference: Port not set up", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - if (channel->data->internalValue - && !(info->defaultValue && channel->data->internalValue == ChannelValueReference(info->defaultValue))) { - mcx_log(LOG_ERROR, "Port %s: Set outport reference: Reference already set", info->GetLogName(info)); + if (channel->internalValue + && !(info->defaultValue && channel->internalValue == ChannelValueDataPointer(info->defaultValue))) { + mcx_log(LOG_ERROR, "Port %s: Set outport reference: Reference already set", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - if (CHANNEL_UNKNOWN != type) { - if (info->GetType(info) != type) { - if (info->IsBinary(info) && (type == CHANNEL_BINARY || type == CHANNEL_BINARY_REFERENCE)) { + if (ChannelTypeIsValid(type)) { + if (!ChannelTypeEq(info->type, type)) { + if (ChannelInfoIsBinary(info) && ChannelTypeIsBinary(type)) { // ok } else { - mcx_log(LOG_ERROR, "Port %s: Set outport reference: Mismatching types", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Set outport reference: Mismatching types", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } } - channel->data->internalValue = reference; + channel->internalValue = reference; return RETURN_OK; } -static McxStatus ChannelOutSetReferenceFunction(ChannelOut * out, const proc * reference, ChannelType type) { +static McxStatus ChannelOutSetReferenceFunction(ChannelOut * out, const proc * reference, ChannelType * type) { Channel * channel = (Channel *) out; ChannelInfo * info = NULL; if (!out) { @@ -711,24 +891,27 @@ static McxStatus ChannelOutSetReferenceFunction(ChannelOut * out, const proc * r return RETURN_ERROR; } - info = channel->GetInfo(channel); - if (CHANNEL_UNKNOWN != type) { - if (info->type != type) { - mcx_log(LOG_ERROR, "Port %s: Set outport function: Mismatching types", info->GetLogName(info)); + info = &channel->info; + if (ChannelTypeIsValid(type)) { + if (!ChannelTypeEq(info->type, type)) { + mcx_log(LOG_ERROR, "Port %s: Set outport function: Mismatching types", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } - if (out->data->valueFunction) { - mcx_log(LOG_ERROR, "Port %s: Set outport function: Reference already set", info->GetLogName(info)); + if (out->data.valueFunction) { + mcx_log(LOG_ERROR, "Port %s: Set outport function: Reference already set", ChannelInfoGetLogName(info)); return RETURN_ERROR; } // Save channel procedure - out->data->valueFunction = (const proc *) reference; + out->data.valueFunction = (const proc *) reference; + + // Initialize (and allocate necessary memory) + ChannelValueInit(&out->data.valueFunctionRes, ChannelTypeClone(type)); // Setup value reference to point to internal value - channel->data->internalValue = ChannelValueReference(&channel->data->value); + channel->internalValue = ChannelValueDataPointer(&channel->value); return RETURN_OK; } @@ -737,7 +920,7 @@ static void WarnAboutNaN(LogSeverity level, ChannelInfo * info, TimeInterval * t if (*max > 0) { if (*count < *max) { mcx_log(level, "Outport %s at time %f is not a number (NaN)", - info->GetName(info), time->startTime); + ChannelInfoGetName(info), time->startTime); *count += 1; if (*count == *max) { mcx_log(level, "This warning will not be shown anymore"); @@ -745,15 +928,17 @@ static void WarnAboutNaN(LogSeverity level, ChannelInfo * info, TimeInterval * t } } else { mcx_log(level, "Outport %s at time %f is not a number (NaN)", - info->GetName(info), time->startTime); + ChannelInfoGetName(info), time->startTime); } } static McxStatus ChannelOutUpdate(Channel * channel, TimeInterval * time) { ChannelOut * out = (ChannelOut *)channel; - ChannelInfo * info = ((Channel *)out)->GetInfo((Channel *)out); + ChannelInfo * info = &channel->info; + + ConnectionList * conns = &out->data.connList; - ObjectContainer * conns = out->data->connections; + ChannelValue * val = NULL; McxStatus retVal = RETURN_OK; @@ -765,96 +950,104 @@ static McxStatus ChannelOutUpdate(Channel * channel, TimeInterval * time) { if (out->GetFunction(out)) { // function value proc * p = (proc *) out->GetFunction(out); - double val = p->fn(time, p->env); + if (RETURN_ERROR == p->fn(time, p->env, &out->data.valueFunctionRes)) { + mcx_log(LOG_ERROR, "Port %s: Update outport: Function failed", ChannelInfoGetLogName(info)); + return RETURN_ERROR; + } #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - MCX_DEBUG_LOG("[%f] CH OUT (%s) (%f, %f)", time->startTime, info->GetLogName(info), time->startTime, val); + MCX_DEBUG_LOG("[%f] CH OUT (%s) (%f, %f)", + time->startTime, + ChannelInfoGetLogName(info), + time->startTime, + out->data.valueFunctionRes.value.d); } #endif // MCX_DEBUG - ChannelValueSetFromReference(&channel->data->value, &val); + if (RETURN_OK != ChannelValueSetFromReference(&channel->value, ChannelValueDataPointer(&out->data.valueFunctionRes))) { + return RETURN_ERROR; + } } else { #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - if (CHANNEL_DOUBLE == info->GetType(info)) { + if (ChannelTypeEq(&ChannelTypeDouble, info->type)) { MCX_DEBUG_LOG("[%f] CH OUT (%s) (%f, %f)", time->startTime, - info->GetLogName(info), + ChannelInfoGetLogName(info), time->startTime, - * (double *) channel->data->internalValue); + * (double *) channel->internalValue); } else { - MCX_DEBUG_LOG("[%f] CH OUT (%s)", time->startTime, info->GetLogName(info)); + MCX_DEBUG_LOG("[%f] CH OUT (%s)", time->startTime, ChannelInfoGetLogName(info)); } } #endif // MCX_DEBUG - ChannelValueSetFromReference(&channel->data->value, channel->data->internalValue); - } - - // Apply conversion - if (info->GetType(info) == CHANNEL_DOUBLE || - info->GetType(info) == CHANNEL_INTEGER) { - ChannelValue * val = &channel->data->value; - - // range - if (out->data->rangeConversion) { - if (out->data->rangeConversionIsActive) { - Conversion * conversion = (Conversion *) out->data->rangeConversion; - retVal = conversion->convert(conversion, val); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update outport: Could not execute range conversion", info->GetLogName(info)); - return RETURN_ERROR; - } - } + if (RETURN_OK != ChannelValueSetFromReference(&channel->value, channel->internalValue)) { + mcx_log(LOG_ERROR, "Port %s: Update outport: Setting value failed", ChannelInfoGetLogName(info)); + return RETURN_ERROR; } + } - // linear - if (out->data->linearConversion) { - Conversion * conversion = (Conversion *) out->data->linearConversion; + val = &channel->value; + + // range conversion + if (out->data.rangeConversion) { + if (out->data.rangeConversionIsActive) { + Conversion * conversion = (Conversion *) out->data.rangeConversion; retVal = conversion->convert(conversion, val); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Port %s: Update outport: Could not execute linear conversion", info->GetLogName(info)); + mcx_log(LOG_ERROR, "Port %s: Update outport: Could not execute range conversion", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } } + // linear conversion + if (out->data.linearConversion) { + Conversion * conversion = (Conversion *) out->data.linearConversion; + retVal = conversion->convert(conversion, val); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Port %s: Update outport: Could not execute linear conversion", ChannelInfoGetLogName(info)); + return RETURN_ERROR; + } + } + // Notify connections of new values - for (j = 0; j < conns->Size(conns); j++) { - Connection * connection = (Connection *) conns->At(conns, j); - channel->SetDefinedDuringInit(channel); + channel->SetDefinedDuringInit(channel); + for (j = 0; j < conns->numConnections; j++) { + Connection * connection = conns->connections[j]; connection->UpdateFromInput(connection, time); } } - if (CHANNEL_DOUBLE == info->GetType(info)) { + if (ChannelTypeEq(&ChannelTypeDouble, info->type)) { const double * val = NULL; { - val = &channel->data->value.value.d; + val = &channel->value.value.d; } if (isnan(*val)) { - switch (out->data->nanCheck) { + switch (out->data.nanCheck) { case NAN_CHECK_ALWAYS: mcx_log(LOG_ERROR, "Outport %s at time %f is not a number (NaN)", - info->GetName(info), time->startTime); + ChannelInfoGetName(info), time->startTime); return RETURN_ERROR; case NAN_CHECK_CONNECTED: - if (conns->Size(conns) > 0) { + if (conns->numConnections > 0) { mcx_log(LOG_ERROR, "Outport %s at time %f is not a number (NaN)", - info->GetName(info), time->startTime); + ChannelInfoGetName(info), time->startTime); return RETURN_ERROR; } else { - WarnAboutNaN(LOG_WARNING, info, time, &out->data->countNaNCheckWarning, &out->data->maxNumNaNCheckWarning); + WarnAboutNaN(LOG_WARNING, info, time, &out->data.countNaNCheckWarning, &out->data.maxNumNaNCheckWarning); break; } case NAN_CHECK_NEVER: - WarnAboutNaN((conns->Size(conns) > 0) ? LOG_ERROR : LOG_WARNING, - info, time, &out->data->countNaNCheckWarning, &out->data->maxNumNaNCheckWarning); + WarnAboutNaN((conns->numConnections > 0) ? LOG_ERROR : LOG_WARNING, + info, time, &out->data.countNaNCheckWarning, &out->data.maxNumNaNCheckWarning); break; } } @@ -865,22 +1058,25 @@ static McxStatus ChannelOutUpdate(Channel * channel, TimeInterval * time) { } static void ChannelOutDestructor(ChannelOut * out) { - object_destroy(out->data); + ChannelOutDataDestructor(&out->data); } static ChannelOut * ChannelOutCreate(ChannelOut * out) { Channel * channel = (Channel *) out; + McxStatus retVal = RETURN_OK; - out->data = (ChannelOutData *) object_create(ChannelOutData); - if (!out->data) { + retVal = ChannelOutDataInit(&out->data); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "ChannelOutCreate: ChannelOutDataInit failed"); return NULL; } // virtual functions channel->GetValueReference = ChannelOutGetValueReference; - channel->IsValid = ChannelOutIsValid; + channel->ProvidesValue = ChannelOutProvidesValue; channel->Update = ChannelOutUpdate; channel->IsConnected = ChannelOutIsConnected; + channel->SetIsFullyConnected = ChannelOutSetIsFullyConnected; out->Setup = ChannelOutSetup; out->RegisterConnection = ChannelOutRegisterConnection; @@ -913,42 +1109,42 @@ static McxStatus ChannelLocalSetup(ChannelLocal * local, ChannelInfo * info) { } static const void * ChannelLocalGetValueReference(Channel * channel) { - return channel->data->internalValue; + return channel->internalValue; } static McxStatus ChannelLocalUpdate(Channel * channel, TimeInterval * time) { return RETURN_OK; } -static int ChannelLocalIsValid(Channel * channel) { - return (channel->data->internalValue != NULL); +static int ChannelLocalProvidesValue(Channel * channel) { + return (channel->internalValue != NULL); } // TODO: Unify with ChannelOutsetReference (similar code) static McxStatus ChannelLocalSetReference(ChannelLocal * local, const void * reference, - ChannelType type) { + ChannelType * type) { Channel * channel = (Channel *) local; ChannelInfo * info = NULL; - info = channel->GetInfo(channel); + info = &channel->info; if (!info) { mcx_log(LOG_ERROR, "Port: Set local value reference: Port not set up"); return RETURN_ERROR; } - if (channel->data->internalValue - && !(info->defaultValue && channel->data->internalValue == ChannelValueReference(info->defaultValue))) { - mcx_log(LOG_ERROR, "Port %s: Set local value reference: Reference already set", info->GetLogName(info)); + if (channel->internalValue + && !(info->defaultValue && channel->internalValue == ChannelValueDataPointer(info->defaultValue))) { + mcx_log(LOG_ERROR, "Port %s: Set local value reference: Reference already set", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - if (CHANNEL_UNKNOWN != type) { - if (info->GetType(info) != type) { - mcx_log(LOG_ERROR, "Port %s: Set local value reference: Mismatching types", info->GetLogName(info)); + if (ChannelTypeIsValid(type)) { + if (!ChannelTypeEq(info->type, type)) { + mcx_log(LOG_ERROR, "Port %s: Set local value reference: Mismatching types", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } - channel->data->internalValue = reference; + channel->internalValue = reference; return RETURN_OK; } @@ -968,9 +1164,9 @@ static ChannelLocal * ChannelLocalCreate(ChannelLocal * local) { // virtual functions channel->GetValueReference = ChannelLocalGetValueReference; channel->Update = ChannelLocalUpdate; - channel->IsValid = ChannelLocalIsValid; + channel->ProvidesValue = ChannelLocalProvidesValue; - channel->IsConnected = ChannelLocalIsValid; + channel->IsConnected = ChannelLocalProvidesValue; local->Setup = ChannelLocalSetup; local->SetReference = ChannelLocalSetReference; diff --git a/src/core/channels/Channel.h b/src/core/channels/Channel.h index 2b394f8..7b53d95 100644 --- a/src/core/channels/Channel.h +++ b/src/core/channels/Channel.h @@ -12,6 +12,12 @@ #define MCX_CORE_CHANNELS_CHANNEL_H #include "CentralParts.h" +#include "core/channels/ChannelInfo.h" +#include "core/channels/ChannelValueReference.h" +#include "objects/ObjectContainer.h" +#include "objects/Vector.h" +#include "core/connections/Connection.h" +#include "core/Conversion.h" #ifdef __cplusplus extern "C" { @@ -19,11 +25,7 @@ extern "C" { struct Config; struct Component; -struct ChannelInfo; -struct ChannelData; -struct ChannelInData; -struct ChannelOutData; struct Connection; @@ -38,12 +40,14 @@ typedef int (* fChannelIsValid)(Channel * channel); typedef int (* fChannelIsConnected)(Channel * channel); +typedef int (* fChannelIsFullyConnected)(Channel * channel); + +typedef McxStatus (* fChannelSetIsFullyConnected)(Channel * channel); + typedef int (* fChannelIsDefinedDuringInit)(Channel * channel); typedef void (* fChannelSetDefinedDuringInit)(Channel * channel); -typedef struct ChannelInfo * (* fChannelGetInfo)(Channel * channel); - typedef McxStatus (* fChannelSetup)(Channel * channel, struct ChannelInfo * info); typedef McxStatus (* fChannelUpdate)(Channel * channel, TimeInterval * time); @@ -53,6 +57,18 @@ extern const struct ObjectClass _Channel; struct Channel { Object _; // base class + ChannelInfo info; + + // ---------------------------------------------------------------------- + // Value + + // NOTE: This flag gets set if there is a defined value for the + // channel during initialization. + int isDefinedDuringInit; + + const void * internalValue; + ChannelValue value; + /** * Virtual method. * @@ -68,23 +84,28 @@ struct Channel { */ fChannelUpdate Update; - /** - * Return info struct of channel. - */ - fChannelGetInfo GetInfo; - /** * Virtual method. * * Returns true if a channel provides a value (connected or default value) */ - fChannelIsValid IsValid; + fChannelIsValid ProvidesValue; /** - * Returns true if a channel is connected + * Returns true if a channel is connected (i.e., atleast one element of the channel) */ fChannelIsConnected IsConnected; + /** + * Returns true if all elements of the channel are connected + */ + fChannelIsFullyConnected IsFullyConnected; + + /** + * Set the isFullyConnected member to reflect whether all elements of the channel are connected + */ + fChannelSetIsFullyConnected SetIsFullyConnected; + /** * Getter for the flag data->isDefinedDuringInit */ @@ -99,7 +120,15 @@ struct Channel { */ fChannelSetup Setup; - struct ChannelData * data; + /** + * Flag storing whether channel is fully connected + * Do not use this directly, but via the member function `IsFullyConnected` + */ + enum { + INVALID_CONNECTION_STATUS = -1, + CHANNEL_ONLY_PARTIALLY_CONNETED = 0, + CHANNEL_FULLY_CONNECTED = 1 + } isFullyConnected_; }; // ---------------------------------------------------------------------- @@ -107,20 +136,49 @@ struct Channel { typedef struct ChannelIn ChannelIn; +typedef struct ConnectionList { + Connection * * connections; // connections (non-overlapping) going into the channel + size_t numConnections; + size_t capacity; +} ConnectionList; + +// object that is stored in target component that stores the channel connection +typedef struct ChannelInData { + + ConnectionList connList; + size_t increment; + + // references to non-overlapping parts of ChannelData::value, where + // values gotten from connections are going to be stored + ChannelValueReference * * valueReferences; + + // ---------------------------------------------------------------------- + // Conversions + struct LinearConversion * linearConversion; + struct RangeConversion * rangeConversion; + TypeConversion * * typeConversions; // conversion objects (or NULL) for each connection in `connections` + UnitConversion * * unitConversions; // conversion objects (or NULL) for each connection in `connections` + + // ---------------------------------------------------------------------- + // Storage in Component + + int isDiscrete; + + void * reference; + ChannelType * type; +} ChannelInData; + typedef McxStatus (* fChannelInSetup)(ChannelIn * in, struct ChannelInfo * info); typedef McxStatus (* fChannelInSetReference) (ChannelIn * in, void * reference, - ChannelType type); + ChannelType * type); -typedef struct ConnectionInfo * (* fChannelInGetConnectionInfo)(ChannelIn * in); +typedef struct Vector * (* fChannelInGetConnectionInfos)(ChannelIn * in); -typedef struct Connection * (* fChannelInGetConnection)(ChannelIn * in); +typedef ConnectionList * (* fChannelInGetConnections)(ChannelIn * in); -typedef McxStatus (* fChannelInSetConnection)(ChannelIn * in, - struct Connection * connection, - const char * unit, - ChannelType type); +typedef McxStatus (*fChannelInRegisterConnection)(ChannelIn * in, struct Connection * connection, const char * unit, ChannelType * type); typedef int (*fChannelInIsDiscrete)(ChannelIn * in); typedef void (*fChannelInSetDiscrete)(ChannelIn * in); @@ -148,15 +206,15 @@ struct ChannelIn { /** * Returns the ConnectionInfo of the incoming connection. */ - fChannelInGetConnectionInfo GetConnectionInfo; + fChannelInGetConnectionInfos GetConnectionInfos; - fChannelInGetConnection GetConnection; + fChannelInGetConnections GetConnections; /** * Set the connection from which the channel retrieves the values in the * specified unit. */ - fChannelInSetConnection SetConnection; + fChannelInRegisterConnection RegisterConnection; /** * Returns true if a channel value is discrete @@ -168,7 +226,7 @@ struct ChannelIn { */ fChannelInSetDiscrete SetDiscrete; - struct ChannelInData * data; + ChannelInData data; }; @@ -176,23 +234,57 @@ struct ChannelIn { // ChannelOut typedef struct ChannelOut ChannelOut; +// object that is provided to consumer of output channel +typedef struct ChannelOutData { + + // Function pointer that provides the value of the channel when called + const proc * valueFunction; + + // Used to store results of channel-internal valueFunction calls + ChannelValue valueFunctionRes; + + // ---------------------------------------------------------------------- + // Conversion + + struct RangeConversion * rangeConversion; + struct LinearConversion * linearConversion; + + int rangeConversionIsActive; + + // ---------------------------------------------------------------------- + // NaN Handling + + NaNCheckLevel nanCheck; + + size_t countNaNCheckWarning; + size_t maxNumNaNCheckWarning; + + // ---------------------------------------------------------------------- + // Connections to Consumers + + // A list of all input channels that are connected to this output channel + ConnectionList connList; + size_t increment; + +} ChannelOutData; + typedef McxStatus (* fChannelOutSetup)(ChannelOut * out, struct ChannelInfo * info, struct Config * config); typedef McxStatus (* fChannelOutSetReference) (ChannelOut * out, const void * reference, - ChannelType type); + ChannelType * type); typedef McxStatus (* fChannelOutSetReferenceFunction) (ChannelOut * out, const proc * reference, - ChannelType type); + ChannelType * type); typedef McxStatus (* fChannelOutRegisterConnection)(struct ChannelOut * out, struct Connection * connection); typedef const proc * (* fChannelOutGetFunction)(ChannelOut * out); -typedef ObjectContainer * (* fChannelOutGetConnections)(ChannelOut * out); +typedef ConnectionList * (* fChannelOutGetConnections)(ChannelOut * out); extern const struct ObjectClass _ChannelOut; @@ -239,7 +331,7 @@ struct ChannelOut { */ fChannelOutGetConnections GetConnections; - struct ChannelOutData * data; + ChannelOutData data; }; // ---------------------------------------------------------------------- @@ -250,7 +342,7 @@ typedef McxStatus (* fChannelLocalSetup)(ChannelLocal * local, struct ChannelInf typedef McxStatus (* fChannelLocalSetReference) (ChannelLocal * local, const void * reference, - ChannelType type); + ChannelType * type); extern const struct ObjectClass _ChannelLocal; diff --git a/src/core/channels/ChannelDimension.c b/src/core/channels/ChannelDimension.c new file mode 100644 index 0000000..9596e61 --- /dev/null +++ b/src/core/channels/ChannelDimension.c @@ -0,0 +1,331 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include "core/channels/ChannelDimension.h" + +#include "util/stdlib.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +McxStatus ChannelDimensionSetup(ChannelDimension * dimension, size_t num) { + dimension->num = num; + + dimension->startIdxs = (size_t *) mcx_calloc(dimension->num, sizeof(size_t)); + if (!dimension->startIdxs) { + goto error_cleanup; + } + dimension->endIdxs = (size_t *) mcx_calloc(dimension->num, sizeof(size_t)); + if (!dimension->endIdxs) { + goto error_cleanup; + } + + return RETURN_OK; + +error_cleanup: + if (dimension->startIdxs) { mcx_free(dimension->startIdxs); } + if (dimension->endIdxs) { mcx_free(dimension->endIdxs); } + + return RETURN_ERROR; +} + +McxStatus ChannelDimensionSetDimension(ChannelDimension * dimension, size_t dim, size_t start, size_t end) { + if (dim > dimension->num) { + return RETURN_ERROR; + } + + dimension->startIdxs[dim] = start; + dimension->endIdxs[dim] = end; + + return RETURN_OK; +} + +size_t ChannelDimensionNumElements(const ChannelDimension * dimension) { + size_t i = 0; + size_t n = 1; + + if (dimension->num == 0) { + return 0; + } + + for (i = 0; i < dimension->num; i++) { + n *= (dimension->endIdxs[i] - dimension->startIdxs[i] + 1); + } + + return n; +} + +ChannelDimension * CloneChannelDimension(const ChannelDimension * dimension) { + ChannelDimension * clone = NULL; + McxStatus retVal = RETURN_OK; + size_t i = 0; + + if (!dimension) { + return NULL; + } + + clone = MakeChannelDimension(); + if (!clone) { + mcx_log(LOG_ERROR, "CloneChannelDimension: Not enough memory"); + return NULL; + } + + retVal = ChannelDimensionSetup(clone, dimension->num); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "CloneChannelDimension: Channel dimension setup failed"); + goto cleanup; + } + + for (i = 0; i < dimension->num; i++) { + retVal = ChannelDimensionSetDimension(clone, i, dimension->startIdxs[i], dimension->endIdxs[i]); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "CloneChannelDimension: Channel dimension %zu set failed", i); + goto cleanup; + } + } + + return clone; + +cleanup: + object_destroy(clone); + return NULL; +} + +int ChannelDimensionEq(const ChannelDimension * first, const ChannelDimension * second) { + size_t i = 0; + + if (!first && !second) { + return TRUE; + } else if (!first || !second) { + return FALSE; + } + + if (first->num != second->num) { + return FALSE; + } + + for (i = 0; i < first->num; i++) { + if (first->startIdxs[i] != second->startIdxs[i] || first->endIdxs[i] != second->endIdxs[i]) { + return FALSE; + } + } + + return TRUE; +} + +int ChannelDimensionConformsToDimension(const ChannelDimension * first, const ChannelDimension * second) { + size_t i = 0; + + if (!first && !second) { + return TRUE; + } else if (!first || !second) { + return FALSE; + } + + if (first->num != second->num) { + return FALSE; + } + + for (i = 0; i < first->num; i++) { + if (first->endIdxs[i] - first->startIdxs[i] != second->endIdxs[i] - second->startIdxs[i]) { + return FALSE; + } + } + + return TRUE; +} + +int ChannelDimensionConformsTo(const ChannelDimension * dimension, const size_t * dims, size_t numDims) { + size_t i = 0; + if (dimension->num != numDims) { + return 0; + } + + for (i = 0; i < numDims; i++) { + if (dims[i] != (dimension->endIdxs[i] - dimension->startIdxs[i] + 1)) { + return 0; + } + } + + return 1; +} + +int ChannelDimensionIncludedIn(const ChannelDimension * first, const ChannelDimension * second) { + size_t i = 0; + + if (!first && !second) { + return TRUE; + } else if (!first || !second) { + return FALSE; + } + + if (first->num != second->num) { + return FALSE; // only same number of dimensions is comparable + } + + for (i = 0; i < first->num; i++) { + if (first->startIdxs[i] < second->startIdxs[i] || first->startIdxs[i] > second->endIdxs[i]) { + return FALSE; + } + + if (first->endIdxs[i] > second->endIdxs[i] || first->endIdxs[i] < second->startIdxs[i]) { + return FALSE; + } + } + + return TRUE; +} + +size_t ChannelDimensionGetIndex(const ChannelDimension * dimension, size_t elem_idx, const size_t * sizes) { + switch (dimension->num) { + case 1: + { + size_t idx = dimension->startIdxs[0] + elem_idx; + if (idx > dimension->endIdxs[0]) { + mcx_log(LOG_ERROR, "ChannelDimensionGetIndex: Index out of range"); + break; + } + + return idx; + } + case 2: + { + size_t dim_1_slice_size = dimension->endIdxs[1] - dimension->startIdxs[1] + 1; + + size_t slice_idx_0 = elem_idx / dim_1_slice_size + dimension->startIdxs[0]; + size_t slice_idx_1 = elem_idx % dim_1_slice_size + dimension->startIdxs[1]; + + if (slice_idx_0 > dimension->endIdxs[0] || slice_idx_1 > dimension->endIdxs[1]) { + mcx_log(LOG_ERROR, "ChannelDimensionGetIndex: Index out of range"); + break; + } + + return slice_idx_0 * sizes[1] + slice_idx_1; + } + default: + mcx_log(LOG_ERROR, "ChannelDimensionGetIndex: Number of dimensions not supported (%zu)", dimension->num); + break; + } + + return (size_t) -1; +} + +size_t ChannelDimensionGetSliceIndex(const ChannelDimension * dimension, size_t slice_idx, const size_t * dims) { + switch (dimension->num) { + case 1: + { + size_t idx = slice_idx - dimension->startIdxs[0]; + if (idx > dimension->endIdxs[0]) { + mcx_log(LOG_ERROR, "ChannelDimensionGetSliceIndex: Index out of range"); + break; + } + + return idx; + } + case 2: + { + size_t idx_0 = slice_idx / dims[1]; + size_t idx_1 = slice_idx - idx_0 * dims[1]; + + size_t slice_idx_0 = idx_0 - dimension->startIdxs[0]; + size_t slice_idx_1 = idx_1 - dimension->startIdxs[1]; + + size_t dim_1_slice_size = dimension->endIdxs[1] - dimension->startIdxs[1] + 1; + + return slice_idx_0 * dim_1_slice_size + slice_idx_1; + } + default: + mcx_log(LOG_ERROR, "ChannelDimensionGetSliceIndex: Number of dimensions not supported (%zu)", dimension->num); + break; + } + + return (size_t) -1; +} + +char * ChannelDimensionString(const ChannelDimension * dimension) { + char * str = NULL; + size_t length = 0; + size_t i = 0; + int n = 0; + + if (!dimension) { + return NULL; + } + + for (i = 0; i < dimension->num; i++) { + length += 1; // '(' + length += mcx_digits10(dimension->startIdxs[i]); // a + length += 2; // ', ' + length += mcx_digits10(dimension->endIdxs[i]); // b + length += 1; // ')' + } + + length += dimension->num - 1; // spaces between dimensions + length += 2; // '[' at the beginning and ']' at the end + length += 1; // '\0' + + str = (char *) mcx_calloc(sizeof(char), length); + if (!str) { + mcx_log(LOG_ERROR, "ChannelDimensionString: Not enough memory"); + return NULL; + } + + n += sprintf(str, "["); + for (i = 0; i < dimension->num; i++) { + if (i > 0) { + n += sprintf(str + n, " "); + } + n += sprintf(str + n, "(%zu, %zu)", dimension->startIdxs[i], dimension->endIdxs[i]); + } + sprintf(str + n, "]"); + + return str; +} + +McxStatus ChannelDimensionAlignIndicesWithZero(ChannelDimension * target, const ChannelDimension * base) { + size_t i = 0; + if (!target && !base) { + return RETURN_OK; + } else if (!target || !base) { + return RETURN_ERROR; + } + + if (target->num != base->num) { + return RETURN_ERROR; + } + + for (i = 0; i < target->num; i++) { + target->endIdxs[i] -= base->startIdxs[i]; + target->startIdxs[i] -= base->startIdxs[i]; + } + + return RETURN_OK; +} + +ChannelDimension * MakeChannelDimension() { + ChannelDimension * dimension = (ChannelDimension *) mcx_calloc(1, sizeof(ChannelDimension)); + + return dimension; +} + +void DestroyChannelDimension(ChannelDimension * dimension) { + if (dimension->startIdxs) { mcx_free(dimension->startIdxs); } + if (dimension->endIdxs) { mcx_free(dimension->endIdxs); } +} + + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ \ No newline at end of file diff --git a/src/core/channels/ChannelDimension.h b/src/core/channels/ChannelDimension.h new file mode 100644 index 0000000..a98d6ef --- /dev/null +++ b/src/core/channels/ChannelDimension.h @@ -0,0 +1,56 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef MCX_CORE_CHANNELS_CHANNEL_DIMENSION_H +#define MCX_CORE_CHANNELS_CHANNEL_DIMENSION_H + +#include "CentralParts.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +typedef struct ChannelDimension { + size_t num; + + size_t * startIdxs; + size_t * endIdxs; +} ChannelDimension; + + +ChannelDimension * MakeChannelDimension(); +ChannelDimension * CloneChannelDimension(const ChannelDimension * dimension); +void DestroyChannelDimension(ChannelDimension * dimension); + +McxStatus ChannelDimensionSetup(ChannelDimension * dimension, size_t num); +McxStatus ChannelDimensionSetDimension(ChannelDimension * dimension, size_t dim, size_t start, size_t end); + +int ChannelDimensionEq(const ChannelDimension * first, const ChannelDimension * second); +int ChannelDimensionConformsToDimension(const ChannelDimension * first, const ChannelDimension * second); +int ChannelDimensionConformsTo(const ChannelDimension * dimension, const size_t * dims, size_t numDims); +int ChannelDimensionIncludedIn(const ChannelDimension * first, const ChannelDimension * second); + +size_t ChannelDimensionNumElements(const ChannelDimension* dimension); +char * ChannelDimensionString(const ChannelDimension * dimension); +size_t ChannelDimensionGetIndex(const ChannelDimension * dimension, size_t elem_idx, const size_t * sizes); +size_t ChannelDimensionGetSliceIndex(const ChannelDimension * dimension, size_t slice_idx, const size_t * dims); + +McxStatus ChannelDimensionAlignIndicesWithZero(ChannelDimension * target, const ChannelDimension * base); + + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ + +#endif // MCX_CORE_CHANNELS_CHANNEL_DIMENSION_H \ No newline at end of file diff --git a/src/core/channels/ChannelInfo.c b/src/core/channels/ChannelInfo.c index 95e5631..ff93130 100644 --- a/src/core/channels/ChannelInfo.c +++ b/src/core/channels/ChannelInfo.c @@ -12,16 +12,16 @@ #include "core/channels/ChannelInfo.h" +#include "core/channels/ChannelValue.h" +#include "objects/Object.h" #include "util/string.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -// ---------------------------------------------------------------------- -// ChannelInfo -static const char * ChannelInfoGetLogName(const ChannelInfo * info) { +const char * ChannelInfoGetLogName(const ChannelInfo * info) { if (info->id) { return info->id; } else { @@ -29,15 +29,7 @@ static const char * ChannelInfoGetLogName(const ChannelInfo * info) { } } -static ChannelType ChannelInfoType(const ChannelInfo * info) { - return info->type; -} - -static ChannelMode ChannelInfoMode(const ChannelInfo * info) { - return info->mode; -} - -static const char * ChannelInfoName(const ChannelInfo * info) { +const char * ChannelInfoGetName(const ChannelInfo * info) { if (info->name) { return info->name; } else { @@ -45,57 +37,11 @@ static const char * ChannelInfoName(const ChannelInfo * info) { } } -static const char * ChannelInfoNameInTool(const ChannelInfo * info) { - return info->nameInTool; +int ChannelInfoIsBinary(const ChannelInfo * info) { + return ChannelTypeIsBinary(info->type); } -static const char * ChannelInfoDescription(const ChannelInfo * info) { - return info->description; -} - -static const char * ChannelInfoID(const ChannelInfo * info) { - return info->id; -} - -static const char * ChannelInfoUnit(const ChannelInfo * info) { - return info->unitString; -} - -static ChannelValue * ChannelGetMin(const ChannelInfo * info) { - return info->min; -} - -static ChannelValue * ChannelGetMax(const ChannelInfo * info) { - return info->max; -} - -static ChannelValue * ChannelInfoGetInitialValue(const ChannelInfo * info) { - return info->initialValue; -} - -static ChannelValue * ChannelInfoScale(const ChannelInfo * info) { - return info->scale; -} - -static ChannelValue * ChannelInfoOffset(const ChannelInfo * info) { - return info->offset; -} - -static ChannelValue * ChannelInfoDefault(const ChannelInfo * info) { - return info->defaultValue; -} - -static int ChannelInfoIsBinary(const ChannelInfo * info) { - return info->type == CHANNEL_BINARY - || info->type == CHANNEL_BINARY_REFERENCE; -} - -static int ChannelInfoGetWriteResultFlag(const ChannelInfo * info) { - return info->writeResult; -} - - -static McxStatus ChannelInfoSetString(char * * dst, const char * src) { +static McxStatus ChannelInfoSetString(char ** dst, const char * src) { if (*dst) { mcx_free(*dst); } @@ -110,256 +56,193 @@ static McxStatus ChannelInfoSetString(char * * dst, const char * src) { return RETURN_OK; } -static McxStatus ChannelInfoSetVector(ChannelInfo * info, VectorChannelInfo * vector) { - if (info->vector) { - object_destroy(info->vector); - } - - info->vector = vector; - - return RETURN_OK; -} - -static McxStatus ChannelInfoSetName(ChannelInfo * info, const char * name) { +McxStatus ChannelInfoSetName(ChannelInfo * info, const char * name) { return ChannelInfoSetString(&info->name, name); } -static McxStatus ChannelInfoSetNameInTool(ChannelInfo * info, const char * name) { +McxStatus ChannelInfoSetNameInTool(ChannelInfo * info, const char * name) { return ChannelInfoSetString(&info->nameInTool, name); } -static McxStatus ChannelInfoSetID(ChannelInfo * info, const char * name) { +McxStatus ChannelInfoSetID(ChannelInfo * info, const char * name) { return ChannelInfoSetString(&info->id, name); } -static McxStatus ChannelInfoSetDescription(ChannelInfo * info, const char * name) { +McxStatus ChannelInfoSetDescription(ChannelInfo * info, const char * name) { return ChannelInfoSetString(&info->description, name); } -static McxStatus ChannelInfoSetUnit(ChannelInfo * info, const char * name) { +McxStatus ChannelInfoSetUnit(ChannelInfo * info, const char * name) { return ChannelInfoSetString(&info->unitString, name); } -static McxStatus ChannelInfoSetType(ChannelInfo * info, ChannelType type) { - if (info->type != CHANNEL_UNKNOWN) { - mcx_log(LOG_ERROR, "Port %s: Type already set", info->GetLogName(info)); +McxStatus ChannelInfoSetType(ChannelInfo * info, ChannelType * type) { + if (ChannelTypeIsValid(info->type)) { + mcx_log(LOG_ERROR, "Port %s: Type already set", ChannelInfoGetLogName(info)); return RETURN_ERROR; } - info->type = type; + info->type = ChannelTypeClone(type); - if (info->IsBinary(info)) { + if (ChannelInfoIsBinary(info)) { // the default for binary is off - info->SetWriteResult(info, FALSE); + info->writeResult = FALSE; } return RETURN_OK; } -static McxStatus ChannelInfoSetMode(ChannelInfo * info, ChannelMode mode) { - info->mode = mode; - - return RETURN_OK; -} - -static McxStatus ChannelInfoSetMin(ChannelInfo * info, ChannelValue * min) { - info->min = min; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetMax(ChannelInfo * info, ChannelValue * max) { - info->max = max; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetScale(ChannelInfo * info, ChannelValue * scale) { - info->scale = scale; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetOffset(ChannelInfo * info, ChannelValue * offset) { - info->offset = offset; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetDefault(ChannelInfo * info, ChannelValue * defaultValue) { - info->defaultValue = defaultValue; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetInitial(ChannelInfo * info, ChannelValue * initialValue) { - info->initialValue = initialValue; - return RETURN_OK; -} - -static McxStatus ChannelInfoSetWriteResult(ChannelInfo * info, int writeResult) { - info->writeResult = writeResult; - return RETURN_OK; -} - - -static void ChannelInfoSet( - ChannelInfo * info, - VectorChannelInfo * vector, - char * name, - char * nameInTool, - char * description, - char * unit, - ChannelType type, - ChannelMode mode, - char * id, - ChannelValue * min, - ChannelValue * max, - ChannelValue * scale, - ChannelValue * offset, - ChannelValue * defaultValue, - ChannelValue * initialValue, - int writeResult) -{ - info->vector = vector; - info->name = name; - info->nameInTool = nameInTool; - info->description = description; - info->unitString = unit; - info->type = type; - info->mode = mode; - info->id = id; - info->min = min; - info->max = max; - info->scale = scale; - info->offset = offset; - info->defaultValue = defaultValue; - info->initialValue = initialValue; - info->writeResult = writeResult; -} - -static void ChannelInfoGet( - const ChannelInfo * info, - VectorChannelInfo ** vector, - char ** name, - char ** nameInTool, - char ** description, - char ** unit, - ChannelType * type, - ChannelMode * mode, - char ** id, - ChannelValue ** min, - ChannelValue ** max, - ChannelValue ** scale, - ChannelValue ** offset, - ChannelValue ** defaultValue, - ChannelValue ** initialValue, - int * writeResult) -{ - * vector = info->vector; - * name = info->name; - * nameInTool = info->nameInTool; - * description = info->description; - * unit = info->unitString; - * type = info->type; - * mode = info->mode; - * id = info->id; - * min = info->min; - * max = info->max; - * scale = info->scale; - * offset = info->offset; - * defaultValue = info->defaultValue; - * initialValue = info->initialValue; - * writeResult = info->writeResult; -} - -static ChannelInfo * ChannelInfoClone(const ChannelInfo * info) { - ChannelInfo * clone = (ChannelInfo *) object_create(ChannelInfo); - - if (!clone) { - return NULL; - } - - if (info->name && !(clone->name = mcx_string_copy(info->name))) { return NULL; } - if (info->nameInTool && !(clone->nameInTool = mcx_string_copy(info->nameInTool))) { return NULL; } - if (info->description && !(clone->description = mcx_string_copy(info->description))) { return NULL; } - if (info->unitString && !(clone->unitString = mcx_string_copy(info->unitString))) { return NULL; } - if (info->id && !(clone->id = mcx_string_copy(info->id))) { return NULL; } - - clone->type = info->type; - clone->mode = info->mode; - - if (info->min) { - if (!(clone->min = ChannelValueClone(info->min))) { return NULL; } +McxStatus ChannelInfoSetup(ChannelInfo * info, + const char * name, + const char * nameInModel, + const char * descr, + const char * unit, + ChannelType * type, + const char * id) { + if (name && RETURN_OK != ChannelInfoSetName(info, name)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set name", name); + return RETURN_ERROR; } - if (info->max) { - if (!(clone->max = ChannelValueClone(info->max))) { return NULL; } + if (nameInModel && RETURN_OK != ChannelInfoSetNameInTool(info, nameInModel)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set name in tool", name); + return RETURN_ERROR; } - if (info->scale) { - if (!(clone->scale = ChannelValueClone(info->scale))) { return NULL; } + if (descr && RETURN_OK != ChannelInfoSetDescription(info, descr)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set description", name); + return RETURN_ERROR; } - if (info->offset) { - if (!(clone->offset = ChannelValueClone(info->offset))) { return NULL; } + if (unit && RETURN_OK != ChannelInfoSetUnit(info, unit)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set unit", name); + return RETURN_ERROR; } - if (info->defaultValue) { - if (!(clone->defaultValue = ChannelValueClone(info->defaultValue))) { return NULL; } + if (id && RETURN_OK != ChannelInfoSetID(info, id)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set ID", name); + return RETURN_ERROR; } - if (info->initialValue) { - if (!(clone->initialValue = ChannelValueClone(info->initialValue))) { return NULL; } + if (RETURN_OK != ChannelInfoSetType(info, type)) { + mcx_log(LOG_DEBUG, "Port %s: Could not set type", name); + return RETURN_ERROR; } - clone->writeResult = info->writeResult; - - return clone; + return RETURN_OK; } -static ChannelInfo * ChannelInfoCopy( - const ChannelInfo * info, - char * name, - char * nameInTool, - char * id) { - - ChannelInfo * copy = info->Clone(info); - - if (!copy) { - return NULL; +static void FreeChannelValue(ChannelValue ** value) { + if (*value) { + ChannelValueDestructor(*value); + mcx_free(*value); + *value = NULL; } - - copy->SetName(copy, name); - copy->SetNameInTool(copy, nameInTool); - copy->SetID(copy, id); - - return copy; } -static McxStatus ChannelInfoInit(ChannelInfo * info, - const char * name, - const char * descr, - const char * unit, - ChannelType type, - const char * id) { +McxStatus ChannelInfoSetFrom(ChannelInfo * info, const ChannelInfo * other) { + McxStatus retVal = RETURN_OK; - - if (name && RETURN_OK != info->SetName(info, name)) { - mcx_log(LOG_DEBUG, "Port %s: Could not set name", name); + retVal = ChannelInfoSetName(info, other->name); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set name"); return RETURN_ERROR; } - if (descr && RETURN_OK != info->SetDescription(info, descr)) { - mcx_log(LOG_DEBUG, "Port %s: Could not set description", name); + + retVal = ChannelInfoSetNameInTool(info, other->nameInTool); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set name in model"); return RETURN_ERROR; } - if (unit && RETURN_OK != info->SetUnit(info, unit)) { - mcx_log(LOG_DEBUG, "Port %s: Could not set unit", name); + + retVal = ChannelInfoSetDescription(info, other->description); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set description"); return RETURN_ERROR; } - if (id && RETURN_OK != info->SetID(info, id)) { - mcx_log(LOG_DEBUG, "Port %s: Could not set ID", name); + + retVal = ChannelInfoSetUnit(info, other->unitString); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set unit"); return RETURN_ERROR; } - if (RETURN_OK != info->SetType(info, type)) { - mcx_log(LOG_DEBUG, "Port %s: Could not set type", name); + + retVal = ChannelInfoSetID(info, other->id); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set name"); return RETURN_ERROR; } + info->type = ChannelTypeClone(other->type); + info->mode = other->mode; + info->writeResult = other->writeResult; + info->connected = other->connected; + info->initialValueIsExact = other->initialValueIsExact; + + info->channel = other->channel; // weak reference + + FreeChannelValue(&info->min); + FreeChannelValue(&info->max); + FreeChannelValue(&info->scale); + FreeChannelValue(&info->offset); + FreeChannelValue(&info->defaultValue); + FreeChannelValue(&info->initialValue); + + if (other->min) { + info->min = ChannelValueClone(other->min); + if (!info->min) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set min"); + return RETURN_ERROR; + } + } + + if (other->max) { + info->max = ChannelValueClone(other->max); + if (!info->max) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set max"); + return RETURN_ERROR; + } + } + + if (other->scale) { + info->scale = ChannelValueClone(other->scale); + if (!info->scale) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set scale"); + return RETURN_ERROR; + } + } + + if (other->offset) { + info->offset = ChannelValueClone(other->offset); + if (!info->offset) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set offset"); + return RETURN_ERROR; + } + } + + if (other->defaultValue) { + info->defaultValue = ChannelValueClone(other->defaultValue); + if (!info->defaultValue) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set default value"); + return RETURN_ERROR; + } + } + + if (other->initialValue) { + info->initialValue = ChannelValueClone(other->initialValue); + if (!info->initialValue) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set initial value"); + return RETURN_ERROR; + } + } + + object_destroy(info->dimension); + if (other->dimension) { + info->dimension = CloneChannelDimension(other->dimension); + if (!info->dimension) { + mcx_log(LOG_ERROR, "ChannelInfoSetFrom: Failed to set dimension"); + return RETURN_ERROR; + } + } + return RETURN_OK; } - static void FreeStr(char ** str) { if (*str) { mcx_free(*str); @@ -367,76 +250,37 @@ static void FreeStr(char ** str) { } } -static void ChannelInfoDestructor(ChannelInfo * info) { +void ChannelInfoDestroy(ChannelInfo * info) { FreeStr(&info->name); FreeStr(&info->nameInTool); FreeStr(&info->description); FreeStr(&info->unitString); FreeStr(&info->id); - if (info->defaultValue) { - ChannelValueDestructor(info->defaultValue); - mcx_free(info->defaultValue); - info->defaultValue = NULL; - } - if (info->initialValue) { - ChannelValueDestructor(info->initialValue); - mcx_free(info->initialValue); - info->initialValue = NULL; - } - if (info->vector) { - object_destroy(info->vector); - } -} - -static ChannelInfo * ChannelInfoCreate(ChannelInfo * info) { - info->Set = ChannelInfoSet; - info->Get = ChannelInfoGet; - info->Clone = ChannelInfoClone; - info->Copy = ChannelInfoCopy; - - info->Init = ChannelInfoInit; - - info->SetVector = ChannelInfoSetVector; - info->SetName = ChannelInfoSetName; - info->SetNameInTool = ChannelInfoSetNameInTool; - info->SetID = ChannelInfoSetID; - info->SetDescription = ChannelInfoSetDescription; - info->SetUnit = ChannelInfoSetUnit; - info->SetType = ChannelInfoSetType; - info->SetMode = ChannelInfoSetMode; - - info->SetMin = ChannelInfoSetMin; - info->SetMax = ChannelInfoSetMax; - info->SetScale = ChannelInfoSetScale; - info->SetOffset = ChannelInfoSetOffset; - info->SetDefault = ChannelInfoSetDefault; - info->SetInitial = ChannelInfoSetInitial; - info->SetWriteResult = ChannelInfoSetWriteResult; - - info->GetType = ChannelInfoType; - info->GetMode = ChannelInfoMode; - info->GetName = ChannelInfoName; - info->GetNameInTool = ChannelInfoNameInTool; - info->GetDescription = ChannelInfoDescription; - info->GetID = ChannelInfoID; - info->GetUnit = ChannelInfoUnit; - info->GetMin = ChannelGetMin; - info->GetMax = ChannelGetMax; - - info->GetInitialValue = ChannelInfoGetInitialValue; - - info->GetScale = ChannelInfoScale; - info->GetOffset = ChannelInfoOffset; - info->GetDefault = ChannelInfoDefault; + FreeChannelValue(&info->min); + FreeChannelValue(&info->max); + FreeChannelValue(&info->scale); + FreeChannelValue(&info->offset); + FreeChannelValue(&info->defaultValue); + FreeChannelValue(&info->initialValue); - info->IsBinary = ChannelInfoIsBinary; + if (info->type) { + ChannelTypeDestructor(info->type); + } - info->GetWriteResultFlag = ChannelInfoGetWriteResultFlag; + if (info->dimension) { + object_destroy(info->dimension); + } - info->GetLogName = ChannelInfoGetLogName; + info->channel = NULL; + info->initialValueIsExact = FALSE; + info->type = ChannelTypeClone(&ChannelTypeUnknown); + info->connected = FALSE; + info->writeResult = TRUE; +} - info->vector = NULL; +McxStatus ChannelInfoInit(ChannelInfo * info) { + info->dimension = NULL; info->name = NULL; info->nameInTool = NULL; @@ -453,7 +297,7 @@ static ChannelInfo * ChannelInfoCreate(ChannelInfo * info) { info->scale = NULL; info->offset = NULL; - info->type = CHANNEL_UNKNOWN; + info->type = ChannelTypeClone(&ChannelTypeUnknown); info->defaultValue = NULL; info->initialValue = NULL; @@ -461,10 +305,9 @@ static ChannelInfo * ChannelInfoCreate(ChannelInfo * info) { info->channel = NULL; - return info; + return RETURN_OK; } -OBJECT_CLASS(ChannelInfo, Object); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/channels/ChannelInfo.h b/src/core/channels/ChannelInfo.h index 1980034..adad36d 100644 --- a/src/core/channels/ChannelInfo.h +++ b/src/core/channels/ChannelInfo.h @@ -11,174 +11,76 @@ #ifndef MCX_CORE_CHANNELS_CHANNELINFO_H #define MCX_CORE_CHANNELS_CHANNELINFO_H +#include "core/channels/ChannelValue.h" #include "CentralParts.h" -#include "core/channels/VectorChannelInfo.h" +#include "core/channels/ChannelDimension.h" + +#include "common/status.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -// ---------------------------------------------------------------------- -// ChannelInfo -typedef struct ChannelInfo ChannelInfo; -typedef struct VectorChannelInfo VectorChannelInfo; -typedef struct Channel Channel; - -extern const struct ObjectClass _ChannelInfo; - -typedef void (* fChannelInfoSet)( - ChannelInfo * info, - struct VectorChannelInfo * vector, - char * name, - char * nameInTool, - char * description, - char * unit, - ChannelType type, - ChannelMode mode, - char * id, - ChannelValue * min, - ChannelValue * max, - ChannelValue * scale, - ChannelValue * offset, - ChannelValue * defaultValue, - ChannelValue * initialValue, - int writeResult); - -typedef void (* fChannelInfoGet)( - const ChannelInfo * info, - struct VectorChannelInfo ** vector, - char ** name, - char ** nameInTool, - char ** description, - char ** unit, - ChannelType * type, - ChannelMode * mode, - char ** id, - ChannelValue ** min, - ChannelValue ** max, - ChannelValue ** scale, - ChannelValue ** offset, - ChannelValue ** defaultValue, - ChannelValue ** initialValue, - int * writeResult); - -typedef ChannelInfo * (* fChannelInfoCopy)( - const ChannelInfo * info, - char * name, - char * nameInTool, - char * id); - -typedef McxStatus (* fChannelInfoInit)( - ChannelInfo * info, - const char * name, - const char * descr, - const char * unit, - ChannelType type, - const char * id); - -typedef ChannelInfo * (* fChannelInfoClone)(const ChannelInfo * info); - -typedef ChannelType (* fChannelInfoGetType)(const ChannelInfo * info); -typedef ChannelMode (* fChannelInfoGetMode)(const ChannelInfo * info); - -typedef McxStatus (* fChannelInfoSetDouble)(ChannelInfo * info, double val); -typedef McxStatus (* fChannelInfoSetInt)(ChannelInfo * info, int val); -typedef McxStatus (* fChannelInfoSetBool)(ChannelInfo * info, int val); -typedef McxStatus (* fChannelInfoSetChannelValue)(ChannelInfo * info, ChannelValue * val); -typedef ChannelValue * (* fChannelInfoGetChannelValue)(const ChannelInfo * info); - -typedef const char * (* fChannelInfoGetString)(const ChannelInfo * info); -typedef McxStatus (* fChannelInfoSetString)(ChannelInfo * info, const char * str); -typedef McxStatus (* fChannelInfoSetChannelType)(ChannelInfo * info, ChannelType type); -typedef McxStatus (* fChannelInfoSetChannelMode)(ChannelInfo * info, ChannelMode mode); -typedef McxStatus (* fChannelInfoSetVector)(ChannelInfo * info, VectorChannelInfo * vector); - -typedef ChannelValue * (* fChannelInfoGetInitialValue)(const ChannelInfo * info); - -typedef int (* fChannelInfoGetInt)(const ChannelInfo * info); - -struct ChannelInfo { - Object _; // base class - - fChannelInfoSet Set; - fChannelInfoGet Get; - fChannelInfoClone Clone; - fChannelInfoCopy Copy; - - fChannelInfoInit Init; - - fChannelInfoSetVector SetVector; - fChannelInfoSetString SetName; - fChannelInfoSetString SetNameInTool; - fChannelInfoSetString SetID; - fChannelInfoSetString SetDescription; - fChannelInfoSetString SetUnit; - - fChannelInfoSetChannelValue SetMin; - fChannelInfoSetChannelValue SetMax; - fChannelInfoSetChannelValue SetScale; - fChannelInfoSetChannelValue SetOffset; - - fChannelInfoSetChannelValue SetDefault; - fChannelInfoSetChannelValue SetInitial; - - fChannelInfoSetBool SetWriteResult; - - fChannelInfoSetChannelType SetType; - fChannelInfoSetChannelMode SetMode; - - fChannelInfoGetType GetType; - fChannelInfoGetMode GetMode; - fChannelInfoGetString GetName; - fChannelInfoGetString GetNameInTool; - fChannelInfoGetString GetDescription; - fChannelInfoGetString GetID; - fChannelInfoGetString GetUnit; - - fChannelInfoGetInt IsBinary; - - fChannelInfoGetInt GetWriteResultFlag; - - fChannelInfoGetInitialValue GetInitialValue; - - fChannelInfoGetChannelValue GetMin; - fChannelInfoGetChannelValue GetMax; - fChannelInfoGetChannelValue GetScale; - fChannelInfoGetChannelValue GetOffset; - fChannelInfoGetChannelValue GetDefault; - - fChannelInfoGetString GetLogName; - - /* vector must be NULL if this is a scalar. It is the *only* way - * to distinguish between vectors of size 1 and scalar values. - */ - struct VectorChannelInfo * vector; + + +typedef struct ChannelInfo { + struct Channel * channel; + + // Channel is a scalar iff dimension == NULL + ChannelDimension * dimension; char * name; + char * nameInTool; char * description; char * unitString; - ChannelMode mode; char * id; - ChannelValue * min; - ChannelValue * max; + ChannelMode mode; int writeResult; - char * nameInTool; - - int connected; + ChannelValue * min; + ChannelValue * max; + ChannelValue * scale; + ChannelValue * offset; - ChannelType type; ChannelValue * defaultValue; ChannelValue * initialValue; + ChannelType * type; + + int connected; int initialValueIsExact; +} ChannelInfo; + + +McxStatus ChannelInfoInit(ChannelInfo * info); +void ChannelInfoDestroy(ChannelInfo * info); + + +const char * ChannelInfoGetLogName(const ChannelInfo * info); +const char * ChannelInfoGetName(const ChannelInfo * info); + +McxStatus ChannelInfoSetName(ChannelInfo * info, const char * name); +McxStatus ChannelInfoSetNameInTool(ChannelInfo * info, const char * name); +McxStatus ChannelInfoSetID(ChannelInfo * info, const char * name); +McxStatus ChannelInfoSetDescription(ChannelInfo * info, const char * name); +McxStatus ChannelInfoSetUnit(ChannelInfo * info, const char * name); +McxStatus ChannelInfoSetType(ChannelInfo * info, ChannelType * type); + +int ChannelInfoIsBinary(const ChannelInfo * info); + +McxStatus ChannelInfoSetup(ChannelInfo * info, + const char * name, + const char * nameInModel, + const char * descr, + const char * unit, + ChannelType * type, + const char * id); + +McxStatus ChannelInfoSetFrom(ChannelInfo * info, const ChannelInfo * other); - ChannelValue * scale; - ChannelValue * offset; - struct Channel * channel; -}; #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/channels/ChannelValue.c b/src/core/channels/ChannelValue.c index e172227..9386b73 100644 --- a/src/core/channels/ChannelValue.c +++ b/src/core/channels/ChannelValue.c @@ -9,35 +9,517 @@ ********************************************************************************/ #include "core/channels/ChannelValue.h" +#include "core/channels/ChannelDimension.h" #include "util/stdlib.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -void ChannelValueInit(ChannelValue * value, ChannelType type) { +ChannelType ChannelTypeUnknown = { CHANNEL_UNKNOWN, NULL}; +ChannelType ChannelTypeInteger = { CHANNEL_INTEGER, NULL}; +ChannelType ChannelTypeDouble = { CHANNEL_DOUBLE, NULL}; +ChannelType ChannelTypeBool = { CHANNEL_BOOL, NULL}; +ChannelType ChannelTypeString = { CHANNEL_STRING, NULL}; +ChannelType ChannelTypeBinary = { CHANNEL_BINARY, NULL}; +ChannelType ChannelTypeBinaryReference = { CHANNEL_BINARY_REFERENCE, NULL}; + + +char * CreateIndexedName(const char * name, unsigned i) { + size_t len = 0; + char * buffer = NULL; + + len = strlen(name) + (mcx_digits10(i) + 1) + 2 + 1; + + buffer = (char *) mcx_calloc(len, sizeof(char)); + if (!buffer) { + return NULL; + } + + snprintf(buffer, len, "%s[%d]", name, i); + + return buffer; +} + + +ChannelType * ChannelTypeClone(ChannelType * type) { + switch (type->con) { + case CHANNEL_UNKNOWN: + case CHANNEL_INTEGER: + case CHANNEL_DOUBLE: + case CHANNEL_BOOL: + case CHANNEL_STRING: + case CHANNEL_BINARY: + case CHANNEL_BINARY_REFERENCE: + // Scalar types are used statically (&ChannelTypeDouble, etc) + return type; + case CHANNEL_ARRAY: { + ChannelType * clone = (ChannelType *) mcx_calloc(sizeof(ChannelType), 1); + if (!clone) { return NULL; } + + clone->con = type->con; + + clone->ty.a.inner = ChannelTypeClone(type->ty.a.inner); + clone->ty.a.numDims = type->ty.a.numDims; + clone->ty.a.dims = mcx_copy(type->ty.a.dims, sizeof(size_t) * type->ty.a.numDims); + if (!clone->ty.a.dims) { + mcx_free(clone); + return NULL; + } + + return clone; + } + } + + return NULL; +} + +void ChannelTypeDestructor(ChannelType * type) { + if (&ChannelTypeUnknown == type) { } + else if (&ChannelTypeInteger == type) { } + else if (&ChannelTypeDouble == type) { } + else if (&ChannelTypeBool == type) { } + else if (&ChannelTypeString == type) { } + else if (&ChannelTypeBinary == type) { } + else if (&ChannelTypeBinaryReference == type) { } + else if (type->con == CHANNEL_ARRAY) { + // other ChannelTypes are static + ChannelTypeDestructor(type->ty.a.inner); + mcx_free(type->ty.a.dims); + mcx_free(type); + } else { + mcx_free(type); + } +} + +ChannelType * ChannelTypeArray(ChannelType * inner, size_t numDims, size_t * dims) { + ChannelType * array = NULL; + + if (!inner) { + return &ChannelTypeUnknown; + } + + array = (ChannelType *) mcx_malloc(sizeof(ChannelType)); + if (!array) { + return &ChannelTypeUnknown; + } + + array->con = CHANNEL_ARRAY; + array->ty.a.inner = inner; + array->ty.a.numDims = numDims; + array->ty.a.dims = (size_t *) mcx_calloc(sizeof(size_t), numDims); + if (!array->ty.a.dims) { + return &ChannelTypeUnknown; + } + + memcpy(array->ty.a.dims, dims, sizeof(size_t)*numDims); + + return array; +} + +ChannelType * ChannelTypeArrayUInt64Dims(ChannelType * inner, size_t numDims, uint64_t * dims) { + ChannelType * array = NULL; + size_t i = 0; + + if (!inner) { + return &ChannelTypeUnknown; + } + + array = (ChannelType *) mcx_malloc(sizeof(ChannelType)); + if (!array) { + return &ChannelTypeUnknown; + } + + array->con = CHANNEL_ARRAY; + array->ty.a.inner = inner; + array->ty.a.numDims = numDims; + array->ty.a.dims = (size_t *) mcx_calloc(sizeof(size_t), numDims); + if (!array->ty.a.dims) { + return &ChannelTypeUnknown; + } + + for (i = 0; i < numDims; i++) { + array->ty.a.dims[i] = dims[i]; + } + + return array; +} + +ChannelType * ChannelTypeArrayInner(ChannelType * array) { + if (!ChannelTypeIsArray(array)) { + return &ChannelTypeUnknown; + } + + return array->ty.a.inner; +} + +int ChannelTypeIsValid(const ChannelType * a) { + return a->con != CHANNEL_UNKNOWN; +} + +int ChannelTypeIsScalar(const ChannelType * a) { + return a->con != CHANNEL_ARRAY; +} + +int ChannelTypeIsArray(const ChannelType * a) { + return a->con == CHANNEL_ARRAY; +} + +int ChannelTypeIsBinary(const ChannelType * a) { + return a->con == CHANNEL_BINARY || a->con == CHANNEL_BINARY_REFERENCE; +} + +ChannelType * ChannelTypeBaseType(const ChannelType * a) { + if (ChannelTypeIsArray(a)) { + return ChannelTypeBaseType(a->ty.a.inner); + } else { + return a; + } +} + +size_t ChannelTypeNumElements(const ChannelType * type) { + if (ChannelTypeIsArray(type)) { + size_t i = 0; + size_t num_elems = 1; + + for (i = 0; i < type->ty.a.numDims; i++) { + num_elems *= type->ty.a.dims[i]; + } + + return num_elems; + } else { + return 1; + } +} + +int ChannelTypeConformable(ChannelType * a, ChannelDimension * sliceA, ChannelType * b, ChannelDimension * sliceB) { + if (a->con == CHANNEL_ARRAY && b->con == CHANNEL_ARRAY) { + if (sliceA && sliceB) { + return a->ty.a.inner == b->ty.a.inner && ChannelDimensionConformsToDimension(sliceA, sliceB); + } else if (sliceA && !sliceB) { + return a->ty.a.inner == b->ty.a.inner && ChannelDimensionConformsTo(sliceA, b->ty.a.dims, b->ty.a.numDims); + } else if (!sliceA && sliceB) { + return a->ty.a.inner == b->ty.a.inner && ChannelDimensionConformsTo(sliceB, a->ty.a.dims, a->ty.a.numDims); + } else { + return ChannelTypeEq(a, b); + } + } else { + if (sliceA || sliceB) { + mcx_log(LOG_ERROR, "ChannelTypeConformable: Slice dimensions defined for non-array channels"); + return 0; + } + + return a->con == b->con; + } +} + +int ChannelTypeEq(const ChannelType * a, const ChannelType * b) { + if (a->con == CHANNEL_ARRAY && b->con == CHANNEL_ARRAY) { + size_t i = 0; + if (a->ty.a.numDims != b->ty.a.numDims) { + return 0; + } + for (i = 0; i < a->ty.a.numDims; i++) { + if (a->ty.a.dims[i] != b->ty.a.dims[i]) { + return 0; + } + } + return a->ty.a.inner == b->ty.a.inner; + } else { + return a->con == b->con; + } +} + +McxStatus mcx_array_init(mcx_array * a, size_t numDims, size_t * dims, ChannelType * inner) { + a->numDims = numDims; + a->dims = (size_t *) mcx_calloc(sizeof(size_t), numDims); + if (!a->dims) { + return RETURN_ERROR; + } + memcpy(a->dims, dims, sizeof(size_t) * numDims); + + a->type = inner; + a->data = (void *) mcx_calloc(ChannelValueTypeSize(inner), mcx_array_num_elements(a)); + if (!a->data) { + return RETURN_ERROR; + } + + return RETURN_OK; +} + +void mcx_array_destroy(mcx_array * a) { + if (a->dims) { mcx_free(a->dims); } + if (a->data) { mcx_free(a->data); } + if (a->type) { ChannelTypeDestructor(a->type); } +} + +int mcx_array_all(mcx_array * a, mcx_array_predicate_f_ptr predicate) { + size_t i = 0; + ChannelValueData element = {0}; + size_t numElems = mcx_array_num_elements(a); + + for (i = 0; i < numElems; i++) { + if (RETURN_OK != mcx_array_get_elem(a, i, &element)) { + mcx_log(LOG_WARNING, "mcx_array_all: Getting element %zu failed", i); + return 0; + } + + if (!predicate(&element, a->type)) { + return 0; + } + } + + return 1; +} + +int mcx_array_leq(const mcx_array * left, const mcx_array * right) { + size_t numElems = 0; + size_t i = 0; + + if (!ChannelTypeEq(left->type, right->type)) { + return 0; + } + + numElems = mcx_array_num_elements(left); + + for (i = 0; i < numElems; i++) { + switch (left->type->con) { + case CHANNEL_DOUBLE: + if (((double *)left->data)[i] > ((double*)right->data)[i]) { + return 0; + } + break; + case CHANNEL_INTEGER: + if (((int *) left->data)[i] > ((int *) right->data)[i]) { + return 0; + } + break; + default: + return 0; + } + } + + return 1; +} + +int mcx_array_dims_match(mcx_array * a, mcx_array * b) { + size_t i = 0; + + if (a->numDims != b->numDims) { + return 0; + } + if (a->dims == NULL || b->dims == NULL) { + return 0; + } + + for (i = 0; i < a->numDims; i++) { + if (a->dims[i] != b->dims[i]) { + return 0; + } + } + + return 1; +} + +size_t mcx_array_num_elements(const mcx_array * a) { + size_t i = 0; + size_t n = 1; + + if (a->numDims == 0) { + return 0; + } + + for (i = 0; i < a->numDims; i++) { + n *= a->dims[i]; + } + + return n; +} + +McxStatus mcx_array_map(mcx_array * a, mcx_array_map_f_ptr fn, void * ctx) { + size_t num_elems = mcx_array_num_elements(a); + size_t i = 0; + + for (i = 0; i < num_elems; i++) { + if (fn((char *) a->data + i * ChannelValueTypeSize(a->type), i, a->type, ctx)) { + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +McxStatus mcx_array_get_elem(const mcx_array * a, size_t idx, ChannelValueData * element) { + size_t num_elems = mcx_array_num_elements(a); + + if (idx >= num_elems) { + mcx_log(LOG_ERROR, "mcx_array_get_elem: Array index out of range (idx: %zu, num_elems: %zu)", idx, num_elems); + return RETURN_ERROR; + } + + switch (a->type->con) { + case CHANNEL_DOUBLE: + ChannelValueDataSetFromReference(element, a->type, ((double*)a->data) + idx); + break; + case CHANNEL_INTEGER: + case CHANNEL_BOOL: + ChannelValueDataSetFromReference(element, a->type, ((int *) a->data) + idx); + break; + case CHANNEL_STRING: + ChannelValueDataSetFromReference(element, a->type, ((char **) a->data) + idx); + break; + case CHANNEL_BINARY: + case CHANNEL_BINARY_REFERENCE: + ChannelValueDataSetFromReference(element, a->type, ((binary_string *) a->data) + idx); + break; + case CHANNEL_ARRAY: + ChannelValueDataSetFromReference(element, a->type, ((mcx_array *) a->data) + idx); + break; + default: + mcx_log(LOG_ERROR, "mcx_array_get_elem: Unknown array type"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +McxStatus mcx_array_set_elem(mcx_array * a, size_t idx, ChannelValueData * element) { + size_t num_elems = mcx_array_num_elements(a); + + if (idx >= num_elems) { + mcx_log(LOG_ERROR, "mcx_array_set_elem: Array index out of range (idx: %zu, num_elems: %zu)", idx, num_elems); + return RETURN_ERROR; + } + + switch (a->type->con) { + case CHANNEL_DOUBLE: + *((double *) a->data + idx) = element->d; + break; + case CHANNEL_INTEGER: + *((int *) a->data + idx) = element->i; + break; + case CHANNEL_BOOL: + *((int *) a->data + idx) = element->i != 0 ? 1 : 0; + break; + case CHANNEL_STRING: + { + char ** elements = (char **) a->data; + + if (elements[idx]) { + mcx_free(elements[idx]); + } + + elements[idx] = (char *) mcx_calloc(strlen(element->s) + 1, sizeof(char)); + if (!elements[idx]) { + mcx_log(LOG_ERROR, "mcx_array_set_elem: Not enough memory"); + return RETURN_ERROR; + } + + strncpy(elements[idx], element->s, strlen(element->s) + 1); + break; + } + case CHANNEL_BINARY: + { + binary_string * elements = (binary_string *) a->data; + if (elements[idx].data) { + mcx_free(elements[idx].data); + } + + elements[idx].len = element->b.len; + elements[idx].data = (char *) mcx_calloc(elements[idx].len, 1); + if (!elements[idx].data) { + mcx_log(LOG_ERROR, "mcx_array_set_elem: Not enough memory"); + return RETURN_ERROR; + } + memcpy(elements[idx].data, element->b.data, elements[idx].len); + break; + } + case CHANNEL_BINARY_REFERENCE: + ((binary_string *) a->data)[idx].len = element->b.len; + ((binary_string *) a->data)[idx].data = element->b.data; + break; + case CHANNEL_ARRAY: + mcx_log(LOG_ERROR, "mcx_array_set_elem: Nested arrays are not supported"); + return RETURN_ERROR; + default: + mcx_log(LOG_ERROR, "mcx_array_set_elem: Unknown array type"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +void * mcx_array_get_elem_reference(const mcx_array * a, size_t idx) { + size_t num_elems = mcx_array_num_elements(a); + char * data = (char *) a->data; + + if (idx >= num_elems) { + mcx_log(LOG_ERROR, "mcx_array_get_elem_reference: Array index out of range (idx: %zu, num_elems: %zu)", idx, num_elems); + return NULL; + } + + return data + idx * ChannelValueTypeSize(a->type); +} + +ChannelType * ChannelTypeFromDimension(ChannelType * base_type, ChannelDimension * dimension) { + if (dimension) { + // source data is an array + size_t i = 0; + ChannelType * type = NULL; + size_t * dims = (size_t *) mcx_calloc(sizeof(size_t), dimension->num); + + if (!dims) { + mcx_log(LOG_ERROR, "DetermineSliceType: Not enough memory for dimension calculation"); + return NULL; + } + + for (i = 0; i < dimension->num; i++) { + dims[i] = dimension->endIdxs[i] - dimension->startIdxs[i] + 1; // indices are inclusive + } + + type = ChannelTypeArray(ChannelTypeClone(ChannelTypeBaseType(base_type)), dimension->num, dims); + mcx_free(dims); + return type; + } else { + // source data is a scalar + return ChannelTypeClone(base_type); + } +} + +void ChannelValueInit(ChannelValue * value, ChannelType * type) { value->type = type; ChannelValueDataInit(&value->value, type); } -void ChannelValueDataDestructor(ChannelValueData * data, ChannelType type) { - if (type == CHANNEL_STRING) { +void ChannelValueDataDestructor(ChannelValueData * data, ChannelType * type) { + if (type->con == CHANNEL_STRING) { if (data->s) { mcx_free(data->s); data->s = NULL; } - } else if (type == CHANNEL_BINARY) { + } else if (type->con == CHANNEL_BINARY) { if (data->b.data) { mcx_free(data->b.data); data->b.data = NULL; } - } else if (type == CHANNEL_BINARY_REFERENCE) { + } else if (type->con == CHANNEL_BINARY_REFERENCE) { // do not free references to binary, they are not owned by the ChannelValueData + } else if (type->con == CHANNEL_ARRAY) { + if (data->a.dims) { + + mcx_free(data->a.dims); + data->a.dims = NULL; + } + if (data->a.data) { + mcx_free(data->a.data); + data->a.data = NULL; + } } } void ChannelValueDestructor(ChannelValue * value) { ChannelValueDataDestructor(&value->value, value->type); + ChannelTypeDestructor(value->type); } static int isSpecialChar(unsigned char c) { @@ -45,6 +527,19 @@ static int isSpecialChar(unsigned char c) { return (c < ' ' || c > '~'); } +size_t ChannelValueDataDoubleToBuffer(char * buffer, void * value, size_t i) { + const size_t precision = 13; + return sprintf(buffer, "%*.*E", (unsigned) precision, (unsigned) precision, ((double *) value)[i]); +} + +size_t ChannelValueDataIntegerToBuffer(char * buffer, void * value, size_t i) { + return sprintf(buffer, "%d", ((int *) value)[i]); +} + +size_t ChannelValueDataBoolToBuffer(char * buffer, void * value, size_t i) { + return sprintf(buffer, "%1d", (((int *) value)[i] != 0) ? 1 : 0); +} + char * ChannelValueToString(ChannelValue * value) { size_t i = 0; size_t length = 0; @@ -52,14 +547,14 @@ char * ChannelValueToString(ChannelValue * value) { const uint32_t digits_of_exp = 4; // = (mcx_digits10(DBL_MAX_10_EXP) + 1 /* sign */ char * buffer = NULL; - switch (value->type) { + switch (value->type->con) { case CHANNEL_DOUBLE: length = 1 /* sign */ + 1 /* pre decimal place */ + 1 /* dot */ + precision + digits_of_exp + 1 /* string termination */; buffer = (char *) mcx_malloc(sizeof(char) * length); if (!buffer) { return NULL; } - sprintf(buffer, "%*.*E", (unsigned) precision, (unsigned) precision, value->value.d); + ChannelValueDataDoubleToBuffer(buffer, &value->value.d, 0); break; case CHANNEL_INTEGER: length = 1 /* sign */ + mcx_digits10(abs(value->value.i)) + 1 /* string termination*/; @@ -67,7 +562,7 @@ char * ChannelValueToString(ChannelValue * value) { if (!buffer) { return NULL; } - sprintf(buffer, "%d", value->value.i); + ChannelValueDataIntegerToBuffer(buffer, &value->value.i, 0); break; case CHANNEL_BOOL: length = 2; @@ -75,7 +570,7 @@ char * ChannelValueToString(ChannelValue * value) { if (!buffer) { return NULL; } - sprintf(buffer, "%1d", (value->value.i != 0) ? 1 : 0); + ChannelValueDataBoolToBuffer(buffer, &value->value.i, 0); break; case CHANNEL_STRING: if (!value->value.s) { @@ -107,10 +602,49 @@ char * ChannelValueToString(ChannelValue * value) { size_t i = 0; for (i = 0; i < value->value.b.len; i++) { - sprintf(buffer + (4 * i), "\\x%02x", value->value.b.data[i]); + // specifier: x (hex integer) -----+ + // length: 2 (unsigned char) -----+| + // width: 2 --------------------+ || + // flag: 0-padded -------------+| || + // || || + // string literal "\x" ------+ || || + sprintf(buffer + (4 * i), "\\x%02hhx", value->value.b.data[i]); + } + } + break; + case CHANNEL_ARRAY:{ + size_t (*fmt)(char * buffer, void * value, size_t i); + + if (ChannelTypeEq(ChannelTypeArrayInner(value->type), &ChannelTypeDouble)) { + fmt = ChannelValueDataDoubleToBuffer; + } else if (ChannelTypeEq(ChannelTypeArrayInner(value->type), &ChannelTypeInteger)) { + fmt = ChannelValueDataIntegerToBuffer; + } else if (ChannelTypeEq(ChannelTypeArrayInner(value->type), &ChannelTypeBool)) { + fmt = ChannelValueDataBoolToBuffer; + } else { + return NULL; + } + + length = 1 /* sign */ + 1 /* pre decimal place */ + 1 /* dot */ + precision + digits_of_exp + 1 /* string termination */; + length *= mcx_array_num_elements(&value->value.a); + buffer = (char *) mcx_malloc(sizeof(char) * length); + if (!buffer) { + return NULL; + } + + if (mcx_array_num_elements(&value->value.a) > 0) { + size_t i = 0; + size_t n = 0; + + n += fmt(buffer + n, value->value.a.data, 0); + for (i = 1; i < mcx_array_num_elements(&value->value.a); i++) { + n += sprintf(buffer + n, ","); + n += fmt(buffer + n, value->value.a.data, i); } } + break; + } default: return NULL; } @@ -118,18 +652,18 @@ char * ChannelValueToString(ChannelValue * value) { return buffer; } -McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType type, char * buffer, size_t len) { +McxStatus ChannelValueDataToStringBuffer(const ChannelValueData * value, ChannelType * type, char * buffer, size_t len) { size_t i = 0; size_t length = 0; const size_t precision = 13; const uint32_t digits_of_exp = 4; // = (mcx_digits10(DBL_MAX_10_EXP) + 1 /* sign */ const char * doubleFmt = "%*.*E"; - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: length = 1 /* sign */ + 1 /* pre decimal place */ + 1 /* dot */ + precision + digits_of_exp + 1 /* string termination */; if (len < length) { - mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %d, given: %d", length, len); + mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); return RETURN_ERROR; } sprintf(buffer, doubleFmt, (unsigned)precision, (unsigned)precision, value->d); @@ -138,7 +672,7 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t length = 1 /* sign */ + mcx_digits10(abs(value->i)) + 1 /* string termination*/; if (len < length) { - mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %d, given: %d", length, len); + mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); return RETURN_ERROR; } sprintf(buffer, "%d", value->i); @@ -146,7 +680,7 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t case CHANNEL_BOOL: length = 2; if (len < length) { - mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %d, given: %d", length, len); + mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); return RETURN_ERROR; } sprintf(buffer, "%1d", (value->i != 0) ? 1 : 0); @@ -158,7 +692,7 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t } length = strlen(value->s) + 1 /* string termination */; if (len < length) { - mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %d, given: %d", length, len); + mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); return RETURN_ERROR; } sprintf(buffer, "%s", value->s); @@ -173,7 +707,7 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t case CHANNEL_BINARY_REFERENCE: length = value->b.len * 4 + 1; if (len < length) { - mcx_log(LOG_DEBUG, "Port value to string: buffer too short. Needed: %d, given: %d", length, len); + mcx_log(LOG_DEBUG, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); return RETURN_ERROR; } { @@ -184,6 +718,19 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t } } break; + case CHANNEL_ARRAY: { + const char * doubleFmt = "% *.*E"; + + length = 1 /* sign */ + 1 /* pre decimal place */ + 1 /* dot */ + precision + digits_of_exp + 1 /* string termination */; + if (len < length) { + mcx_log(LOG_ERROR, "Port value to string: buffer too short. Needed: %zu, given: %zu", length, len); + return RETURN_ERROR; + } + sprintf(buffer, doubleFmt, (unsigned)precision, (unsigned)precision, *(double *)value->a.data); + + + break; + } default: mcx_log(LOG_DEBUG, "Port value to string: Unknown type"); return RETURN_ERROR; @@ -192,24 +739,24 @@ McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType t return RETURN_OK; } -McxStatus ChannelValueToStringBuffer(ChannelValue * value, char * buffer, size_t len) { +McxStatus ChannelValueToStringBuffer(const ChannelValue * value, char * buffer, size_t len) { return ChannelValueDataToStringBuffer(&value->value, value->type, buffer, len); } -ChannelType ChannelValueType(ChannelValue * value) { +ChannelType * ChannelValueType(ChannelValue * value) { return value->type; } -void * ChannelValueReference(ChannelValue * value) { - if (value->type == CHANNEL_UNKNOWN) { +void * ChannelValueDataPointer(ChannelValue * value) { + if (value->type->con == CHANNEL_UNKNOWN) { return NULL; } else { return &value->value; } } -void ChannelValueDataInit(ChannelValueData * data, ChannelType type) { - switch (type) { +void ChannelValueDataInit(ChannelValueData * data, ChannelType * type) { + switch (type->con) { case CHANNEL_DOUBLE: data->d = 0.0; break; @@ -227,16 +774,82 @@ void ChannelValueDataInit(ChannelValueData * data, ChannelType type) { data->b.len = 0; data->b.data = NULL; break; + case CHANNEL_ARRAY: { + void * tmp = data->a.dims; + data->a.type = ChannelTypeClone(type->ty.a.inner); + data->a.numDims = type->ty.a.numDims; + data->a.dims = (size_t *) mcx_calloc(sizeof(size_t), type->ty.a.numDims); + if (data->a.dims) { + memcpy(data->a.dims, type->ty.a.dims, type->ty.a.numDims * sizeof(size_t)); + } + data->a.data = mcx_calloc(mcx_array_num_elements(&data->a), ChannelValueTypeSize(data->a.type)); + break; + } case CHANNEL_UNKNOWN: default: break; } } -void ChannelValueDataSetFromReference(ChannelValueData * data, ChannelType type, const void * reference) { - if (!reference) { return; } +McxStatus ChannelValueDataSetFromReferenceIfElemwisePred(ChannelValueData * data, + ChannelType * type, + const void * reference, + fChannelValueDataSetterPredicate predicate) { + if (!reference) { + return RETURN_OK; + } + + if (ChannelTypeIsArray(type)) { + mcx_array * a = (mcx_array *) reference; + size_t i = 0; + ChannelValueData first = {0}; + ChannelValueData second = {0}; + + if (!mcx_array_dims_match(&data->a, a)) { + mcx_log(LOG_ERROR, "ChannelValueDataSetFromReferenceIfElemwisePred: Mismatching array dimensions"); + return RETURN_ERROR; + } + + if (a->data == NULL || data->a.data == NULL) { + mcx_log(LOG_ERROR, "ChannelValueDataSetFromReferenceIfElemwisePred: Array data not initialized"); + return RETURN_ERROR; + } + + for (i = 0; i < mcx_array_num_elements(&data->a); i++) { + if (RETURN_OK != mcx_array_get_elem(&data->a, i, &first)) { + mcx_log(LOG_ERROR, "ChannelValueDataSetFromReferenceIfElemwisePred: Getting destination element %zu failed", i); + return RETURN_ERROR; + } + + if (RETURN_OK != mcx_array_get_elem(a, i, &second)) { + mcx_log(LOG_ERROR, "ChannelValueDataSetFromReferenceIfElemwisePred: Getting source element %zu failed", i); + return RETURN_ERROR; + } + + if (predicate(&first, &second, a->type)) { + mcx_array_set_elem(&data->a, i, &second); + } + } + + return RETURN_OK; + } else { + + } + switch (type->con) { + default: + if (predicate(data, reference, type)) { + return ChannelValueDataSetFromReference(data, type, reference); + } + break; + } + + return RETURN_OK; +} + +McxStatus ChannelValueDataSetFromReference(ChannelValueData * data, ChannelType * type, const void * reference) { + if (!reference) { return RETURN_OK; } - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: data->d = * (double *) reference; break; @@ -275,80 +888,144 @@ void ChannelValueDataSetFromReference(ChannelValueData * data, ChannelType type, data->b.data = ((binary_string *) reference)->data; } break; + case CHANNEL_ARRAY: + if (NULL != reference) { + mcx_array * a = (mcx_array *) reference; + + // The first call to SetFromReference fixes the dimensions + if (!data->a.numDims && a->numDims) { + if (RETURN_OK != mcx_array_init(&data->a, a->numDims, a->dims, a->type)) { + return RETURN_ERROR; + } + } + + // Arrays do not support multiplexing (yet) + if (!mcx_array_dims_match(&data->a, a)) { + return RETURN_ERROR; + } + + if (a->data == NULL || data->a.data == NULL) { + return RETURN_ERROR; + } + + memcpy(data->a.data, a->data, ChannelValueTypeSize(data->a.type) * mcx_array_num_elements(&data->a)); + } case CHANNEL_UNKNOWN: default: break; } -} -void ChannelValueSetFromReference(ChannelValue * value, const void * reference) { - if (!reference) { return; } + return RETURN_OK; +} - ChannelValueDataSetFromReference(&value->value, value->type, reference); +McxStatus ChannelValueSetFromReference(ChannelValue * value, const void * reference) { + return ChannelValueDataSetFromReference(&value->value, value->type, reference); } McxStatus ChannelValueSet(ChannelValue * value, const ChannelValue * source) { - if (value->type != source->type) { + if (!ChannelTypeEq(value->type, source->type)) { mcx_log(LOG_ERROR, "Port: Set: Mismatching types. Source type: %s, target type: %s", ChannelTypeToString(source->type), ChannelTypeToString(value->type)); return RETURN_ERROR; } - ChannelValueSetFromReference(value, ChannelValueReference((ChannelValue *) source)); + if (RETURN_OK != ChannelValueSetFromReference(value, ChannelValueDataPointer((ChannelValue *) source))) { + return RETURN_ERROR; + } return RETURN_OK; } -void ChannelValueSetToReference(ChannelValue * value, void * reference) { - switch (value->type) { - case CHANNEL_DOUBLE: - * (double *) reference = value->value.d; - break; - case CHANNEL_INTEGER: - * (int *) reference = value->value.i; - break; - case CHANNEL_BOOL: - * (int *) reference = value->value.i; - break; - case CHANNEL_STRING: - if (* (char **) reference) { - mcx_free(* (char **) reference); - * (char **) reference = NULL; - } - if (value->value.s) { - * (char **) reference = (char *) mcx_calloc(strlen(value->value.s) + 1, sizeof(char)); - if (* (char **) reference) { - strncpy(* (char **) reference, value->value.s, strlen(value->value.s) + 1); +McxStatus ChannelValueDataSetToReference(ChannelValueData * value, ChannelType * type, void * reference) { + if (!reference) { + mcx_log(LOG_ERROR, "ChannelValueDataSetToReference: Reference not defined"); + return RETURN_ERROR; + } + + switch (type->con) { + case CHANNEL_DOUBLE: + *(double *) reference = value->d; + break; + case CHANNEL_INTEGER: + *(int *) reference = value->i; + break; + case CHANNEL_BOOL: + *(int *) reference = value->i; + break; + case CHANNEL_STRING: + if (*(char **) reference) { + mcx_free(*(char **) reference); + *(char **) reference = NULL; } - } - break; - case CHANNEL_BINARY: - if (NULL != reference && NULL != ((binary_string *) reference)->data) { - mcx_free(((binary_string *) reference)->data); - ((binary_string *) reference)->data = NULL; - } - if (value->value.b.data) { - ((binary_string *) reference)->len = value->value.b.len; - ((binary_string *) reference)->data = (char *) mcx_calloc(value->value.b.len, 1); - if (((binary_string *) reference)->data) { - memcpy(((binary_string *) reference)->data, value->value.b.data, value->value.b.len); + if (value->s) { + *(char **) reference = (char *) mcx_calloc(strlen(value->s) + 1, sizeof(char)); + if (*(char **) reference) { + strncpy(*(char **) reference, value->s, strlen(value->s) + 1); + } else { + return RETURN_ERROR; + } } - } - break; - case CHANNEL_BINARY_REFERENCE: - if (NULL != reference) { - ((binary_string *) reference)->len = value->value.b.len; - ((binary_string *) reference)->data = value->value.b.data; - } - break; - case CHANNEL_UNKNOWN: - default: - break; + break; + case CHANNEL_BINARY: + if (NULL != ((binary_string *) reference)->data) { + mcx_free(((binary_string *) reference)->data); + ((binary_string *) reference)->data = NULL; + } + + if (value->b.data) { + ((binary_string *) reference)->len = value->b.len; + ((binary_string *) reference)->data = (char *) mcx_calloc(value->b.len, 1); + if (((binary_string *) reference)->data) { + memcpy(((binary_string *) reference)->data, value->b.data, value->b.len); + } + } + break; + case CHANNEL_BINARY_REFERENCE: + ((binary_string *) reference)->len = value->b.len; + ((binary_string *) reference)->data = value->b.data; + break; + case CHANNEL_ARRAY: + { + mcx_array * a = (mcx_array *) reference; + + // First Set fixes the dimensions + if (value->a.numDims && !a->numDims) { + if (RETURN_OK != mcx_array_init(a, value->a.numDims, value->a.dims, value->a.type)) { + mcx_log(LOG_ERROR, "ChannelValueDataSetToReference: Array initialization failed"); + return RETURN_ERROR; + } + } + + // Arrays do not support multiplexing (yet) + if (!mcx_array_dims_match(a, &value->a)) { + mcx_log(LOG_ERROR, "ChannelValueDataSetToReference: Array dimensions do not match"); + return RETURN_ERROR; + } + + if (value->a.data == NULL || a->data == NULL) { + mcx_log(LOG_ERROR, "ChannelValueDataSetToReference: No array data available"); + return RETURN_ERROR; + } + + memcpy(a->data, value->a.data, ChannelValueTypeSize(a->type) * mcx_array_num_elements(a)); + break; + } + case CHANNEL_UNKNOWN: + default: + break; } + + return RETURN_OK; + } + +McxStatus ChannelValueSetToReference(ChannelValue * value, void * reference) { + return ChannelValueDataSetToReference(&value->value, value->type, reference); +} + #ifdef __cplusplus -size_t ChannelValueTypeSize(ChannelType type) { - switch (type) { +size_t ChannelValueTypeSize(ChannelType * type) { + switch (type->con) { case CHANNEL_DOUBLE: return sizeof(ChannelValueData::d); case CHANNEL_INTEGER: @@ -357,13 +1034,18 @@ size_t ChannelValueTypeSize(ChannelType type) { return sizeof(ChannelValueData::i); case CHANNEL_STRING: return sizeof(ChannelValueData::s); + case CHANNEL_BINARY: + case CHANNEL_BINARY_REFERENCE: + return sizeof(ChannelValueData::b); + case CHANNEL_ARRAY: + return sizeof(ChannelValueData::a); } return 0; } #else //__cplusplus -size_t ChannelValueTypeSize(ChannelType type) { +size_t ChannelValueTypeSize(ChannelType * type) { ChannelValueData value; - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: return sizeof(value.d); case CHANNEL_INTEGER: @@ -372,13 +1054,22 @@ size_t ChannelValueTypeSize(ChannelType type) { return sizeof(value.i); case CHANNEL_STRING: return sizeof(value.s); + case CHANNEL_BINARY: + case CHANNEL_BINARY_REFERENCE: + return sizeof(value.b); + case CHANNEL_ARRAY: + return sizeof(value.a); } return 0; } #endif //__cplusplus -const char * ChannelTypeToString(ChannelType type) { - switch (type) { +int ChannelTypeMatch(ChannelType * a, ChannelType * b) { + return ChannelTypeEq(a, b); +} + +const char * ChannelTypeToString(ChannelType * type) { + switch (type->con) { case CHANNEL_UNKNOWN: return "Unknown"; case CHANNEL_DOUBLE: @@ -390,19 +1081,26 @@ const char * ChannelTypeToString(ChannelType type) { case CHANNEL_STRING: return "String"; case CHANNEL_BINARY: - case CHANNEL_BINARY_REFERENCE: return "Binary"; + case CHANNEL_BINARY_REFERENCE: + return "BinaryReference"; + case CHANNEL_ARRAY: + return "Array"; default: return ""; } } ChannelValue * ChannelValueClone(ChannelValue * value) { + if (!value) { return NULL; } + ChannelValue * clone = (ChannelValue *) mcx_malloc(sizeof(ChannelValue)); if (!clone) { return NULL; } - ChannelValueInit(clone, ChannelValueType(value)); + // ChannelTypeClone might fail, then clone will be + // ChannelTypeUnknown and ChannelValueSet below returns an error + ChannelValueInit(clone, ChannelTypeClone(ChannelValueType(value))); if (ChannelValueSet(clone, value) != RETURN_OK) { mcx_free(clone); @@ -414,26 +1112,28 @@ ChannelValue * ChannelValueClone(ChannelValue * value) { int ChannelValueLeq(ChannelValue * val1, ChannelValue * val2) { - if (ChannelValueType(val1) != ChannelValueType(val2)) { + if (!ChannelTypeEq(val1->type, val2->type)) { return 0; } - switch (ChannelValueType(val1)) { + switch (ChannelValueType(val1)->con) { case CHANNEL_DOUBLE: return val1->value.d <= val2->value.d; case CHANNEL_INTEGER: return val1->value.i <= val2->value.i; + case CHANNEL_ARRAY: + return mcx_array_leq(&val1->value.a, &val2->value.a); default: return 0; } } int ChannelValueGeq(ChannelValue * val1, ChannelValue * val2) { - if (ChannelValueType(val1) != ChannelValueType(val2)) { + if (!ChannelTypeEq(val1->type, val2->type)) { return 0; } - switch (ChannelValueType(val1)) { + switch (ChannelValueType(val1)->con) { case CHANNEL_DOUBLE: return val1->value.d >= val2->value.d; case CHANNEL_INTEGER: @@ -444,11 +1144,11 @@ int ChannelValueGeq(ChannelValue * val1, ChannelValue * val2) { } int ChannelValueEq(ChannelValue * val1, ChannelValue * val2) { - if (ChannelValueType(val1) != ChannelValueType(val2)) { + if (!ChannelTypeEq(val1->type, val2->type)) { return 0; } - switch (ChannelValueType(val1)) { + switch (ChannelValueType(val1)->con) { case CHANNEL_DOUBLE: return val1->value.d == val2->value.d; case CHANNEL_BOOL: @@ -461,47 +1161,122 @@ int ChannelValueEq(ChannelValue * val1, ChannelValue * val2) { } } +static int ChannelValueArrayElemAddOffset(void * elem, size_t idx, ChannelType * type, void * ctx) { + mcx_array * offset = (mcx_array *) ctx; + + switch (type->con) { + case CHANNEL_DOUBLE: + *(double *) elem = *(double *) elem + ((double *) offset->data)[idx]; + break; + case CHANNEL_INTEGER: + *(int *) elem = *(int *) elem + ((int *) offset->data)[idx]; + break; + default: + mcx_log(LOG_ERROR, "ChannelValueArrayElemAddOffset: Type %s not allowed", ChannelTypeToString(type)); + return 1; + } + + return 0; +} + McxStatus ChannelValueAddOffset(ChannelValue * val, ChannelValue * offset) { - if (ChannelValueType(val) != ChannelValueType(offset)) { + if (!ChannelTypeEq(val->type, offset->type)) { mcx_log(LOG_ERROR, "Port: Add offset: Mismatching types. Value type: %s, offset type: %s", ChannelTypeToString(ChannelValueType(val)), ChannelTypeToString(ChannelValueType(offset))); return RETURN_ERROR; } - switch (ChannelValueType(val)) { + switch (ChannelValueType(val)->con) { case CHANNEL_DOUBLE: val->value.d += offset->value.d; return RETURN_OK; case CHANNEL_INTEGER: val->value.i += offset->value.i; return RETURN_OK; + case CHANNEL_ARRAY: + return mcx_array_map(&val->value.a, ChannelValueArrayElemAddOffset, &offset->value.a); default: mcx_log(LOG_ERROR, "Port: Add offset: Type %s not allowed", ChannelTypeToString(ChannelValueType(val))); return RETURN_ERROR; } } +static int ChannelValueArrayElemScale(void * elem, size_t idx, ChannelType * type, void * ctx) { + mcx_array * factor = (mcx_array *) ctx; + + switch (type->con) { + case CHANNEL_DOUBLE: + *(double *) elem = *(double *) elem * ((double *) factor->data)[idx]; + break; + case CHANNEL_INTEGER: + *(int *) elem = *(int *) elem * ((int *) factor->data)[idx]; + break; + default: + mcx_log(LOG_ERROR, "ChannelValueArrayElemScale: Type %s not allowed", ChannelTypeToString(type)); + return 1; + } + + return 0; +} + McxStatus ChannelValueScale(ChannelValue * val, ChannelValue * factor) { - if (ChannelValueType(val) != ChannelValueType(factor)) { + if (!ChannelTypeEq(val->type, factor->type)) { mcx_log(LOG_ERROR, "Port: Scale: Mismatching types. Value type: %s, factor type: %s", ChannelTypeToString(ChannelValueType(val)), ChannelTypeToString(ChannelValueType(factor))); return RETURN_ERROR; } - switch (ChannelValueType(val)) { + switch (ChannelValueType(val)->con) { case CHANNEL_DOUBLE: val->value.d *= factor->value.d; return RETURN_OK; case CHANNEL_INTEGER: val->value.i *= factor->value.i; return RETURN_OK; + case CHANNEL_ARRAY: + return mcx_array_map(&val->value.a, ChannelValueArrayElemScale, &factor->value.a); default: mcx_log(LOG_ERROR, "Port: Scale: Type %s not allowed", ChannelTypeToString(ChannelValueType(val))); return RETURN_ERROR; } } -ChannelValue ** ArrayToChannelValueArray(void * values, size_t num, ChannelType type) { +// Does not take ownership of dims or data +ChannelValue * ChannelValueNewScalar(ChannelType * type, void * data) { + ChannelValue * value = mcx_malloc(sizeof(ChannelValue)); + if (!value) { + return NULL; + } + + ChannelValueInit(value, ChannelTypeClone(type)); + ChannelValueSetFromReference(value, data); + + return value; +} + +// Does not take ownership of dims or data +ChannelValue * ChannelValueNewArray(size_t numDims, size_t dims[], ChannelType * type, void * data) { + ChannelValue * value = mcx_malloc(sizeof(ChannelValue)); + if (!value) { + return NULL; + } + + ChannelValueInit(value, ChannelTypeArray(type, numDims, dims)); + + if (value->value.a.data && data) { + memcpy(value->value.a.data, data, ChannelValueTypeSize(type) * mcx_array_num_elements(&value->value.a)); + } + + return value; +} + +void ChannelValueDestroy(ChannelValue ** value) { + ChannelValueDestructor(*value); + mcx_free(*value); + *value = NULL; +} + +ChannelValue ** ArrayToChannelValueArray(void * values, size_t num, ChannelType * type) { ChannelValue ** array = NULL; size_t size = ChannelValueTypeSize(type); @@ -526,8 +1301,10 @@ ChannelValue ** ArrayToChannelValueArray(void * values, size_t num, ChannelType return NULL; } - ChannelValueInit(array[i], type); - ChannelValueSetFromReference(array[i], (char *) values + i*size); + ChannelValueInit(array[i], ChannelTypeClone(type)); + if (RETURN_OK != ChannelValueSetFromReference(array[i], (char *) values + i*size)) { + return RETURN_ERROR; + } } return array; diff --git a/src/core/channels/ChannelValue.h b/src/core/channels/ChannelValue.h index b177593..9647c62 100644 --- a/src/core/channels/ChannelValue.h +++ b/src/core/channels/ChannelValue.h @@ -12,18 +12,89 @@ #define MCX_CORE_CHANNELS_CHANNEL_VALUE_H #include "CentralParts.h" +#include +#include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ + +typedef struct ChannelDimension ChannelDimension; + +char * CreateIndexedName(const char * name, unsigned i); + +// possible types of values that can be put on channels +typedef enum ChannelTypeConstructor { + CHANNEL_UNKNOWN = 0, + CHANNEL_DOUBLE = 1, + CHANNEL_INTEGER = 2, + CHANNEL_BOOL = 3, + CHANNEL_STRING = 4, + CHANNEL_BINARY = 5, + CHANNEL_BINARY_REFERENCE = 6, + CHANNEL_ARRAY = 7, +} ChannelTypeConstructor; + +typedef struct ChannelTypeArrayType { + struct ChannelType * inner; + size_t numDims; + size_t * dims; +} ChannelTypeArrayType; + +typedef struct ChannelType { + ChannelTypeConstructor con; + union { + ChannelTypeArrayType a; + } ty; +} ChannelType; + +// pre-defined types +extern ChannelType ChannelTypeUnknown; +extern ChannelType ChannelTypeInteger; +extern ChannelType ChannelTypeDouble; +extern ChannelType ChannelTypeBool; +extern ChannelType ChannelTypeString; +extern ChannelType ChannelTypeBinary; +extern ChannelType ChannelTypeBinaryReference; +ChannelType * ChannelTypeArray(ChannelType * inner, size_t numDims, size_t * dims); +ChannelType * ChannelTypeArrayUInt64Dims(ChannelType * inner, size_t numDims, uint64_t * dims); + +ChannelType * ChannelTypeClone(ChannelType * type); +void ChannelTypeDestructor(ChannelType * type); + +ChannelType * ChannelTypeArrayInner(ChannelType * array); + +int ChannelTypeIsValid(const ChannelType * a); +int ChannelTypeIsScalar(const ChannelType * a); +int ChannelTypeIsArray(const ChannelType * a); +int ChannelTypeIsBinary(const ChannelType * a); + +size_t ChannelTypeNumElements(const ChannelType * type); + +ChannelType * ChannelTypeFromDimension(ChannelType * base_type, ChannelDimension * dimension); + +ChannelType * ChannelTypeBaseType(const ChannelType * a); + +int ChannelTypeEq(const ChannelType * a, const ChannelType * b); +int ChannelTypeConformable(ChannelType * a, ChannelDimension * sliceA, ChannelType * b, ChannelDimension * sliceB); + +typedef struct MapStringChannelType { + const char * key; + ChannelType * value; +} MapStringChannelType; + + typedef struct { double startTime; double endTime; } TimeInterval; +typedef union ChannelValueData ChannelValueData; +typedef struct ChannelValue ChannelValue; + typedef struct { - double (* fn)(TimeInterval * arg, void * env); + McxStatus (* fn)(TimeInterval * arg, void * env, ChannelValue * res); void * env; } proc; @@ -32,57 +103,83 @@ typedef struct { char * data; } binary_string; -// possible types of values that can be put on channels -typedef enum ChannelType { - CHANNEL_UNKNOWN = 0, - CHANNEL_DOUBLE = 1, - CHANNEL_INTEGER = 2, - CHANNEL_BOOL = 3, - CHANNEL_STRING = 4, - CHANNEL_BINARY = 5, - CHANNEL_BINARY_REFERENCE = 6, -} ChannelType; +typedef struct { + size_t numDims; + size_t * dims; + ChannelType * type; + void * data; +} mcx_array; + +McxStatus mcx_array_init(mcx_array * a, size_t numDims, size_t * dims, ChannelType * type); +void mcx_array_destroy(mcx_array * a); +int mcx_array_dims_match(mcx_array * a, mcx_array * b); +size_t mcx_array_num_elements(const mcx_array * a); -typedef union ChannelValueData { +typedef int (*mcx_array_map_f_ptr)(void * element, size_t idx, ChannelType * type, void * ctx); + +McxStatus mcx_array_map(mcx_array * a, mcx_array_map_f_ptr fn, void * ctx); +McxStatus mcx_array_get_elem(const mcx_array * a, size_t idx, ChannelValueData * element); +McxStatus mcx_array_set_elem(mcx_array * a, size_t idx, ChannelValueData * element); + +void * mcx_array_get_elem_reference(const mcx_array * a, size_t idx); + +typedef int (*mcx_array_predicate_f_ptr)(void * element, ChannelType * type); +int mcx_array_all(mcx_array * a, mcx_array_predicate_f_ptr predicate); +int mcx_array_leq(const mcx_array * left, const mcx_array * right); + +union ChannelValueData { /* the order is significant. double needs to be the first entry for union initialization to work */ double d; int i; char * s; binary_string b; -} ChannelValueData; + mcx_array a; +}; -typedef struct ChannelValue { - ChannelType type; +struct ChannelValue { + ChannelType * type; ChannelValueData value; -} ChannelValue; +}; -void ChannelValueInit(ChannelValue * value, ChannelType type); +// Takes ownership of type +void ChannelValueInit(ChannelValue * value, ChannelType * type); void ChannelValueDestructor(ChannelValue * value); char * ChannelValueToString(ChannelValue * value); -McxStatus ChannelValueDataToStringBuffer(ChannelValueData * value, ChannelType type, char * buffer, size_t len); -McxStatus ChannelValueToStringBuffer(ChannelValue * value, char * buffer, size_t len); +McxStatus ChannelValueDataToStringBuffer(const ChannelValueData * value, ChannelType * type, char * buffer, size_t len); +McxStatus ChannelValueToStringBuffer(const ChannelValue * value, char * buffer, size_t len); -ChannelType ChannelValueType(ChannelValue * value); -void * ChannelValueReference(ChannelValue * value); +ChannelType * ChannelValueType(ChannelValue * value); +void * ChannelValueDataPointer(ChannelValue * value); -void ChannelValueDataDestructor(ChannelValueData * data, ChannelType type); -void ChannelValueDataInit(ChannelValueData * data, ChannelType type); -void ChannelValueDataSetFromReference(ChannelValueData * data, ChannelType type, const void * reference); +void ChannelValueDataDestructor(ChannelValueData * data, ChannelType * type); +void ChannelValueDataInit(ChannelValueData * data, ChannelType * type); +McxStatus ChannelValueDataSetFromReference(ChannelValueData * data, ChannelType * type, const void * reference); +typedef int (*fChannelValueDataSetterPredicate)(void * first, void * second, ChannelType * type); +McxStatus ChannelValueDataSetFromReferenceIfElemwisePred(ChannelValueData * data, + ChannelType * type, + const void * reference, + fChannelValueDataSetterPredicate predicate); +McxStatus ChannelValueDataSetToReference(ChannelValueData * value, ChannelType * type, void * reference); -void ChannelValueSetFromReference(ChannelValue * value, const void * reference); -void ChannelValueSetToReference(ChannelValue * value, void * reference); +McxStatus ChannelValueSetFromReference(ChannelValue * value, const void * reference); +McxStatus ChannelValueSetToReference(ChannelValue * value, void * reference); McxStatus ChannelValueSet(ChannelValue * value, const ChannelValue * source); -size_t ChannelValueTypeSize(ChannelType type); +size_t ChannelValueTypeSize(ChannelType * type); +int ChannelTypeMatch(ChannelType * a, ChannelType * b); + +ChannelValue * ChannelValueNewScalar(ChannelType * type, void * data); +ChannelValue * ChannelValueNewArray(size_t numDims, size_t dims[], ChannelType * type, void * data); +void ChannelValueDestroy(ChannelValue ** value); -ChannelValue ** ArrayToChannelValueArray(void * values, size_t num, ChannelType type); +ChannelValue ** ArrayToChannelValueArray(void * values, size_t num, ChannelType * type); /* * Returns a string representation of ChannelType for use in log * messages. */ -const char * ChannelTypeToString(ChannelType type); +const char * ChannelTypeToString(ChannelType * type); /* * Creates a copy of value. Allocates memory if needed, e.g. when diff --git a/src/core/channels/ChannelValueReference.c b/src/core/channels/ChannelValueReference.c new file mode 100644 index 0000000..152e363 --- /dev/null +++ b/src/core/channels/ChannelValueReference.c @@ -0,0 +1,230 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include "core/channels/ChannelValueReference.h" +#include "common/logging.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +void DestroyChannelValueReference(ChannelValueReference * ref) { + if (ref->type == CHANNEL_VALUE_REF_SLICE) { + if (ref->ref.slice.dimension) { + DestroyChannelDimension(ref->ref.slice.dimension); + } + } + + mcx_free(ref); +} + + +ChannelValueReference * MakeChannelValueReference(ChannelValue * value, ChannelDimension * slice) { + ChannelValueReference * ref = (ChannelValueReference *) mcx_calloc(1, sizeof(ChannelValueReference)); + + if (!ref) { + return NULL; + } + + if (slice) { + ref->type = CHANNEL_VALUE_REF_SLICE; + ref->ref.slice.dimension = slice; + ref->ref.slice.ref = value; + } else { + ref->type = CHANNEL_VALUE_REF_VALUE; + ref->ref.value = value; + } + + return ref; +} + + +McxStatus ChannelValueReferenceSetFromPointer(ChannelValueReference * ref, const void * ptr, ChannelDimension * srcDimension, TypeConversion * conv) { + if (conv) { + return conv->Convert(conv, ref, ptr); + } + + if (ref->type == CHANNEL_VALUE_REF_VALUE) { + if (ChannelTypeIsArray(ref->ref.value->type)) { + mcx_array * destArray = &ref->ref.value->value.a; + mcx_array * srcArray = (mcx_array *) ptr; + + if (srcArray->data == NULL || destArray->data == NULL) { + mcx_log(LOG_ERROR, "ChannelValueReferenceSetFromPointer: Empty array data given"); + return RETURN_ERROR; + } + + if (srcArray->numDims == 1) { + // if there is only one dimension, values are sequentially stored in memory so we can use memcpy + // we could also check if for numDims > 1, values are sequentially stored or not, but there is no + // need for that now + size_t numBytes = ChannelValueTypeSize(destArray->type) * mcx_array_num_elements(destArray); + size_t srcOffset = srcDimension != 0 ? srcDimension->startIdxs[0] * ChannelValueTypeSize(srcArray->type) : 0; + void * sourceData = (char *) srcArray->data + srcOffset; + + memcpy(destArray->data, sourceData, numBytes); + } else { + // copy element by element + size_t i = 0; + size_t numElems = srcDimension ? ChannelDimensionNumElements(srcDimension) : mcx_array_num_elements(destArray); + + for (i = 0; i < numElems; i++) { + size_t srcIdx = srcDimension ? ChannelDimensionGetIndex(srcDimension, i, srcArray->dims) : i; + void * srcElem = mcx_array_get_elem_reference(srcArray, srcIdx); + void * destElem = mcx_array_get_elem_reference(destArray, i); + memcpy(destElem, srcElem, ChannelValueTypeSize(destArray->type)); + } + } + + return RETURN_OK; + } else { + if (srcDimension) { + mcx_array * src = (mcx_array *) (ptr); + + if (ChannelDimensionNumElements(srcDimension) != 1) { + mcx_log(LOG_ERROR, "ChannelValueReferenceSetFromPointer: Setting scalar value from an array"); + return RETURN_ERROR; + } + + return ChannelValueDataSetFromReference( + &ref->ref.value->value, + ref->ref.value->type, + mcx_array_get_elem_reference(src, ChannelDimensionGetIndex(srcDimension, 0, src->dims))); + } else { + return ChannelValueDataSetFromReference(&ref->ref.value->value, ref->ref.value->type, ptr); + } + } + } else { + if (ChannelTypeIsArray(ref->ref.slice.ref->type)) { + mcx_array * destArray = &ref->ref.slice.ref->value.a; + mcx_array * srcArray = (mcx_array *) ptr; + + ChannelDimension * destDimension = ref->ref.slice.dimension; + + if (srcArray->data == NULL || destArray->data == NULL) { + mcx_log(LOG_ERROR, "ChannelValueReferenceSetFromPointer: Empty array data given"); + return RETURN_ERROR; + } + + if (srcArray->numDims == 1) { + // if there is only one dimension, values are sequentially stored in memory so we can use memcpy + // we could also check if for numDims > 1, values are sequentially stored or not, but there is no + // need for that now + size_t numBytes = ChannelValueTypeSize(destArray->type) * (destDimension->endIdxs[0] - destDimension->startIdxs[0] + 1); + size_t destOffset = destDimension->startIdxs[0] * ChannelValueTypeSize(destArray->type); + void * destData = (char *) destArray->data + destOffset; + size_t srcOffset = srcDimension != 0 ? srcDimension->startIdxs[0] * ChannelValueTypeSize(srcArray->type) : 0; + void * sourceData = (char *) srcArray->data + srcOffset; + + memcpy(destData, sourceData, numBytes); + } else { + // copy element by element + size_t i = 0; + size_t numElems = srcDimension ? ChannelDimensionNumElements(srcDimension) : mcx_array_num_elements(destArray); + + for (i = 0; i < numElems; i++) { + size_t srcIdx = srcDimension ? ChannelDimensionGetIndex(srcDimension, i, srcArray->dims) : i; + size_t destIdx = ChannelDimensionGetIndex(destDimension, i, destArray->dims); + + void * srcElem = mcx_array_get_elem_reference(srcArray, srcIdx); + void * destElem = mcx_array_get_elem_reference(destArray, destIdx); + memcpy(destElem, srcElem, ChannelValueTypeSize(destArray->type)); + } + } + + return RETURN_OK; + } else { + if (srcDimension) { + mcx_array * src = (mcx_array *) (ptr); + + if (ChannelDimensionNumElements(srcDimension) != 1) { + mcx_log(LOG_ERROR, "ChannelValueReferenceSetFromPointer: Setting scalar value from an array"); + return RETURN_ERROR; + } + + return ChannelValueDataSetFromReference( + &ref->ref.slice.ref->value, + ref->ref.slice.ref->type, + mcx_array_get_elem_reference(src, ChannelDimensionGetIndex(srcDimension, 0, src->dims))); + } else { + return ChannelValueDataSetFromReference(&ref->ref.slice.ref->value, ref->ref.slice.ref->type, ptr); + } + } + } + + return RETURN_OK; +} + +McxStatus ChannelValueReferenceElemMap(ChannelValueReference * ref, fChannelValueReferenceElemMapFunc fn, void * ctx) { + switch (ref->type) { + case CHANNEL_VALUE_REF_VALUE: + if (ChannelTypeIsArray(ref->ref.value->type)) { + size_t i = 0; + + for (i = 0; i < mcx_array_num_elements(&ref->ref.value->value.a); i++) { + void * elem = mcx_array_get_elem_reference(&ref->ref.value->value.a, i); + if (!elem) { + return RETURN_ERROR; + } + + if (RETURN_ERROR == fn(elem, i, ChannelValueType(ref->ref.value), ctx)) { + return RETURN_ERROR; + } + } + + return RETURN_OK; + } else { + return fn(ChannelValueDataPointer(ref->ref.value), 0, ChannelValueType(ref->ref.value), ctx); + } + case CHANNEL_VALUE_REF_SLICE: + if (ChannelTypeIsArray(ref->ref.slice.ref->type)) { + size_t i = 0; + + for (i = 0; i < ChannelDimensionNumElements(ref->ref.slice.dimension); i++) { + size_t idx = ChannelDimensionGetIndex(ref->ref.slice.dimension, i, ref->ref.slice.ref->value.a.dims); + + void * elem = mcx_array_get_elem_reference(&ref->ref.slice.ref->value.a, idx); + if (!elem) { + return RETURN_ERROR; + } + + if (RETURN_ERROR == fn(elem, idx, ChannelValueType(ref->ref.slice.ref), ctx)) { + return RETURN_ERROR; + } + } + + return RETURN_OK; + } else { + return fn(ChannelValueDataPointer(ref->ref.slice.ref), 0, ChannelValueType(ref->ref.slice.ref), ctx); + } + default: + mcx_log(LOG_ERROR, "ChannelValueReferenceElemMap: Invalid internal channel value reference type (%d)", ref->type); + return RETURN_ERROR; + } +} + +ChannelType * ChannelValueReferenceGetType(ChannelValueReference * ref) { + switch (ref->type) { + case CHANNEL_VALUE_REF_VALUE: + return ChannelValueType(ref->ref.value); + case CHANNEL_VALUE_REF_SLICE: + return ChannelValueType(ref->ref.slice.ref); + default: + mcx_log(LOG_ERROR, "Invalid internal channel value reference type (%d)", ref->type); + return NULL; + } +} + + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ \ No newline at end of file diff --git a/src/core/channels/ChannelValueReference.h b/src/core/channels/ChannelValueReference.h new file mode 100644 index 0000000..10ea9bd --- /dev/null +++ b/src/core/channels/ChannelValueReference.h @@ -0,0 +1,61 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef MCX_CORE_CHANNELS_CHANNEL_VALUE_REFERENCE_H +#define MCX_CORE_CHANNELS_CHANNEL_VALUE_REFERENCE_H + +#include "CentralParts.h" +#include "core/channels/ChannelDimension.h" + +#include "core/Conversion.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +typedef struct ArraySlice { + ChannelDimension * dimension; + ChannelValue * ref; +} ArraySlice; + +typedef enum ChannelValueRefType { + CHANNEL_VALUE_REF_VALUE, + CHANNEL_VALUE_REF_SLICE +} ChannelValueRefType; + + +typedef struct ChannelValueReference { + ChannelValueRefType type; + union { + ChannelValue * value; + ArraySlice slice; + } ref; +} ChannelValueReference; + + +ChannelValueReference * MakeChannelValueReference(ChannelValue * value, ChannelDimension * slice); +void DestroyChannelValueReference(ChannelValueReference * ref); + + +McxStatus +ChannelValueReferenceSetFromPointer(ChannelValueReference * ref, const void * ptr, ChannelDimension * srcDimension, TypeConversion * typeConv); +ChannelType * ChannelValueReferenceGetType(ChannelValueReference * ref); + +typedef McxStatus (*fChannelValueReferenceElemMapFunc)(void * element, size_t idx, ChannelType * type, void * ctx); +McxStatus ChannelValueReferenceElemMap(ChannelValueReference * ref, fChannelValueReferenceElemMapFunc fn, void * ctx); + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ + +#endif // MCX_CORE_CHANNELS_CHANNEL_VALUE_REFERENCE_H \ No newline at end of file diff --git a/src/core/channels/Channel_impl.h b/src/core/channels/Channel_impl.h index 60ef770..9588c99 100644 --- a/src/core/channels/Channel_impl.h +++ b/src/core/channels/Channel_impl.h @@ -13,92 +13,12 @@ #include "CentralParts.h" #include "objects/ObjectContainer.h" +#include "core/channels/ChannelInfo.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -// ---------------------------------------------------------------------- -// Channel - -typedef struct ChannelData { - Object _; // base class - - // ---------------------------------------------------------------------- - // General Information - - ChannelInfo * info; - - // ---------------------------------------------------------------------- - // Value - - // NOTE: This flag gets set if there is a defined value for the - // channel during initialization. - int isDefinedDuringInit; - const void * internalValue; - ChannelValue value; - -} ChannelData; - -// ---------------------------------------------------------------------- -// ChannelIn - -// object that is stored in target component that stores the channel connection -typedef struct ChannelInData { - Object _; // base class - - struct Connection * connection; - - // ---------------------------------------------------------------------- - // Conversions - - struct TypeConversion * typeConversion; - struct UnitConversion * unitConversion; - struct LinearConversion * linearConversion; - struct RangeConversion * rangeConversion; - - // ---------------------------------------------------------------------- - // Storage in Component - - int isDiscrete; - - void * reference; -} ChannelInData; - -// ---------------------------------------------------------------------- -// ChannelOut - -// object that is provided to consumer of output channel -typedef struct ChannelOutData { - Object _; // base class - - // Function pointer that provides the value of the channel when called - const proc * valueFunction; - - // ---------------------------------------------------------------------- - // Conversion - - struct RangeConversion * rangeConversion; - struct LinearConversion * linearConversion; - - int rangeConversionIsActive; - - // ---------------------------------------------------------------------- - // NaN Handling - - NaNCheckLevel nanCheck; - - size_t countNaNCheckWarning; - size_t maxNumNaNCheckWarning; - - // ---------------------------------------------------------------------- - // Connections to Consumers - - // A list of all input channels that are connected to this output channel - ObjectContainer * connections; - -} ChannelOutData; - // ---------------------------------------------------------------------- // ChannelLocal diff --git a/src/core/channels/VectorChannelInfo.c b/src/core/channels/VectorChannelInfo.c index ee6fbe9..10492b3 100644 --- a/src/core/channels/VectorChannelInfo.c +++ b/src/core/channels/VectorChannelInfo.c @@ -9,6 +9,7 @@ ********************************************************************************/ #include "core/channels/VectorChannelInfo.h" +#include "core/channels/ChannelInfo.h" #include "util/string.h" #include "objects/ObjectContainer.h" @@ -61,9 +62,8 @@ static McxStatus VectorChannelInfoSetup( static McxStatus VectorChannelInfoAddElement( VectorChannelInfo * info, ChannelInfo * channel, - size_t index) { - - ChannelInfo * oldChannel = NULL; + size_t index) +{ McxStatus retVal = RETURN_OK; if (index < info->startIndex || index > info->endIndex) { @@ -71,14 +71,9 @@ static McxStatus VectorChannelInfoAddElement( return RETURN_ERROR; } - oldChannel = (ChannelInfo *) info->channels->At(info->channels, index - info->startIndex); - if (oldChannel) { - object_destroy(oldChannel); - } - - retVal = info->channels->SetAt(info->channels, index - info->startIndex, (Object *) channel); + retVal = info->channels->SetAt(info->channels, index - info->startIndex, &channel); if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Vector port: %s: Could not add port info with index %d", info->GetName(info)); + mcx_log(LOG_ERROR, "Vector port: %s: Could not add port info with index %zu", info->GetName(info), index); return RETURN_ERROR; } @@ -102,7 +97,7 @@ static const char * VectorChannelInfoGetNameInTool(VectorChannelInfo * info) { } static ChannelInfo * VectorChannelInfoGetElement(VectorChannelInfo * info, size_t index) { - return (ChannelInfo *) info->channels->At(info->channels, index - info->startIndex); + return *(ChannelInfo **) info->channels->At(info->channels, index - info->startIndex); } static int VectorChannelInfoIsScalar(VectorChannelInfo * info) { @@ -139,11 +134,13 @@ static VectorChannelInfo * VectorChannelInfoCreate(VectorChannelInfo * info) { info->startIndex = SIZE_T_ERROR; info->endIndex = SIZE_T_ERROR; - info->channels = (ObjectContainer *) object_create(ObjectContainer); + info->channels = (Vector *) object_create(Vector); if (!info->channels) { return NULL; } + info->channels->Setup(info->channels, sizeof(ChannelInfo *), NULL, NULL, NULL); + return info; } diff --git a/src/core/channels/VectorChannelInfo.h b/src/core/channels/VectorChannelInfo.h index 0a9b24e..118a71f 100644 --- a/src/core/channels/VectorChannelInfo.h +++ b/src/core/channels/VectorChannelInfo.h @@ -12,7 +12,7 @@ #define MCX_CORE_CHANNELS_VECTORCHANNELINFO_H #include "CentralParts.h" -#include "core/channels/ChannelInfo.h" +#include "objects/Vector.h" #ifdef __cplusplus extern "C" { @@ -53,7 +53,7 @@ struct VectorChannelInfo { size_t startIndex; size_t endIndex; - ObjectContainer * channels; // of ChannelInfo, the elements of the vector + Vector * channels; // of ChannelInfo, the elements of the vector }; #ifdef __cplusplus diff --git a/src/core/connections/Connection.c b/src/core/connections/Connection.c index 2f3edad..01bc80a 100644 --- a/src/core/connections/Connection.c +++ b/src/core/connections/Connection.c @@ -10,8 +10,9 @@ #include "CentralParts.h" #include "core/connections/Connection.h" -#include "core/connections/Connection_impl.h" #include "core/channels/Channel.h" +#include "core/channels/ChannelInfo.h" +#include "core/channels/ChannelValueReference.h" #include "core/connections/ConnectionInfo.h" #include "core/Conversion.h" @@ -21,34 +22,64 @@ // Filter #include "core/connections/filters/DiscreteFilter.h" +#include "core/connections/filters/MemoryFilter.h" #include "core/connections/filters/IntExtFilter.h" #include "core/connections/filters/ExtFilter.h" #include "core/connections/filters/IntFilter.h" +#include "util/compare.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -McxStatus CheckConnectivity(ObjectContainer * connections) { + +static void UpdateInChannelInfo(Component * comp, size_t idx) { + Databus * db = comp->GetDatabus(comp); + + if (DatabusInChannelsDefined(db)) { + Channel * channel = (Channel *) DatabusGetInChannel(db, idx); + if (channel) { + channel->info.connected = 1; + } + } +} + +static void UpdateOutChannelInfo(Component * comp, size_t idx) { + Databus * db = comp->GetDatabus(comp); + + if (DatabusOutChannelsDefined(db)) { + Channel * channel = (Channel *) DatabusGetOutChannel(db, idx); + if (channel) { + channel->info.connected = 1; + } + } +} + +McxStatus CheckConnectivity(Vector * connections) { size_t i = 0; - for (i = 0; i < connections->Size(connections); i++) { + size_t connSize = connections->Size(connections); + + for (i = 0; i < connSize; i++) { ConnectionInfo * connInfo = (ConnectionInfo *) connections->At(connections, i); ChannelInfo * info = NULL; - Component * target = connInfo->GetTargetComponent(connInfo); - int targetId = connInfo->GetTargetChannelID(connInfo); + Component * target = connInfo->targetComponent; + int targetId = connInfo->targetChannel; - Component * source = connInfo->GetSourceComponent(connInfo); - int sourceId = connInfo->GetSourceChannelID(connInfo); + Component * source = connInfo->sourceComponent; + int sourceId = connInfo->sourceChannel; info = DatabusInfoGetChannel(DatabusGetInInfo(target->GetDatabus(target)), targetId); if (info) { info->connected = 1; + UpdateInChannelInfo(target, targetId); } info = DatabusInfoGetChannel(DatabusGetOutInfo(source->GetDatabus(source)), sourceId); if (info) { info->connected = 1; + UpdateOutChannelInfo(source, sourceId); } } @@ -64,22 +95,19 @@ McxStatus MakeOneConnection(ConnectionInfo * info, InterExtrapolatingType isInte ChannelInfo * outInfo = NULL; ChannelInfo * inInfo = NULL; - source = info->GetSourceComponent(info); - target = info->GetTargetComponent(info); + source = info->sourceComponent; + target = info->targetComponent; // Get data types of involved channels - outInfo = DatabusInfoGetChannel(DatabusGetOutInfo(source->GetDatabus(source)), - info->GetSourceChannelID(info)); - - inInfo = DatabusInfoGetChannel(DatabusGetInInfo(target->GetDatabus(target)), - info->GetTargetChannelID(info)); + outInfo = DatabusInfoGetChannel(DatabusGetOutInfo(source->GetDatabus(source)), info->sourceChannel); + inInfo = DatabusInfoGetChannel(DatabusGetInInfo(target->GetDatabus(target)), info->targetChannel); if (!outInfo || !inInfo) { mcx_log(LOG_ERROR, "Connection: Make connection: Invalid arguments"); return RETURN_ERROR; } - InterExtrapolationParams * params = info->GetInterExtraParams(info); + InterExtrapolationParams * params = &info->interExtrapolationParams; if (EXTRAPOLATING == isInterExtrapolating) { if (params->extrapolationOrder != params->interpolationOrder) { @@ -89,7 +117,7 @@ McxStatus MakeOneConnection(ConnectionInfo * info, InterExtrapolatingType isInte isInterExtrapolating = INTEREXTRAPOLATING; } - info->SetInterExtrapolating(info, isInterExtrapolating); + info->isInterExtrapolating = isInterExtrapolating; connection = DatabusCreateConnection(source->GetDatabus(source), info); if (!connection) { @@ -100,35 +128,873 @@ McxStatus MakeOneConnection(ConnectionInfo * info, InterExtrapolatingType isInte return RETURN_OK; } +static void LogStepRatios(double sourceStep, double targetStep, double synchStep, const char * connString) { + if (sourceStep <= synchStep && targetStep <= synchStep) { + MCX_DEBUG_LOG("CONN %s: source <= synch && target <= synch", connString); + } else if (sourceStep <= synchStep && targetStep > synchStep) { + MCX_DEBUG_LOG("CONN %s: source <= synch && target > synch", connString); + } else if (sourceStep > synchStep && targetStep <= synchStep) { + MCX_DEBUG_LOG("CONN %s: source > synch && target <= synch", connString); + } else { + MCX_DEBUG_LOG("CONN %s: source > synch && target > synch", connString); + } +} + +static int ComponentMightNotRespectStepSize(Component * comp) { + return FALSE; +} + +static size_t DetermineFilterBufferSize(Component * source, Component * target, const char * connString) { + Model * model = source->GetModel(source); + Task * task = model->GetTask(model); + + double synchStep = task->GetTimeStep(task); + double sourceStep = source->GetTimeStep(source) > 0 ? source->GetTimeStep(source) : synchStep; + double targetStep = target->GetTimeStep(target) > 0 ? target->GetTimeStep(target) : synchStep; + + size_t buffSize = 0; + + if (model->config->overrideInterpolationBuffSize > 0) { + buffSize = model->config->overrideInterpolationBuffSize; + } + else if (ComponentMightNotRespectStepSize(source) || ComponentMightNotRespectStepSize(target)) { + buffSize = model->config->interpolationBuffSize; + } + else { + buffSize = (size_t) ceil(synchStep / sourceStep) + 1; + } + + buffSize += model->config->interpolationBuffSizeSafetyExt; + + if (buffSize > model->config->interpolationBuffSizeLimit) { + mcx_log(LOG_WARNING, "%s: buffer limit exceeded (%zu > &zu). Limit can be changed via MC_INTERPOLATION_BUFFER_SIZE_LIMIT.", + connString, buffSize, model->config->interpolationBuffSizeLimit); + + buffSize = model->config->interpolationBuffSizeLimit; + } + + return buffSize; +} + +static size_t MemoryFilterHistorySize(Component * sourceComp, Component * targetComp, int extDegree, const char * connString) { + size_t size = 0; + + Model * model = sourceComp->GetModel(sourceComp); + Task * task = model->GetTask(model); + + size_t limit = model->config->memFilterHistoryLimit; + + double syncStep = task->GetTimeStep(task); + + double sourceStep = sourceComp->GetTimeStep(sourceComp) ? sourceComp->GetTimeStep(sourceComp) : syncStep; + double targetStep = targetComp->GetTimeStep(targetComp) ? targetComp->GetTimeStep(targetComp) : syncStep; + + double syncToSrcRatio = syncStep / sourceStep; + double syncToTrgRatio = syncStep / targetStep; + + double trgToSyncRatio = targetStep / syncStep; + double trgToSrcRatio = targetStep / sourceStep; + + double srcToSyncRatio = sourceStep / syncStep; + double srcToTrgRatio = sourceStep / targetStep; + + double syncToSrc = round(syncToSrcRatio); + double syncToTrg = round(syncToTrgRatio); + + double trgToSync = round(trgToSyncRatio); + double trgToSrc = round(trgToSrcRatio); + + double srcToSync = round(srcToSyncRatio); + double srcToTrg = round(srcToTrgRatio); + + int useInputsAtEndTime = task->useInputsAtEndTime; + + StepTypeType stepType = task->GetStepTypeType(task); + + if (!model->config->useMemFilter) { + return 0; + } + + if (ComponentMightNotRespectStepSize(sourceComp) || ComponentMightNotRespectStepSize(targetComp)) { + return 0; + } + + if (STEP_TYPE_PARALLEL_MT == stepType) { + if (useInputsAtEndTime && extDegree == 0) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 2: T = t_a && t_a > t_b && t_a = n * t_b + else if (double_eq(syncStep, sourceStep) && srcToTrgRatio > 1.0 && double_eq(srcToTrgRatio, srcToTrg)) { + size = 2; + } + // CASE 3: T = t_a && t_a > t_b && t_a = m * t_b + else if (double_eq(syncStep, sourceStep) && srcToTrgRatio > 1.0 && !double_eq(srcToTrgRatio, srcToTrg)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 5: T > t_a && T = n * t_a && t_a > t_b && t_a = k * t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && srcToTrgRatio > 1.0 && double_eq(srcToTrgRatio, srcToTrg)) { + size = (size_t) syncToSrc + 1; + } + // CASE 6: T > t_a && T = n * t_a && t_a > t_b && t_a = m * t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && srcToTrgRatio > 1.0 && !double_eq(srcToTrgRatio, srcToTrg)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 10: T < t_a && T = t_b && n * T = t_a && n = 2 + else if (double_eq(syncStep, targetStep) && double_eq(srcToSyncRatio, 2.0)) { + size = 2; + } + // CASE 12: T < t_a && T = t_b && m * T = t_a && m <= 1.5 + else if (double_eq(syncStep, targetStep) && srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && (double_eq(srcToSyncRatio, 1.5) || srcToSyncRatio < 1.5)) { + size = 2; + } + // CASE 14: T < t_a && T < t_b && n * T = t_b && k * T = t_a && k / n = 2 + else if (trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSync / trgToSync; + if (double_eq(factor, 2.0)) { + size = 2; + } + } + // CASE 16: T < t_a && T < t_b && n * T = t_b && k * T = t_a && k / n in (1,2) + else if (trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSync / trgToSync; + if (!double_eq(factor, round(factor)) && factor > 1.0 && factor < 2.0) { + size = 2; + } + } + // CASE 18: T < t_a && T < t_b && n * T = t_b && p * T = t_a && p / n in (1,2) + else if (trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSyncRatio / trgToSync; + if (!double_eq(factor, round(factor)) && factor > 1.0 && factor < 2.0) { + size = 2; + } + } + // CASE 20: T < t_a && T < t_b && m * T = t_b && k * T = t_a && k / m in (1,2) + else if (trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSync / trgToSyncRatio; + if (!double_eq(factor, round(factor)) && factor > 1.0 && factor < 2.0) { + size = 2; + } + } + // CASE 22: T < t_a && T < t_b && m * T = t_b && k * T = t_a && k / m = 2 + else if (trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSync / trgToSyncRatio; + if (double_eq(factor, 2.0)) { + size = 2; + } + } + // CASE 24: T < t_a && T < t_b && m * T = t_b && p * T = t_a && p / m = 2 + else if (trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSyncRatio / trgToSyncRatio; + if (double_eq(factor, 2.0)) { + size = 2; + } + } + // CASE 26: T < t_a && T < t_b && m * T = t_b && p * T = t_a && p / m in (1,2) + else if (trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync)) { + double factor = srcToSyncRatio / trgToSyncRatio; + if (!double_eq(factor, round(factor)) && factor > 1.0 && factor < 2.0) { + size = 2; + } + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 37: T = t_b && t_b > t_a && t_b = m * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) trgToSrc + 1; + } + // CASE 39: T > t_b && T = n * t_b && t_b > t_a && t_b = m * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 40: T > t_b && t = m * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) trgToSrc + 1; + } + // CASE 41: T > t_b && t = m * t_b && t_b > t_a && t_b = p * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 43: T < t_b && T = t_a && m * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 45: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n not in {2,3,...} && k > n + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 46: T < t_b && T < t_a && n * T = t_a && p * T = t_b && p > n + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + size = 2; + } + // CASE 47: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m not in {2,3,...} && k > m + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 50: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m not in {2,3,...} && p > m + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t) syncToSrc + 1; + } + // CASE 52: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 53: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p not in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 54: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m not in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 56: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 57: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m < 2 + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor < 2.0 && !double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 58: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m > 2 && p * m not in {3,4,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 2.0 && !double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + else if (!useInputsAtEndTime && extDegree == 0) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 2: T = t_a && t_a > t_b && t_a = n * t_b + else if (double_eq(syncStep, sourceStep) && srcToTrgRatio > 1.0 && double_eq(srcToTrgRatio, srcToTrg)) { + size = 2; + } + // CASE 3: T = t_a && t_a > t_b && t_a = m * t_b + else if (double_eq(syncStep, sourceStep) && srcToTrgRatio > 1.0 && !double_eq(srcToTrgRatio, srcToTrg)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 5: T > t_a && T = n * t_a && t_a > t_b && t_a = k * t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && srcToTrgRatio > 1.0 && double_eq(srcToTrgRatio, srcToTrg)) { + size = (size_t) syncToSrc + 1; + } + // CASE 6: T > t_a && T = n * t_a && t_a > t_b && t_a = m * t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && srcToTrgRatio > 1.0 && !double_eq(srcToTrgRatio, srcToTrg)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 12: T < t_a && T = t_b && m * T = t_a && m <= 1.5 + else if (double_eq(syncStep, targetStep) && srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && (double_eq(srcToSyncRatio, 1.5) || srcToSyncRatio < 1.5)) { + size = 2; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) trgToSrc + 1; + } + // CASE 40: T > t_b && t = m * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) trgToSrc + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 43: T < t_b && T = t_a && m * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t) syncToSrc + 1; + } + // CASE 52: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 53: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p not in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 56: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + else if (useInputsAtEndTime) { + // not applicable + } + else if (!useInputsAtEndTime) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t) syncToSrc + 1; + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + } else if (STEP_TYPE_SEQUENTIAL == stepType) { + if (useInputsAtEndTime && extDegree == 0) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) trgToSrc + 1; + } + // CASE 40: T > t_b && t = m * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) trgToSrc + 1; + } + // CASE 41: T > t_b && t = m * t_b && t_b > t_a && t_b = p * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 43: T < t_b && T = t_a && m * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 45: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n not in {2,3,...} && k > n + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSync / srcToSync; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 46: T < t_b && T < t_a && n * T = t_a && p * T = t_b && p > n + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + size = 2; + } + // CASE 47: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m not in {2,3,...} && k > m + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 50: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m not in {2,3,...} && p > m + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync) && trgToSyncRatio > srcToSyncRatio) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t)syncToSrc + 1; + } + // CASE 52: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 53: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p not in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 54: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m not in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && !double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 56: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 58: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m > 2 && p * m not in {3,4,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 2.0 && !double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + else if (!useInputsAtEndTime && extDegree == 0) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t)syncToTrg * (size_t)trgToSrc + 1; + } + // CASE 40: T > t_b && t = m * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) trgToSrc + 1; + } + // CASE 41: T > t_b && t = m * t_b && t_b > t_a && t_b = p * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t)syncToSrc + 1; + } + // CASE 52: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 56: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + else if (useInputsAtEndTime) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) trgToSrc + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + } + else if (!useInputsAtEndTime) { + // CASE 1: T = t_a && t_a = t_b + if (double_eq(syncStep, sourceStep) && double_eq(sourceStep, targetStep)) { + size = 2; + } + // CASE 4: T > t_a && T = n * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) syncToSrc + 1; + } + // CASE 7: T > t_a && T = m * t_a && t_a = t_b + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && double_eq(sourceStep, targetStep)) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + // CASE 36: T = t_b && t_b > t_a && t_b = n * t_a + else if (double_eq(syncStep, targetStep) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) trgToSrc + 1; + } + // CASE 38: T > t_b && T = n * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) syncToTrg * (size_t) trgToSrc + 1; + } + // CASE 40: T > t_b && t = m * t_b && t_b > t_a && t_b = k * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) trgToSrc + 1; + } + // CASE 41: T > t_b && t = m * t_b && t_b > t_a && t_b = p * t_a + else if (syncToTrgRatio > 1.0 && !double_eq(syncToTrgRatio, syncToTrg) && trgToSrcRatio > 1.0 && !double_eq(trgToSrcRatio, trgToSrc)) { + size = (size_t) ceil(syncToTrgRatio) * (size_t) ceil(trgToSrcRatio) + 1; + } + // CASE 42: T < t_b && T = t_a && n * T = t_b + else if (double_eq(syncStep, sourceStep) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = 2; + } + // CASE 44: T < t_b && T < t_a &&& n * T = t_a && k * T = t_b && k / n in {2,3,...} + else if (srcToSyncRatio > 1.0 && double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSync; + if (factor > 1 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 48: T < t_b && T < t_a &&& m * T = t_a && k * T = t_b && k / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSync / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 49: T < t_b && T < t_a &&& m * T = t_a && p * T = t_b && p / m in {2,3,...} + else if (srcToSyncRatio > 1.0 && !double_eq(srcToSyncRatio, srcToSync) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = trgToSyncRatio / srcToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = 2; + } + } + // CASE 51: T < t_b && T > t_a && T = n * t_a && k * T = t_b + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + size = (size_t)syncToSrc + 1; + } + // CASE 52: T < t_b && T > t_a && T = n * t_a && p * T = t_b && n * p in {2,3,...} + else if (syncToSrcRatio > 1.0 && double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrc * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) syncToSrc + 1; + } + } + // CASE 55: T < t_b && T > t_a && T = m * t_a && k * T = t_b && k * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSync; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + // CASE 56: T < t_b && T > t_a && T = m * t_a && p * T = t_b && p * m in {2,3,...} + else if (syncToSrcRatio > 1.0 && !double_eq(syncToSrcRatio, syncToSrc) && trgToSyncRatio > 1.0 && !double_eq(trgToSyncRatio, trgToSync)) { + double factor = syncToSrcRatio * trgToSyncRatio; + if (factor > 1.0 && double_eq(factor, round(factor))) { + size = (size_t) ceil(syncToSrcRatio) + 1; + } + } + } + } + + if (size == 0) { + return 0; + } + + if (size + model->config->memFilterHistoryExtra > limit) { + mcx_log(LOG_WARNING, "%s: history size limit exceeded (%zu > &zu). Limit can be changed via MC_MEM_FILTER_HISTORY_LIMIT. " + "Disabling memory filter", + connString, size + model->config->memFilterHistoryExtra, limit); + + return 0; + } + + return size + model->config->memFilterHistoryExtra; +} + +static MemoryFilter * SetMemoryFilter(int reverseSearch, ChannelType * sourceType, size_t historySize) { + McxStatus retVal = RETURN_OK; + + MemoryFilter * filter = (MemoryFilter *)object_create(MemoryFilter); + if (!filter) { + mcx_log(LOG_ERROR, "Memory filter creation failed"); + return NULL; + } + + mcx_log(LOG_DEBUG, " Setting up memory filter. (%p)", filter); + mcx_log(LOG_DEBUG, " History size: %zu", historySize); + + retVal = filter->Setup(filter, sourceType, historySize, reverseSearch); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Memory filter setup failed"); + object_destroy(filter); + return NULL; + } -ChannelFilter * FilterFactory(Connection * connection) { + return filter; +} + +ChannelFilter * FilterFactory(ConnectionState * state, + InterExtrapolationType extrapolation_type, + InterExtrapolationParams * extrapolation_params, + ChannelType * channel_type, + InterExtrapolatingType inter_extrapolating_type, + int is_decoupled, + Component * sourceComp, + Component * targetComp, + const char * connString) { ChannelFilter * filter = NULL; McxStatus retVal; - ConnectionInfo * info = connection->GetInfo(connection); - InterExtrapolationType extrapolType = info->GetInterExtraType(info); - InterExtrapolationParams * params = info->GetInterExtraParams(info); + Model * model = sourceComp->GetModel(sourceComp); + Task * task = model->GetTask(model); + int useInputsAtEndTime = task->useInputsAtEndTime; - if (info->GetType(info) == CHANNEL_DOUBLE) { - if (!(INTERVAL_COUPLING == params->interpolationInterval && INTERVAL_SYNCHRONIZATION == params->extrapolationInterval)) { + if (ChannelTypeEq(channel_type, &ChannelTypeDouble)) { + if (!(INTERVAL_COUPLING == extrapolation_params->interpolationInterval && + INTERVAL_SYNCHRONIZATION == extrapolation_params->extrapolationInterval)) + { mcx_log(LOG_WARNING, "The use of inter/extrapolation interval settings for double is not supported"); } - if (extrapolType == INTEREXTRAPOLATION_POLYNOMIAL) { + if (extrapolation_type == INTEREXTRAPOLATION_POLYNOMIAL) { - InterExtrapolatingType isInterExtrapol = info->GetInterExtrapolating(info); - if (INTERPOLATING == isInterExtrapol && info->IsDecoupled(info)) { - isInterExtrapol = INTEREXTRAPOLATING; + if (INTERPOLATING == inter_extrapolating_type && is_decoupled) { + inter_extrapolating_type = INTEREXTRAPOLATING; } - int degree = (INTERPOLATING == isInterExtrapol) ? params->interpolationOrder : params->extrapolationOrder; + int degree = (INTERPOLATING == inter_extrapolating_type) ? extrapolation_params->interpolationOrder : + extrapolation_params->extrapolationOrder; - if (EXTRAPOLATING == isInterExtrapol || INTEREXTRAPOLATING == isInterExtrapol) { - if (INTEREXTRAPOLATING == isInterExtrapol) { + if (EXTRAPOLATING == inter_extrapolating_type || INTEREXTRAPOLATING == inter_extrapolating_type) { + size_t memFilterHist = MemoryFilterHistorySize(sourceComp, targetComp, extrapolation_params->extrapolationOrder, connString); + if (0 != memFilterHist) { + filter = (ChannelFilter *) SetMemoryFilter(useInputsAtEndTime, channel_type, memFilterHist); + if (!filter) { + return NULL; + } + } else if (INTEREXTRAPOLATING == inter_extrapolating_type) { IntExtFilter * intExtFilter = (IntExtFilter *)object_create(IntExtFilter); filter = (ChannelFilter *)intExtFilter; mcx_log(LOG_DEBUG, " Setting up dynamic filter. (%p)", filter); - mcx_log(LOG_DEBUG, " Interpolation order: %d, extrapolation order: %d", params->interpolationOrder, params->extrapolationOrder); - retVal = intExtFilter->Setup(intExtFilter, params->extrapolationOrder, params->interpolationOrder); + mcx_log(LOG_DEBUG, " Interpolation order: %d, extrapolation order: %d", extrapolation_params->interpolationOrder, extrapolation_params->extrapolationOrder); + size_t buffSize = DetermineFilterBufferSize(sourceComp, targetComp, connString); + retVal = intExtFilter->Setup(intExtFilter, extrapolation_params->extrapolationOrder, extrapolation_params->interpolationOrder, buffSize); if (RETURN_OK != retVal) { return NULL; } @@ -143,14 +1009,23 @@ ChannelFilter * FilterFactory(Connection * connection) { } } } else { - IntFilter * intFilter = (IntFilter *) object_create(IntFilter); - filter = (ChannelFilter *) intFilter; - mcx_log(LOG_DEBUG, " Setting up coupling step interpolation filter. (%p)", filter); - mcx_log(LOG_DEBUG, " Interpolation order: %d", degree); - retVal = intFilter->Setup(intFilter, degree); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Connection: Filter: Could not setup"); - return NULL; + size_t memFilterHist = MemoryFilterHistorySize(sourceComp, targetComp, degree, connString); + if (0 != memFilterHist) { + filter = (ChannelFilter *) SetMemoryFilter(useInputsAtEndTime, channel_type, memFilterHist); + if (!filter) { + return NULL; + } + } else { + IntFilter* intFilter = (IntFilter*)object_create(IntFilter); + filter = (ChannelFilter*)intFilter; + mcx_log(LOG_DEBUG, " Setting up coupling step interpolation filter. (%p)", filter); + mcx_log(LOG_DEBUG, " Interpolation order: %d", degree); + size_t buffSize = DetermineFilterBufferSize(sourceComp, targetComp, connString); + retVal = intFilter->Setup(intFilter, degree, buffSize); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "Connection: Filter: Could not setup"); + return NULL; + } } } @@ -162,92 +1037,83 @@ ChannelFilter * FilterFactory(Connection * connection) { } else { DiscreteFilter * discreteFilter = NULL; - if (!(0 == params->extrapolationOrder && - 0 == params->interpolationOrder && - INTERVAL_COUPLING == params->interpolationInterval && - INTERVAL_SYNCHRONIZATION == params->extrapolationInterval + if (!(0 == extrapolation_params->extrapolationOrder && + 0 == extrapolation_params->interpolationOrder && + INTERVAL_COUPLING == extrapolation_params->interpolationInterval && + INTERVAL_SYNCHRONIZATION == extrapolation_params->extrapolationInterval )) { mcx_log(LOG_WARNING, "Invalid inter/extrapolation settings for non-double connection detected"); } mcx_log(LOG_DEBUG, "Using constant synchronization step extrapolation for non-double connection"); discreteFilter = (DiscreteFilter *) object_create(DiscreteFilter); - discreteFilter->Setup(discreteFilter, info->GetType(info)); + discreteFilter->Setup(discreteFilter, channel_type); filter = (ChannelFilter *) discreteFilter; } - if (NULL == filter && info->GetType(info) == CHANNEL_DOUBLE) { + if (NULL == filter && ChannelTypeEq(channel_type, &ChannelTypeDouble)) { // TODO: add a check to avoid filters for non-multirate cases - ExtFilter * extFilter = (ExtFilter *) object_create(ExtFilter); - extFilter->Setup(extFilter, 0); - filter = (ChannelFilter *) extFilter; + size_t memFilterHist = MemoryFilterHistorySize(sourceComp, targetComp, 0, connString); + if (0 != memFilterHist) { + filter = (ChannelFilter *) SetMemoryFilter(useInputsAtEndTime, channel_type, memFilterHist); + if (!filter) { + return NULL; + } + } else { + ExtFilter * extFilter = (ExtFilter *) object_create(ExtFilter); + extFilter->Setup(extFilter, 0); + filter = (ChannelFilter *) extFilter; + } } - filter->AssignState(filter, &connection->data->state); + filter->AssignState(filter, state); return filter; } - -static ConnectionData * ConnectionDataCreate(ConnectionData * data) { - data->out = NULL; - data->in = NULL; - - data->info = NULL; - - data->value = NULL; - data->useInitialValue = FALSE; - - data->isActiveDependency = TRUE; - - ChannelValueInit(&data->store, CHANNEL_UNKNOWN); - - data->state = InCommunicationMode; - - data->NormalUpdateFrom = NULL; - data->NormalUpdateTo = NULL; - data->normalValue = NULL; - - return data; +static void * ConnectionGetValueReference(Connection * connection) { + return (void *)connection->value_; } - -static void ConnectionDataDestructor(ConnectionData * data) { - object_destroy(data->info); - - ChannelValueDestructor(&data->store); +static void ConnectionSetValueReference(Connection * connection, void * reference) { + connection->value_ = reference; } -OBJECT_CLASS(ConnectionData, Object); +static ChannelDimension * ConnectionGetValueDimension(Connection * connection) { + return NULL; +} +static ChannelType * ConnectionGetValueType(Connection * connection) { + ChannelOut * out = connection->out_; + Channel * channel = (Channel *) out; + ChannelInfo * channelInfo = &channel->info; -static void * ConnectionGetValueReference(Connection * connection) { - return (void *)connection->data->value; + return channelInfo->type; } static void ConnectionDestructor(Connection * connection) { - object_destroy(connection->data); + ChannelValueDestructor(&connection->store_); + DestroyConnectionInfo(&connection->info); } static ChannelOut * ConnectionGetSource(Connection * connection) { - return connection->data->out; + return connection->out_; } static ChannelIn * ConnectionGetTarget(Connection * connection) { - return connection->data->in; + return connection->in_; } static ConnectionInfo * ConnectionGetInfo(Connection * connection) { - return connection->data->info; + return &connection->info; } static int ConnectionIsDecoupled(Connection * connection) { - ConnectionInfo * info = connection->GetInfo(connection); - return info->IsDecoupled(info); + return ConnectionInfoIsDecoupled(&connection->info); } static int ConnectionIsDefinedDuringInit(Connection * connection) { @@ -262,11 +1128,11 @@ static void ConnectionSetDefinedDuringInit(Connection * connection) { static int ConnectionIsActiveDependency(Connection * conn) { - return conn->data->isActiveDependency; + return conn->isActiveDependency_; } static void ConnectionSetActiveDependency(Connection * conn, int active) { - conn->data->isActiveDependency = active; + conn->isActiveDependency_ = active; } static void ConnectionUpdateFromInput(Connection * connection, TimeInterval * time) { @@ -275,139 +1141,206 @@ static void ConnectionUpdateFromInput(Connection * connection, TimeInterval * ti static McxStatus ConnectionUpdateInitialValue(Connection * connection) { ConnectionInfo * info = connection->GetInfo(connection); - Channel * in = (Channel *) connection->data->in; - Channel * out = (Channel *) connection->data->out; + Channel * in = (Channel *) connection->in_; + Channel * out = (Channel *) connection->out_; + + ChannelInfo * inInfo = &in->info; + ChannelInfo * outInfo = &out->info; - ChannelInfo * inInfo = in->GetInfo(in); - ChannelInfo * outInfo = out->GetInfo(out); + ChannelValueReference * storeRef = NULL; - if (connection->data->state != InInitializationMode) { - char * buffer = info->ConnectionString(info); + McxStatus retVal = RETURN_OK; + + if (connection->state_ != InInitializationMode) { + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_ERROR, "Connection %s: Update initial value: Cannot update initial value outside of initialization mode", buffer); mcx_free(buffer); return RETURN_ERROR; } if (!out || !in) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_ERROR, "Connection %s: Update initial value: Cannot update initial value for unconnected connection", buffer); mcx_free(buffer); return RETURN_ERROR; } - if (inInfo->GetInitialValue(inInfo)) { - McxStatus retVal = RETURN_OK; - ChannelValue * store = &connection->data->store; - ChannelValue * inChannelValue = inInfo->GetInitialValue(inInfo); - ChannelValue * inValue = ChannelValueClone(inChannelValue); + storeRef = MakeChannelValueReference(&connection->store_, NULL); + if (!storeRef) { + mcx_log(LOG_ERROR, "Could not create store reference for initial connection"); + return RETURN_ERROR; + } - if (NULL == inValue) { - mcx_log(LOG_ERROR, "Could not clone initial value for initial connection"); - return RETURN_ERROR; + if (inInfo->initialValue) { + TypeConversion * typeConv = NULL; + ChannelValue * inChannelValue = inInfo->initialValue; + ChannelDimension * srcDim = NULL; + + srcDim = CloneChannelDimension(info->targetDimension); + if (info->targetDimension && !srcDim) { + mcx_log(LOG_ERROR, "Could not clone source dimension"); + retVal = RETURN_ERROR; + goto cleanup_1; + } + retVal = ChannelDimensionAlignIndicesWithZero(srcDim, inInfo->dimension); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "Dimension normalization failed"); + goto cleanup_1; } // The type of the stored value of a connection is the type of the out channel. // If the value is taken from the in channel, the value must be converted. // TODO: It might be a better idea to use the type of the in channel as type of the connection. // Such a change might be more complex to implement. - if (inValue->type != store->type) { - TypeConversion * typeConv = (TypeConversion *) object_create(TypeConversion); - Conversion * conv = (Conversion *) typeConv; - retVal = typeConv->Setup(typeConv, inValue->type, store->type); + if (!ChannelTypeConformable(storeRef->ref.value->type, NULL, inChannelValue->type, srcDim)) { + typeConv = (TypeConversion *) object_create(TypeConversion); + retVal = typeConv->Setup(typeConv, inChannelValue->type, info->targetDimension, storeRef->ref.value->type, NULL); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Could not set up initial type conversion"); - object_destroy(typeConv); - mcx_free(inValue); - return RETURN_ERROR; - } - retVal = conv->convert(conv, inValue); - object_destroy(typeConv); - - if (RETURN_ERROR == retVal) { - mcx_log(LOG_ERROR, "Could not convert type of initial value"); - mcx_free(inValue); - return RETURN_ERROR; + retVal = RETURN_ERROR; + goto cleanup_1; } } - retVal = ChannelValueSet(store, inValue); + retVal = ChannelValueReferenceSetFromPointer(storeRef, ChannelValueDataPointer(inChannelValue), srcDim, typeConv); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "Could not set up initial value in connection"); - mcx_free(inValue); - return RETURN_ERROR; + goto cleanup_1; + } + + connection->useInitialValue_ = TRUE; + +cleanup_1: + object_destroy(typeConv); + object_destroy(srcDim); + + if (retVal == RETURN_ERROR) { + goto cleanup; + } + } else if (outInfo->initialValue) { + ChannelDimension * targetDim = CloneChannelDimension(info->sourceDimension); + if (info->sourceDimension && !targetDim) { + mcx_log(LOG_ERROR, "Could not clone target dimension"); + retVal = RETURN_ERROR; + goto cleanup; } - mcx_free(inValue); - connection->data->useInitialValue = TRUE; - } else if (outInfo->GetInitialValue(outInfo)) { - ChannelValueSet(&connection->data->store, outInfo->GetInitialValue(outInfo)); - connection->data->useInitialValue = TRUE; + retVal = ChannelDimensionAlignIndicesWithZero(targetDim, outInfo->dimension); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "Dimension normalization failed"); + object_destroy(targetDim); + goto cleanup; + } + + ChannelValueReferenceSetFromPointer(storeRef, ChannelValueDataPointer(outInfo->initialValue), targetDim, NULL); + connection->useInitialValue_ = TRUE; } else { { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_WARNING, "Connection %s: No initial values are specified for the ports of the connection", buffer); mcx_free(buffer); } - ChannelValueInit(&connection->data->store, info->GetType(info)); + + ChannelType * storeType = ChannelTypeFromDimension(ConnectionInfoGetType(info), info->sourceDimension); + if (!storeType) { + mcx_log(LOG_ERROR, "Creating type from the dimension failed"); + retVal = RETURN_ERROR; + goto cleanup; + } + + ChannelValueInit(&connection->store_, storeType); } - return RETURN_OK; +cleanup: + DestroyChannelValueReference(storeRef); + + return retVal; } static void ConnectionInitUpdateFrom(Connection * connection, TimeInterval * time) { #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - Channel * channel = (Channel *) connection->data->out; - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] CONN (%s) UpdateFromInput", time->startTime, info->GetName(info)); + Channel * channel = (Channel *) connection->out_; + ChannelInfo * info = &channel->info; + MCX_DEBUG_LOG("[%f] CONN (%s) UpdateFromInput", time->startTime, ChannelInfoGetName(info)); } #endif // Do nothing } -static void ConnectionInitUpdateTo(Connection * connection, TimeInterval * time) { - Channel * channel = (Channel *) connection->data->out; +static McxStatus ConnectionInitSetToStore(Connection * connection) { + Channel* channel = (Channel*)connection->out_; + ChannelInfo* info = &channel->info; + ChannelValueReference * storeRef = MakeChannelValueReference(&connection->store_, NULL); + McxStatus retVal = RETURN_OK; + + if (!storeRef) { + mcx_log(LOG_ERROR, "Could not create store reference for initial connection"); + return RETURN_ERROR; + } + + ConnectionInfo * connInfo = connection->GetInfo(connection); + ChannelDimension * clone = CloneChannelDimension(connInfo->sourceDimension); + ChannelDimensionAlignIndicesWithZero(clone, info->dimension); + retVal = ChannelValueReferenceSetFromPointer(storeRef, channel->GetValueReference(channel), clone, NULL); + if (RETURN_ERROR == retVal) { + goto cleanup; + } + +cleanup: + DestroyChannelValueReference(storeRef); + + return retVal; +} + +static McxStatus ConnectionInitUpdateTo(Connection * connection, TimeInterval * time) { + Channel * channel = (Channel *) connection->out_; + ChannelInfo * info = &channel->info; #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] CONN (%s) UpdateToOutput", time->startTime, info->GetName(info)); + ChannelInfo * info = &channel->info; + MCX_DEBUG_LOG("[%f] CONN (%s) UpdateToOutput", time->startTime, ChannelInfoGetName(info)); } #endif - if (!connection->data->useInitialValue) { - ChannelValueSetFromReference(&connection->data->store, channel->GetValueReference(channel)); + if (!connection->useInitialValue_) { + if (RETURN_OK != connection->InitSetToStore(connection)) { + return RETURN_ERROR; + } if (channel->IsDefinedDuringInit(channel)) { connection->SetDefinedDuringInit(connection); } } else { connection->SetDefinedDuringInit(connection); } + + return RETURN_OK; } static McxStatus ConnectionEnterInitializationMode(Connection * connection) { #ifdef MCX_DEBUG - Channel * channel = (Channel *) connection->data->out; - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] CONN (%s) EnterInit", 0.0, info->GetName(info)); + Channel * channel = (Channel *) connection->out_; + ChannelInfo * info = &channel->info; + MCX_DEBUG_LOG("[%f] CONN (%s) EnterInit", 0.0, ChannelInfoGetName(info)); #endif - if (connection->data->state == InInitializationMode) { + if (connection->state_ == InInitializationMode) { mcx_log(LOG_ERROR, "Connection: Enter initialization mode: Called multiple times"); return RETURN_ERROR; } - connection->data->state = InInitializationMode; + connection->state_ = InInitializationMode; // save functions for normal mode - connection->data->NormalUpdateFrom = connection->UpdateFromInput; - connection->data->NormalUpdateTo = connection->UpdateToOutput; - connection->data->normalValue = connection->data->value; + connection->NormalUpdateFrom_ = connection->UpdateFromInput; + connection->NormalUpdateTo_ = connection->UpdateToOutput; + connection->normalValue_ = connection->value_; // set functions for initialization mode connection->UpdateFromInput = ConnectionInitUpdateFrom; connection->UpdateToOutput = ConnectionInitUpdateTo; - connection->data->value = ChannelValueReference(&connection->data->store); + connection->value_ = ChannelValueDataPointer(&connection->store_); connection->IsDefinedDuringInit = ConnectionIsDefinedDuringInit; connection->SetDefinedDuringInit = ConnectionSetDefinedDuringInit; @@ -421,21 +1354,21 @@ static McxStatus ConnectionExitInitializationMode(Connection * connection, doubl #ifdef MCX_DEBUG if (time < MCX_DEBUG_LOG_TIME) { - Channel * channel = (Channel *) connection->data->out; - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] CONN (%s) ExitInit", time, info->GetName(info)); + Channel * channel = (Channel *) connection->out_; + ChannelInfo * info = &channel->info; + MCX_DEBUG_LOG("[%f] CONN (%s) ExitInit", time, ChannelInfoGetName(info)); } #endif - if (connection->data->state != InInitializationMode) { + if (connection->state_ != InInitializationMode) { mcx_log(LOG_ERROR, "Connection: Exit initialization mode: Called multiple times"); return RETURN_ERROR; } // restore functions for normal mode - connection->UpdateFromInput = connection->data->NormalUpdateFrom; - connection->UpdateToOutput = connection->data->NormalUpdateTo; - connection->data->value = connection->data->normalValue; + connection->UpdateFromInput = connection->NormalUpdateFrom_; + connection->UpdateToOutput = connection->NormalUpdateTo_; + connection->value_ = connection->normalValue_; connection->IsDefinedDuringInit = NULL; connection->SetDefinedDuringInit(connection); // After initialization all values are defined connection->SetDefinedDuringInit = NULL; @@ -451,7 +1384,7 @@ static McxStatus ConnectionExitInitializationMode(Connection * connection, doubl } static McxStatus ConnectionEnterCommunicationMode(Connection * connection, double time) { - connection->data->state = InCommunicationMode; + connection->state_ = InCommunicationMode; return RETURN_OK; } @@ -459,7 +1392,7 @@ static McxStatus ConnectionEnterCommunicationMode(Connection * connection, doubl static McxStatus ConnectionEnterCouplingStepMode(Connection * connection , double communicationTimeStepSize, double sourceTimeStepSize, double targetTimeStepSize) { - connection->data->state = InCouplingStepMode; + connection->state_ = InCouplingStepMode; return RETURN_OK; } @@ -468,30 +1401,40 @@ McxStatus ConnectionSetup(Connection * connection, ChannelOut * out, ChannelIn * McxStatus retVal = RETURN_OK; Channel * chOut = (Channel *) out; - ChannelInfo * outInfo = chOut->GetInfo(chOut); + ChannelInfo * outInfo = &chOut->info; - connection->data->out = out; - connection->data->in = in; - connection->data->info = info; + connection->out_ = out; + connection->in_ = in; if (in->IsDiscrete(in)) { - info->SetDiscreteTarget(info); + info->hasDiscreteTarget = TRUE; } - ChannelValueInit(&connection->data->store, outInfo->GetType(outInfo)); + retVal = ConnectionInfoSetFrom(&connection->info, info); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + retVal = connection->SetupStore(connection, out, in, info); + if (RETURN_ERROR == retVal) { + char * buffer = ConnectionInfoConnectionString(info); + mcx_log(LOG_ERROR, "Connection %s: Store setup failed", buffer); + mcx_free(buffer); + return RETURN_ERROR; + } // Add connection to channel out retVal = out->RegisterConnection(out, connection); if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_ERROR, "Connection %s: Setup connection: Could not register with outport", buffer); mcx_free(buffer); return RETURN_ERROR; } - retVal = in->SetConnection(in, connection, outInfo->GetUnit(outInfo), outInfo->GetType(outInfo)); + retVal = in->RegisterConnection(in, connection, outInfo->unitString, outInfo->type); if (RETURN_OK != retVal) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_ERROR, "Connection %s: Setup connection: Could not register with inport", buffer); mcx_free(buffer); return RETURN_ERROR; @@ -500,19 +1443,33 @@ McxStatus ConnectionSetup(Connection * connection, ChannelOut * out, ChannelIn * return RETURN_OK; } -static Connection * ConnectionCreate(Connection * connection) { - connection->data = (ConnectionData *) object_create(ConnectionData); +McxStatus ConnectionSetupStore(Connection * connection, ChannelOut * out, ChannelIn * in, ConnectionInfo * info) { + Channel * chOut = (Channel *) out; + ChannelInfo * outInfo = &chOut->info; + ChannelType * storeType = ChannelTypeFromDimension(outInfo->type, info->sourceDimension); - if (!connection->data) { - return NULL; + if (!storeType) { + return RETURN_ERROR; } + ChannelValueInit(&connection->store_, storeType); + + return RETURN_OK; +} + +static Connection * ConnectionCreate(Connection * connection) { + McxStatus retVal = RETURN_OK; + connection->Setup = NULL; + connection->SetupStore = ConnectionSetupStore; connection->GetSource = ConnectionGetSource; connection->GetTarget = ConnectionGetTarget; connection->GetValueReference = ConnectionGetValueReference; + connection->SetValueReference = ConnectionSetValueReference; + connection->GetValueDimension = ConnectionGetValueDimension; + connection->GetValueType = ConnectionGetValueType; connection->GetInfo = ConnectionGetInfo; @@ -535,6 +1492,29 @@ static Connection * ConnectionCreate(Connection * connection) { connection->AddFilter = NULL; + connection->out_ = NULL; + connection->in_ = NULL; + + retVal = ConnectionInfoInit(&connection->info); + if (RETURN_ERROR == retVal) { + return NULL; + } + + connection->value_ = NULL; + connection->useInitialValue_ = FALSE; + + connection->isActiveDependency_ = TRUE; + + ChannelValueInit(&connection->store_, &ChannelTypeUnknown); + + connection->state_ = InCommunicationMode; + + connection->NormalUpdateFrom_ = NULL; + connection->NormalUpdateTo_ = NULL; + connection->normalValue_ = NULL; + + connection->InitSetToStore = ConnectionInitSetToStore; + return connection; } diff --git a/src/core/connections/Connection.h b/src/core/connections/Connection.h index f90ea6c..1e54b67 100644 --- a/src/core/connections/Connection.h +++ b/src/core/connections/Connection.h @@ -13,6 +13,7 @@ #include "CentralParts.h" #include "core/connections/ConnectionInfo.h" +#include "objects/Vector.h" #ifdef __cplusplus extern "C" { @@ -30,7 +31,7 @@ typedef enum { InInitializationMode } ConnectionState; -McxStatus CheckConnectivity(ObjectContainer * connections); +McxStatus CheckConnectivity(Vector * connections); McxStatus MakeOneConnection(ConnectionInfo * info, InterExtrapolatingType isInterExtrapolating); @@ -44,11 +45,18 @@ typedef McxStatus (* fConnectionSetup)(Connection * channel, struct ChannelOut * out, struct ChannelIn * in, struct ConnectionInfo * info); +typedef McxStatus (* fConnectionSetupStore)(Connection * conn, + struct ChannelOut * out, + struct ChannelIn * in, + struct ConnectionInfo * info); typedef struct ChannelOut * (* fConnectionGetSource)(Connection * connection); typedef struct ChannelIn * (* fConnectionGetTarget)(Connection * connection); typedef void * (* fConnectionGetValueReference)(Connection * connection); +typedef void (* fConnectionSetValueReference)(Connection * connection, void * reference); +typedef ChannelDimension * (*fConnectionGetValueDimension)(Connection * connection); +typedef ChannelType * (*fConnectionGetValueType)(Connection * connection); typedef ConnectionInfo * (* fConnectionGetInfo)(Connection * connection); @@ -60,9 +68,10 @@ typedef void (* fConnectionSetVoid)(Connection * connection); typedef void (* fConnectionUpdateFromInput)(Connection * connection, TimeInterval * time); -typedef void (* fConnectionUpdateToOutput)(Connection * connection, TimeInterval * time); +typedef McxStatus (* fConnectionUpdateToOutput)(Connection * connection, TimeInterval * time); typedef McxStatus (* fConnectionUpdateInitialValue)(Connection * connection); +typedef McxStatus (* fConnectionInitSetToStore)(Connection * connection); typedef McxStatus (* fConnectionEnterInitializationMode)(Connection * connection); typedef McxStatus (* fConnectionExitInitializationMode)(Connection * connection, double time); @@ -74,9 +83,38 @@ typedef McxStatus (* fConnectionAddFilter)(Connection * connection); extern const struct ObjectClass _Connection; + struct Connection { Object _; // base class + // source + struct ChannelOut * out_; + + // target + struct ChannelIn * in_; + + + // ---------------------------------------------------------------------- + // Value on channel + + const void * value_; + int useInitialValue_; + + ChannelValue store_; + + int isActiveDependency_; + + // Meta Data + ConnectionInfo info; + + // Current state of the connection in state machine + ConnectionState state_; + + // Temporary save functions during initialization mode + fConnectionUpdateFromInput NormalUpdateFrom_; + fConnectionUpdateToOutput NormalUpdateTo_; + const void * normalValue_; + /** * Virtual Method. * @@ -85,6 +123,8 @@ struct Connection { */ fConnectionSetup Setup; + fConnectionSetupStore SetupStore; + /** * Returns the source out channel. */ @@ -101,6 +141,18 @@ struct Connection { */ fConnectionGetValueReference GetValueReference; + fConnectionGetValueDimension GetValueDimension; + + fConnectionGetValueType GetValueType; + + fConnectionInitSetToStore InitSetToStore; + + /** + * Set the reference to the value of the connection. This value will be + * updated on each call to UpdateToOutput(). + */ + fConnectionSetValueReference SetValueReference; + /** * Returns the connection info struct. */ @@ -168,15 +220,22 @@ struct Connection { fConnectionUpdateInitialValue UpdateInitialValue; fConnectionAddFilter AddFilter; - - struct ConnectionData * data; } ; //------------------------------------------------------------------------------ // Common Functionality for Subclasses McxStatus ConnectionSetup(Connection * connection, struct ChannelOut * out, struct ChannelIn * in, ConnectionInfo * info); -struct ChannelFilter * FilterFactory(Connection * connection); +struct ChannelFilter *FilterFactory(ConnectionState *state, + InterExtrapolationType extrapolation_type, + InterExtrapolationParams *extrapolation_params, + ChannelType *channel_type, + InterExtrapolatingType inter_extrapolating_type, + int is_decoupled, + Component * sourceComp, + Component * targetComp, + const char * connString); + #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/connections/ConnectionInfo.c b/src/core/connections/ConnectionInfo.c index ba5ebda..4a4ae3c 100644 --- a/src/core/connections/ConnectionInfo.c +++ b/src/core/connections/ConnectionInfo.c @@ -9,7 +9,7 @@ ********************************************************************************/ #include "core/connections/ConnectionInfo.h" -#include "core/connections/ConnectionInfo_impl.h" +#include "core/channels/ChannelInfo.h" #include "core/Model.h" #include "core/Databus.h" @@ -18,215 +18,57 @@ extern "C" { #endif /* __cplusplus */ -static ConnectionInfoData * ConnectionInfoDataCreate(ConnectionInfoData * data) { - data->sourceComponent = NULL; - data->targetComponent = NULL; - data->sourceChannel = -1; - data->targetChannel = -1; - data->isDecoupled = FALSE; - data->isInterExtrapolating = INTERPOLATING; - - data->interExtrapolationType = INTEREXTRAPOLATION_NONE; - data->interExtrapolationParams = (InterExtrapolationParams *) mcx_malloc(sizeof(InterExtrapolationParams)); - if (!data->interExtrapolationParams) { - return NULL; - } - data->interExtrapolationParams->extrapolationInterval = INTERVAL_SYNCHRONIZATION; - data->interExtrapolationParams->extrapolationOrder = POLY_CONSTANT; - data->interExtrapolationParams->interpolationInterval = INTERVAL_COUPLING; - data->interExtrapolationParams->interpolationOrder = POLY_CONSTANT; - - data->decoupleType = DECOUPLE_DEFAULT; - data->decouplePriority = 0; - - data->hasDiscreteTarget = FALSE; - - return data; -} - -static void ConnectionInfoDataDestructor(ConnectionInfoData * data) { - if (data->interExtrapolationParams) { - mcx_free(data->interExtrapolationParams); - data->interExtrapolationParams = NULL; - } -} - -OBJECT_CLASS(ConnectionInfoData, Object); - - -static void ConnectionInfoSet( - ConnectionInfo * info, - Component * sourceComponent, - Component * targetComponent, - int sourceChannel, - int targetChannel, - int isDecoupled, - InterExtrapolatingType isInterExtrapolating, - InterExtrapolationType interExtrapolationType, - InterExtrapolationParams * interExtrapolationParams, - DecoupleType decoupleType, - int decouplePriority -) { - - info->data->sourceComponent = sourceComponent; - info->data->targetComponent = targetComponent; - info->data->sourceChannel = sourceChannel; - info->data->targetChannel = targetChannel; - info->data->isDecoupled = isDecoupled; - info->data->isInterExtrapolating = isInterExtrapolating; - info->data->interExtrapolationType = interExtrapolationType; - info->data->interExtrapolationParams = interExtrapolationParams; - info->data->decoupleType = decoupleType; - info->data->decouplePriority = decouplePriority; -} - -static void ConnectionInfoGet( - ConnectionInfo * info, - Component ** sourceComponent, - Component ** targetComponent, - int * sourceChannel, - int * targetChannel, - int * isDecoupled, - InterExtrapolatingType * isInterExtrapolating, - InterExtrapolationType * interExtrapolationType, - InterExtrapolationParams ** interExtrapolationParams, - DecoupleType * decoupleType, - int * decouplePriority -) { - - * sourceComponent = info->data->sourceComponent; - * targetComponent = info->data->targetComponent; - * sourceChannel = info->data->sourceChannel; - * targetChannel = info->data->targetChannel; - * isDecoupled = info->data->isDecoupled; - * isInterExtrapolating = info->data->isInterExtrapolating; - * interExtrapolationType = info->data->interExtrapolationType; - * interExtrapolationParams = info->data->interExtrapolationParams; - * decoupleType = info->data->decoupleType; - * decouplePriority = info->data->decouplePriority; -} - -static ConnectionInfo * ConnectionInfoClone(ConnectionInfo * info) { - ConnectionInfo * clone = (ConnectionInfo *) object_create(ConnectionInfo); - - if (!clone) { - return NULL; - } - - clone->data->sourceComponent = info->data->sourceComponent; - clone->data->targetComponent = info->data->targetComponent; - - clone->data->sourceChannel = info->data->sourceChannel; - clone->data->targetChannel = info->data->targetChannel; - - clone->data->isDecoupled = info->data->isDecoupled; - clone->data->isInterExtrapolating = info->data->isInterExtrapolating; - - clone->data->interExtrapolationType = info->data->interExtrapolationType; - - clone->data->interExtrapolationParams->extrapolationInterval = info->data->interExtrapolationParams->extrapolationInterval; - clone->data->interExtrapolationParams->extrapolationOrder = info->data->interExtrapolationParams->extrapolationOrder; - clone->data->interExtrapolationParams->interpolationInterval = info->data->interExtrapolationParams->interpolationInterval; - clone->data->interExtrapolationParams->interpolationOrder = info->data->interExtrapolationParams->interpolationOrder; - - clone->data->decoupleType = info->data->decoupleType; - clone->data->decouplePriority = info->data->decouplePriority; - - clone->data->hasDiscreteTarget = info->data->hasDiscreteTarget; - - return clone; -} - -static ConnectionInfo * ConnectionInfoCopy( - ConnectionInfo * info, - int sourceChannel, - int targetChannel) { - - ConnectionInfo * copy = info->Clone(info); - - copy->data->sourceChannel = sourceChannel; - copy->data->targetChannel = targetChannel; - - return copy; -} - -static int ConnectionInfoGetDecouplePriority(ConnectionInfo * info) { - return info->data->decouplePriority; +int ConnectionInfoIsDecoupled(ConnectionInfo * info) { + return info->isDecoupled_; } -static int ConnectionInfoGetSourceChannelID(ConnectionInfo * info) { - return info->data->sourceChannel; +void ConnectionInfoSetDecoupled(ConnectionInfo * info) { + info->isDecoupled_ = TRUE; } -static int ConnectionInfoGetTargetChannelID(ConnectionInfo * info) { - return info->data->targetChannel; -} - -static Component * ConnectionInfoGetSourceComponent(ConnectionInfo * info) { - return info->data->sourceComponent; -} - -static Component * ConnectionInfoGetTargetComponent(ConnectionInfo * info) { - return info->data->targetComponent; -} - -static DecoupleType ConnectionInfoGetDecoupleType(ConnectionInfo * info) { - return info->data->decoupleType; -} - -static int ConnectionInfoIsDecoupled(ConnectionInfo * info) { - return info->data->isDecoupled; -} - -static void ConnectionInfoSetDecoupled(ConnectionInfo * info) { - info->data->isDecoupled = TRUE; -} - -static InterExtrapolatingType ConnectionInfoGetInterExtrapolating(ConnectionInfo * info) { - return info->data->isInterExtrapolating; -} - -static void ConnectionInfoSetInterExtrapolating(ConnectionInfo * info, InterExtrapolatingType isInterExtrapolating) { - info->data->isInterExtrapolating = isInterExtrapolating; -} - -static ChannelType ConnectionInfoGetType(ConnectionInfo * info) { +ChannelType * ConnectionInfoGetType(ConnectionInfo * info) { //Return the data type of the corresponding outport of the source component Component * source = NULL; Databus * db = NULL; ChannelInfo * outInfo = NULL; + if (ChannelTypeIsValid(info->connType_)) { + return info->connType_; + } + if (NULL == info) { mcx_log(LOG_DEBUG, "ConnectionInfo: GetType: no info available"); - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } - source = info->GetSourceComponent(info); + source = info->sourceComponent; if (NULL == source) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, "ConnectionInfo '%s': GetType: no source available", buffer); mcx_free(buffer); - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } db = source->GetDatabus(source); if (NULL == db) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, "ConnectionInfo '%s': GetType: no databus available", buffer); mcx_free(buffer); - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } - outInfo = DatabusInfoGetChannel(DatabusGetOutInfo(db), info->GetSourceChannelID(info)); + outInfo = DatabusInfoGetChannel(DatabusGetOutInfo(db), info->sourceChannel); if (!outInfo) { - char * buffer = info->ConnectionString(info); + char * buffer = ConnectionInfoConnectionString(info); mcx_log(LOG_DEBUG, "ConnectionInfo '%s': GetType: no outinfo available", buffer); mcx_free(buffer); - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } - return outInfo->GetType(outInfo); + + info->connType_ = outInfo->type; + return info->connType_; } -static char * ConnectionInfoConnectionString(ConnectionInfo * info) { +char * ConnectionInfoConnectionString(ConnectionInfo * info) { Component * src = NULL; Component * trg = NULL; @@ -250,11 +92,11 @@ static char * ConnectionInfoConnectionString(ConnectionInfo * info) { return NULL; } - src = info->GetSourceComponent(info); - trg = info->GetTargetComponent(info); + src = info->sourceComponent; + trg = info->targetComponent; - srcID = info->GetSourceChannelID(info); - trgID = info->GetTargetChannelID(info); + srcID = info->sourceChannel; + trgID = info->targetChannel; if (!src || !trg) { @@ -276,9 +118,9 @@ static char * ConnectionInfoConnectionString(ConnectionInfo * info) { len = strlen("(, ) - (, )") + strlen(src->GetName(src)) - + strlen(srcInfo->GetName(srcInfo)) + + strlen(ChannelInfoGetName(srcInfo)) + strlen(trg->GetName(trg)) - + strlen(trgInfo->GetName(trgInfo)) + + strlen(ChannelInfoGetName(trgInfo)) + 1 /* terminator */; buffer = (char *) mcx_malloc(len * sizeof(char)); @@ -288,81 +130,58 @@ static char * ConnectionInfoConnectionString(ConnectionInfo * info) { sprintf(buffer, "(%s, %s) - (%s, %s)", src->GetName(src), - srcInfo->GetName(srcInfo), + ChannelInfoGetName(srcInfo), trg->GetName(trg), - trgInfo->GetName(trgInfo)); + ChannelInfoGetName(trgInfo)); return buffer; } -static InterExtrapolationType ConnectionInfoGetInterExtraType(ConnectionInfo * info) { - return info->data->interExtrapolationType; -} - -static InterExtrapolationParams * ConnectionInfoGetInterExtraParams(ConnectionInfo * info) { - return info->data->interExtrapolationParams; +void DestroyConnectionInfo(ConnectionInfo * info) { + if (info->sourceDimension) { DestroyChannelDimension(info->sourceDimension); } + if (info->targetDimension) { DestroyChannelDimension(info->targetDimension); } } -static void ConnectionInfoSetInterExtraType(ConnectionInfo * info, InterExtrapolationType type) { - info->data->interExtrapolationType = type; -} +McxStatus ConnectionInfoSetFrom(ConnectionInfo * info, const ConnectionInfo * other) { + McxStatus retVal = RETURN_OK; -static void ConnectionInfoDestructor(ConnectionInfo * info) { - object_destroy(info->data); -} + memcpy(info, other, sizeof(ConnectionInfo)); -static int ConnectionHasDiscreteTarget(ConnectionInfo * info) { - return info->data->hasDiscreteTarget; -} + info->sourceDimension = CloneChannelDimension(other->sourceDimension); + info->targetDimension = CloneChannelDimension(other->targetDimension); -static void ConnectionSetDiscreteTarget(ConnectionInfo * info) { - info->data->hasDiscreteTarget = TRUE; + return RETURN_OK; } -static ConnectionInfo * ConnectionInfoCreate(ConnectionInfo * info) { - info->data = (ConnectionInfoData *) object_create(ConnectionInfoData); - - if (!info->data) { - return NULL; - } - - info->Set = ConnectionInfoSet; - info->Get = ConnectionInfoGet; - - info->Clone = ConnectionInfoClone; - info->Copy = ConnectionInfoCopy; - - info->GetSourceChannelID = ConnectionInfoGetSourceChannelID; - info->GetTargetChannelID = ConnectionInfoGetTargetChannelID; - - info->GetSourceComponent = ConnectionInfoGetSourceComponent; - info->GetTargetComponent = ConnectionInfoGetTargetComponent; - - info->GetDecoupleType = ConnectionInfoGetDecoupleType; - info->GetDecouplePriority = ConnectionInfoGetDecouplePriority; +McxStatus ConnectionInfoInit(ConnectionInfo * info) { + info->sourceComponent = NULL; + info->targetComponent = NULL; - info->IsDecoupled = ConnectionInfoIsDecoupled; - info->SetDecoupled = ConnectionInfoSetDecoupled; + info->sourceChannel = -1; + info->targetChannel = -1; - info->GetInterExtrapolating = ConnectionInfoGetInterExtrapolating; - info->SetInterExtrapolating = ConnectionInfoSetInterExtrapolating; + info->isDecoupled_ = FALSE; + info->isInterExtrapolating = INTERPOLATING; - info->HasDiscreteTarget = ConnectionHasDiscreteTarget; - info->SetDiscreteTarget = ConnectionSetDiscreteTarget; + info->interExtrapolationType = INTEREXTRAPOLATION_NONE; + info->interExtrapolationParams.extrapolationInterval = INTERVAL_SYNCHRONIZATION; + info->interExtrapolationParams.extrapolationOrder = POLY_CONSTANT; + info->interExtrapolationParams.interpolationInterval = INTERVAL_COUPLING; + info->interExtrapolationParams.interpolationOrder = POLY_CONSTANT; - info->GetType = ConnectionInfoGetType; + info->decoupleType = DECOUPLE_DEFAULT; + info->decouplePriority = 0; - info->ConnectionString = ConnectionInfoConnectionString; + info->hasDiscreteTarget = FALSE; - info->GetInterExtraType = ConnectionInfoGetInterExtraType; - info->GetInterExtraParams = ConnectionInfoGetInterExtraParams; + info->connType_ = &ChannelTypeUnknown; - info->SetInterExtraType = ConnectionInfoSetInterExtraType; + info->sourceDimension = NULL; + info->targetDimension = NULL; - return info; + return RETURN_OK; } -OBJECT_CLASS(ConnectionInfo, Object); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/connections/ConnectionInfo.h b/src/core/connections/ConnectionInfo.h index 2c5f492..7b27627 100644 --- a/src/core/connections/ConnectionInfo.h +++ b/src/core/connections/ConnectionInfo.h @@ -1,5 +1,5 @@ /******************************************************************************** - * Copyright (c) 2020 AVL List GmbH and others + * Copyright (c) 2022 AVL List GmbH and others * * This program and the accompanying materials are made available under the * terms of the Apache Software License 2.0 which is available at @@ -11,10 +11,9 @@ #ifndef MCX_CORE_CONNECTIONS_CONNECTIONINFO_H #define MCX_CORE_CONNECTIONS_CONNECTIONINFO_H -#include "core/channels/ChannelInfo.h" -#include "objects/ObjectContainer.h" #include "CentralParts.h" #include "core/Component_interface.h" +#include "core/channels/ChannelDimension.h" #define DECOUPLE_DEFAULT DECOUPLE_IFNEEDED @@ -22,113 +21,50 @@ extern "C" { #endif /* __cplusplus */ -// ---------------------------------------------------------------------- -// ConnectionInfo -struct ConnectionInfo; -typedef struct ConnectionInfo ConnectionInfo; +typedef struct Component Component; -typedef void (*fConnectionInfoSet)( - ConnectionInfo * info - , Component * sourceComponent - , Component * targetComponent - , int sourceChannel - , int targetChannel - , int isDecoupled - , InterExtrapolatingType isInterExtrapolating - , InterExtrapolationType interExtrapolationType - , InterExtrapolationParams * interExtrapolationParams - , DecoupleType decoupleType - , int decouplePriority -); -typedef void (* fConnectionInfoGet)( - ConnectionInfo * info - , Component ** sourceComponent - , Component ** targetComponent - , int * sourceChannel - , int * targetChannel - , int * isDecoupled - , InterExtrapolatingType * isInterExtrapolating - , InterExtrapolationType * interExtrapolationType - , InterExtrapolationParams ** interExtrapolationParams - , DecoupleType * decoupleType - , int * decouplePriority -); +typedef struct ConnectionInfo { + Component * sourceComponent; + Component * targetComponent; -typedef ConnectionInfo * (* fConnectionInfoClone)( - ConnectionInfo * info); + int sourceChannel; + int targetChannel; -typedef ConnectionInfo * (* fConnectionInfoCopy)( - ConnectionInfo * info, - int sourceChannel, - int targetChannel); + // Decouple Info: If this connection is decoupled because of an algebraic loop + // in the model (this means that the value of the source for the target is + // behind one timestep) + int isDecoupled_; -typedef int (* fConnectionInfoGetChannelID)(ConnectionInfo * info); + int hasDiscreteTarget; -typedef Component * (* fConnectionInfoGetSourceComponent)(ConnectionInfo * info); -typedef Component * (* fConnectionInfoGetTargetComponent)(ConnectionInfo * info); + ChannelType * connType_; -typedef DecoupleType (* fConnectionInfoGetDecoupleType)(ConnectionInfo * info); + InterExtrapolatingType isInterExtrapolating; -typedef ChannelType (* fConnectionInfoGetType)(ConnectionInfo * info); + InterExtrapolationType interExtrapolationType; + InterExtrapolationParams interExtrapolationParams; -typedef int (* fConnectionInfoGetBool)(ConnectionInfo * info); -typedef int (* fConnectionInfoGetInt)(ConnectionInfo * info); -typedef InterExtrapolatingType (* fConnectionInfoGetInterExtrapolating)(ConnectionInfo * info); + DecoupleType decoupleType; + int decouplePriority; -typedef void (* fConnectionInfoSetVoid)(ConnectionInfo * info); -typedef void (* fConnectionInfoSetInterExtrapolating)(ConnectionInfo * info, InterExtrapolatingType isInterExtrapolating); -typedef char * (* fConnectionInfoConnectionString)(ConnectionInfo * info); + ChannelDimension * sourceDimension; + ChannelDimension * targetDimension; +} ConnectionInfo; -typedef InterExtrapolationType (* fConnectionInfoGetInterExtraType)(ConnectionInfo * info); -typedef InterExtrapolationParams * (* fConnectionInfoGetInterExtraParams)(ConnectionInfo * info); -typedef void (* fConnectionInfoSetInterExtraType)(ConnectionInfo * info, InterExtrapolationType type); +McxStatus ConnectionInfoInit(ConnectionInfo * info); +McxStatus ConnectionInfoSetFrom(ConnectionInfo * info, const ConnectionInfo * other); +void DestroyConnectionInfo(ConnectionInfo * info); -typedef int (*fConnectionHasDiscreteTarget)(ConnectionInfo * info); -typedef void (*fConnectionSetDiscreteTarget)(ConnectionInfo * info); -extern const struct ObjectClass _ConnectionInfo; +ChannelType * ConnectionInfoGetType(ConnectionInfo * info); -struct ConnectionInfo { - Object _; // base class +int ConnectionInfoIsDecoupled(ConnectionInfo * info); +void ConnectionInfoSetDecoupled(ConnectionInfo * info); - fConnectionInfoSet Set; - fConnectionInfoGet Get; - - fConnectionInfoClone Clone; - fConnectionInfoCopy Copy; - - fConnectionInfoGetChannelID GetSourceChannelID; - fConnectionInfoGetChannelID GetTargetChannelID; - - fConnectionInfoGetSourceComponent GetSourceComponent; - fConnectionInfoGetTargetComponent GetTargetComponent; - - fConnectionInfoGetDecoupleType GetDecoupleType; - fConnectionInfoGetInt GetDecouplePriority; - - fConnectionInfoGetBool IsDecoupled; - fConnectionInfoSetVoid SetDecoupled; - - fConnectionInfoGetInterExtrapolating GetInterExtrapolating; - fConnectionInfoSetInterExtrapolating SetInterExtrapolating; - - fConnectionHasDiscreteTarget HasDiscreteTarget; - fConnectionSetDiscreteTarget SetDiscreteTarget; - - fConnectionInfoGetType GetType; - - fConnectionInfoConnectionString ConnectionString; - - fConnectionInfoGetInterExtraType GetInterExtraType; - fConnectionInfoGetInterExtraParams GetInterExtraParams; - - fConnectionInfoSetInterExtraType SetInterExtraType; - - struct ConnectionInfoData * data; -} ; +char * ConnectionInfoConnectionString(ConnectionInfo * info); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/connections/ConnectionInfoFactory.c b/src/core/connections/ConnectionInfoFactory.c index c963d10..9f0ef0b 100644 --- a/src/core/connections/ConnectionInfoFactory.c +++ b/src/core/connections/ConnectionInfoFactory.c @@ -10,222 +10,305 @@ #include "core/connections/ConnectionInfoFactory.h" #include "core/connections/ConnectionInfo.h" +#include "core/channels/ChannelDimension.h" #include "core/Databus.h" +#include "objects/Vector.h" +#include "util/stdlib.h" #include "util/string.h" +#include "core/channels/ChannelValue.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -static ConnectionInfo * ConnectionInfoFactoryCreateConnectionInfo(ObjectContainer * components, - ConnectionInput * connInput, - Component * sourceCompOverride, - Component * targetCompOverride) { - McxStatus retVal = RETURN_OK; - ConnectionInfo * info = NULL; - Component * sourceComp = NULL; - Component * targetComp = NULL; +static McxStatus ConnectionInfoFactoryInitConnectionInfo(ConnectionInfo * info, + ObjectContainer * components, + ConnectionInput * connInput, + Component * sourceCompOverride, + Component * targetCompOverride) { + McxStatus retVal = RETURN_OK; - int sourceChannel = 0; - int targetChannel = 0; int id = 0; - int connectionInverted = 0; + char * strToChannel = NULL; + char * strFromChannel = NULL; - int isDecoupled = FALSE; - InterExtrapolatingType isInterExtrapolating = INTERPOLATING; + retVal = ConnectionInfoInit(info); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "Initializing the ConnectionInfo object failed"); + goto cleanup; + } - InterExtrapolationType interExtrapolationType; - InterExtrapolationParams * interExtrapolationParams = NULL; + // source component + { + // use conn endpoints from caller if they are not in components + info->sourceComponent = sourceCompOverride; + + if (info->sourceComponent == NULL) { + char * inputFromComponent = connInput->fromType == ENDPOINT_SCALAR ? connInput->from.scalarEndpoint->component : + connInput->from.vectorEndpoint->component; + if (inputFromComponent == NULL) { + retVal = input_element_error((InputElement*)connInput, "Source element is not specified"); + goto cleanup; + } - DecoupleType decoupleType; - int decouplePriority = 0; + if (0 == strlen(inputFromComponent)) { + retVal = input_element_error((InputElement*)connInput, "Source element name is empty"); + goto cleanup; + } - // temporary data for reading not used in info->Set() - char * strFromChannel = NULL; - char * strToChannel = NULL; + id = components->GetNameIndex(components, inputFromComponent); + if (id < 0) { + retVal = input_element_error((InputElement*)connInput, "Source element %s does not exist", + inputFromComponent); + goto cleanup; + } - // weak pointers to endpoint data - char * inputToChannel = NULL; - char * inputToComponent = NULL; - char * inputFromChannel = NULL; - char * inputFromComponent = NULL; + info->sourceComponent = (Component *) components->elements[id]; + } + } - Databus * databus = NULL; - DatabusInfo * databusInfo = NULL; + // target component + { + // use conn endpoints from caller if they are not in components + info->targetComponent = targetCompOverride; + + if (info->targetComponent == NULL) { + char * inputToComponent = connInput->toType == ENDPOINT_SCALAR ? connInput->to.scalarEndpoint->component : + connInput->to.vectorEndpoint->component; + if (inputToComponent == NULL) { + retVal = input_element_error((InputElement*)connInput, "Target element is not specified"); + goto cleanup; + } - info = (ConnectionInfo *)object_create(ConnectionInfo); - if (NULL == info) { - return NULL; - } + if (0 == strlen(inputToComponent)) { + retVal = input_element_error((InputElement*)connInput, "Target element name is empty"); + goto cleanup; + } - // get default values - info->Get( - info, - &sourceComp, - &targetComp, - &sourceChannel, - &targetChannel, - &isDecoupled, - &isInterExtrapolating, - &interExtrapolationType, - &interExtrapolationParams, - &decoupleType, - &decouplePriority - ); - - // use conn endpoints from caller if they are not in components - sourceComp = sourceCompOverride; - targetComp = targetCompOverride; + id = components->GetNameIndex(components, inputToComponent); + if (id < 0) { + retVal = input_element_error((InputElement*)connInput, "Target element %s does not exist", + inputToComponent); + goto cleanup; + } - // source component - if (sourceComp == NULL) { - inputFromComponent = connInput->fromType == ENDPOINT_SCALAR ? connInput->from.scalarEndpoint->component : - connInput->from.vectorEndpoint->component; - if (inputFromComponent == NULL) { - retVal = input_element_error((InputElement*)connInput, "Source element is not specified"); - goto cleanup; + info->targetComponent = (Component *) components->elements[id]; } + } + + // source channel + { + Databus * databus = info->sourceComponent->GetDatabus(info->sourceComponent); + DatabusInfo * databusInfo = DatabusGetOutInfo(databus); + ChannelInfo * sourceInfo = NULL; + + char * inputFromChannel = connInput->fromType == ENDPOINT_SCALAR ? connInput->from.scalarEndpoint->channel : + connInput->from.vectorEndpoint->channel; - if (0 == strlen(inputFromComponent)) { - retVal = input_element_error((InputElement*)connInput, "Source element name is empty"); + strFromChannel = mcx_string_copy(inputFromChannel); + if (0 == strlen(strFromChannel)) { + retVal = input_element_error((InputElement*)connInput, "Source port name is empty"); goto cleanup; } - id = components->GetNameIndex(components, inputFromComponent); - if (id < 0) { - retVal = input_element_error((InputElement*)connInput, "Source element %s does not exist", - inputFromComponent); - goto cleanup; + // arrays/multiplexing: source slice dimensions + if (connInput->fromType == ENDPOINT_VECTOR) { + ChannelDimension * sourceDimension = MakeChannelDimension(); + if (!sourceDimension) { + retVal = RETURN_ERROR; + goto cleanup; + } + + if (RETURN_OK != ChannelDimensionSetup(sourceDimension, 1)) { + mcx_log(LOG_ERROR, "Source port %s: Could not set number of dimensions", strFromChannel); + retVal = RETURN_ERROR; + DestroyChannelDimension(sourceDimension); + goto cleanup; + } + + if (RETURN_OK != ChannelDimensionSetDimension(sourceDimension, 0, connInput->from.vectorEndpoint->startIndex, connInput->from.vectorEndpoint->endIndex)) { + mcx_log(LOG_ERROR, "Source port %s: Could not set dimension boundaries", strFromChannel); + retVal = RETURN_ERROR; + DestroyChannelDimension(sourceDimension); + goto cleanup; + } + + info->sourceDimension = sourceDimension; } - sourceComp = (Component *) components->elements[id]; - } + info->sourceChannel = DatabusInfoGetChannelID(databusInfo, strFromChannel); + if (info->sourceChannel < 0) { + // the connection might be inverted, see SSP 1.0 specification (section 5.3.2.1, page 47) - // source channel - inputFromChannel = connInput->fromType == ENDPOINT_SCALAR ? connInput->from.scalarEndpoint->channel : - connInput->from.vectorEndpoint->channel; - strFromChannel = mcx_string_copy(inputFromChannel); - if (0 == strlen(strFromChannel)) { - retVal = input_element_error((InputElement*)connInput, "Source port name is empty"); - goto cleanup; - } + databusInfo = DatabusGetInInfo(databus); + info->sourceChannel = DatabusInfoGetChannelID(databusInfo, strFromChannel); + + if (info->sourceChannel < 0) { + mcx_log(LOG_ERROR, "Connection: Source port %s of element %s does not exist", + strFromChannel, info->sourceComponent->GetName(info->sourceComponent)); + retVal = RETURN_ERROR; + goto cleanup; + } else { + connectionInverted = 1; + } + } - if (connInput->fromType == ENDPOINT_VECTOR) { - mcx_free(strFromChannel); - strFromChannel = CreateIndexedName(inputFromChannel, connInput->from.vectorEndpoint->startIndex); - if (!strFromChannel) { + // check that the source endpoint "fits" into the channel + sourceInfo = DatabusInfoGetChannel(databusInfo, info->sourceChannel); + if (!ChannelDimensionIncludedIn(info->sourceDimension, sourceInfo->dimension)) { + char* channelDimString = ChannelDimensionString(sourceInfo->dimension); + char* connDimString = ChannelDimensionString(info->sourceDimension); + mcx_log(LOG_ERROR, + "Connection: Dimension index mismatch between source port %s of element %s and the connection endpoint: %s vs %s", + strFromChannel, + info->sourceComponent->GetName(info->sourceComponent), + channelDimString, + connDimString); retVal = RETURN_ERROR; + + if (channelDimString) { + mcx_free(channelDimString); + } + if (connDimString) { + mcx_free(connDimString); + } + goto cleanup; } } - // target component - if (targetComp == NULL) { - inputToComponent = connInput->toType == ENDPOINT_SCALAR ? connInput->to.scalarEndpoint->component : - connInput->to.vectorEndpoint->component; - if (inputToComponent == NULL) { - retVal = input_element_error((InputElement*)connInput, "Target element is not specified"); + // target channel + { + Databus * databus = info->targetComponent->GetDatabus(info->targetComponent); + DatabusInfo * databusInfo = NULL; + ChannelInfo * targetInfo = NULL; + + char * inputToChannel = connInput->toType == ENDPOINT_SCALAR ? connInput->to.scalarEndpoint->channel : + connInput->to.vectorEndpoint->channel; + strToChannel = mcx_string_copy(inputToChannel); + if (0 == strlen(strToChannel)) { + retVal = input_element_error((InputElement*)connInput, "Target port name is empty"); goto cleanup; } - if (0 == strlen(inputToComponent)) { - retVal = input_element_error((InputElement*)connInput, "Target element name is empty"); - goto cleanup; + if (0 == connectionInverted) { + databusInfo = DatabusGetInInfo(databus); + } else { + databusInfo = DatabusGetOutInfo(databus); } - id = components->GetNameIndex(components, inputToComponent); - if (id < 0) { - retVal = input_element_error((InputElement*)connInput, "Target element %s does not exist", - inputToComponent); - goto cleanup; - } + // arrays/multiplexing: target slice dimensions + if (connInput->toType == ENDPOINT_VECTOR) { + ChannelDimension * targetDimension = MakeChannelDimension(); + if (!targetDimension) { + retVal = RETURN_ERROR; + goto cleanup; + } - targetComp = (Component *) components->elements[id]; - } + if (RETURN_OK != ChannelDimensionSetup(targetDimension, 1)) { + mcx_log(LOG_ERROR, "Target port %s: Could not set number of dimensions", strToChannel); + retVal = RETURN_ERROR; + DestroyChannelDimension(targetDimension); + goto cleanup; + } - // target channel - inputToChannel = connInput->toType == ENDPOINT_SCALAR ? connInput->to.scalarEndpoint->channel : - connInput->to.vectorEndpoint->channel; - strToChannel = mcx_string_copy(inputToChannel); - if (0 == strlen(strToChannel)) { - retVal = input_element_error((InputElement*)connInput, "Target port name is empty"); - goto cleanup; - } + if (RETURN_OK != ChannelDimensionSetDimension(targetDimension, + 0, + (size_t) connInput->to.vectorEndpoint->startIndex, + (size_t) connInput->to.vectorEndpoint->endIndex)) + { + mcx_log(LOG_ERROR, "Target port %s: Could not set dimension boundaries", strToChannel); + retVal = RETURN_ERROR; + DestroyChannelDimension(targetDimension); + goto cleanup; + } - if (connInput->toType == ENDPOINT_VECTOR) { - mcx_free(strToChannel); - strToChannel = CreateIndexedName(inputToChannel, connInput->to.vectorEndpoint->startIndex); - if (!strToChannel) { - retVal = RETURN_ERROR; - goto cleanup; + info->targetDimension = targetDimension; } - } - - databus = sourceComp->GetDatabus(sourceComp); - databusInfo = DatabusGetOutInfo(databus); - sourceChannel = DatabusInfoGetChannelID(databusInfo, strFromChannel); - if (sourceChannel < 0) { - // the connection might be inverted, see SSP 1.0 specification (section 5.3.2.1, page 47) - databusInfo = DatabusGetInInfo(databus); - sourceChannel = DatabusInfoGetChannelID(databusInfo, strFromChannel); - - if (sourceChannel < 0) { - mcx_log(LOG_ERROR, "Connection: Source port %s of element %s does not exist", - strFromChannel, sourceComp->GetName(sourceComp)); + info->targetChannel = DatabusInfoGetChannelID(databusInfo, strToChannel); + if (info->targetChannel < 0) { + if (0 == connectionInverted) { + mcx_log(LOG_ERROR, "Connection: Target port %s of element %s does not exist", + strToChannel, info->targetComponent->GetName(info->targetComponent)); + } else { + mcx_log(LOG_ERROR, "Connection: Source port %s of element %s does not exist", + strToChannel, info->targetComponent->GetName(info->targetComponent)); + } retVal = RETURN_ERROR; goto cleanup; - } else { - connectionInverted = 1; } - } - databus = targetComp->GetDatabus(targetComp); + // check that the target endpoint "fits" into the channel + targetInfo = DatabusInfoGetChannel(databusInfo, info->targetChannel); + if (!ChannelDimensionIncludedIn(info->targetDimension, targetInfo->dimension)) { + char * channelDimString = ChannelDimensionString(targetInfo->dimension); + char * connDimString = ChannelDimensionString(info->targetDimension); + mcx_log(LOG_ERROR, + "Connection: Dimension index mismatch between connection endpoint and the target port %s of element %s: %s vs %s", + strToChannel, + info->targetComponent->GetName(info->targetComponent), + connDimString, + channelDimString); + retVal = RETURN_ERROR; - if (0 == connectionInverted) { - databusInfo = DatabusGetInInfo(databus); - } else { - databusInfo = DatabusGetOutInfo(databus); - } + if (channelDimString) { + mcx_free(channelDimString); + } + if (connDimString) { + mcx_free(connDimString); + } - targetChannel = DatabusInfoGetChannelID(databusInfo, strToChannel); - if (targetChannel < 0) { - if (0 == connectionInverted) { - mcx_log(LOG_ERROR, "Connection: Target port %s of element %s does not exist", - strToChannel, targetComp->GetName(targetComp)); - } else { - mcx_log(LOG_ERROR, "Connection: Source port %s of element %s does not exist", - strToChannel, targetComp->GetName(targetComp)); + goto cleanup; } - retVal = RETURN_ERROR; - goto cleanup; } + // swap endpoints if connection is inverted if (connectionInverted) { - int tmp = sourceChannel; - Component * tmpCmp = sourceComp; + int tmp = info->sourceChannel; + Component * tmpCmp = info->sourceComponent; + ChannelDimension * tmpDim = info->sourceDimension; - sourceChannel = targetChannel; - targetChannel = tmp; + info->sourceChannel = info->targetChannel; + info->targetChannel = tmp; - sourceComp = targetComp; - targetComp = tmpCmp; + info->sourceComponent = info->targetComponent; + info->targetComponent = tmpCmp; + + info->sourceDimension = info->targetDimension; + info->targetDimension = tmpDim; mcx_log(LOG_DEBUG, "Connection: Inverted connection (%s, %s) -- (%s, %s)", - targetComp->GetName(targetComp), strFromChannel, sourceComp->GetName(sourceComp), strToChannel); + info->targetComponent->GetName(info->targetComponent), strFromChannel, info->sourceComponent->GetName(info->sourceComponent), strToChannel); + } + + { + // check that connection endpoint dimensions match + ChannelDimension * sourceDim = info->sourceDimension; + ChannelDimension * targetDim = info->targetDimension; + + size_t numSourceElems = sourceDim ? ChannelDimensionNumElements(sourceDim) : 1; + size_t numTargetElems = targetDim ? ChannelDimensionNumElements(targetDim) : 1; + + if (numSourceElems != numTargetElems) { + mcx_log(LOG_ERROR, "Connection: Lengths of vectors do not match"); + retVal = RETURN_ERROR; + goto cleanup; + } } // extrapolation if (connInput->interExtrapolationType.defined) { - interExtrapolationType = connInput->interExtrapolationType.value; + info->interExtrapolationType = connInput->interExtrapolationType.value; } - if (INTEREXTRAPOLATION_POLYNOMIAL == interExtrapolationType) { + if (INTEREXTRAPOLATION_POLYNOMIAL == info->interExtrapolationType) { // read the parameters of poly inter-/extrapolation - InterExtrapolationParams * params = interExtrapolationParams; + InterExtrapolationParams * params = &info->interExtrapolationParams; InterExtrapolationInput * paramsInput = connInput->interExtrapolation; params->extrapolationInterval = paramsInput->extrapolationType; @@ -236,102 +319,62 @@ static ConnectionInfo * ConnectionInfoFactoryCreateConnectionInfo(ObjectContaine // decouple if (connInput->decoupleType.defined) { - decoupleType = connInput->decoupleType.value; + info->decoupleType = connInput->decoupleType.value; // decouple priority - if (DECOUPLE_IFNEEDED == decoupleType) { + if (DECOUPLE_IFNEEDED == info->decoupleType) { DecoupleIfNeededInput * decoupleInput = (DecoupleIfNeededInput*)connInput->decoupleSettings; if (decoupleInput->priority.defined) { - decouplePriority = decoupleInput->priority.value; + info->decouplePriority = decoupleInput->priority.value; } - if (decouplePriority < 0) { + if (info->decouplePriority < 0) { retVal = input_element_error((InputElement*)decoupleInput, "Invalid decouple priority"); goto cleanup; } } } - info->Set( - info, - sourceComp, - targetComp, - sourceChannel, - targetChannel, - isDecoupled, - isInterExtrapolating, - interExtrapolationType, - interExtrapolationParams, - decoupleType, - decouplePriority - ); - cleanup: - if (RETURN_ERROR == retVal) { object_destroy(info); } if (NULL != strFromChannel) { mcx_free(strFromChannel); } if (NULL != strToChannel) { mcx_free(strToChannel); } - return info; + return retVal; } -ObjectContainer * ConnectionInfoFactoryCreateConnectionInfos(ObjectContainer * components, - ConnectionInput * connInput, - Component * sourceCompOverride, - Component * targetCompOverride) { - ConnectionInfo * info = NULL; - ObjectContainer * list = NULL; +Vector * ConnectionInfoFactoryCreateConnectionInfos( + ObjectContainer * components, + ConnectionInput * connInput, + Component * sourceCompOverride, + Component * targetCompOverride) +{ + McxStatus retVal = RETURN_OK; + + ConnectionInfo info = { 0 }; + Vector * list = NULL; - list = (ObjectContainer *) object_create(ObjectContainer); + list = (Vector *) object_create(Vector); if (!list) { goto cleanup; } - info = ConnectionInfoFactoryCreateConnectionInfo(components, connInput, - sourceCompOverride, targetCompOverride); - if (!info) { + list->Setup(list, sizeof(ConnectionInfo), ConnectionInfoInit, ConnectionInfoSetFrom, DestroyConnectionInfo); + + retVal = ConnectionInfoFactoryInitConnectionInfo(&info, components, connInput, sourceCompOverride, targetCompOverride); + if (RETURN_ERROR == retVal) { goto cleanup; } - if (connInput->fromType == ENDPOINT_VECTOR || connInput->toType == ENDPOINT_VECTOR) { - /* vector of connections */ - int fromStartIndex = connInput->fromType == ENDPOINT_VECTOR ? connInput->from.vectorEndpoint->startIndex : 0; - int fromEndIndex = connInput->fromType == ENDPOINT_VECTOR ? connInput->from.vectorEndpoint->endIndex : 0; - - int toStartIndex = connInput->toType == ENDPOINT_VECTOR ? connInput->to.vectorEndpoint->startIndex : 0; - int toEndIndex = connInput->toType == ENDPOINT_VECTOR ? connInput->to.vectorEndpoint->endIndex : 0; - - int i = 0; - int fromStart = info->GetSourceChannelID(info); - int toStart = info->GetTargetChannelID(info); - - if (fromEndIndex - fromStartIndex != toEndIndex - toStartIndex) { - /* the lenghts of both sides do not match */ - mcx_log(LOG_ERROR, "Connection: Lengths of vectors do not match"); - goto cleanup; - } - - for (i = 0; fromStartIndex + i <= fromEndIndex; i++) { - ConnectionInfo * copy = info->Copy(info, fromStart + i, toStart + i); - if (!copy) { - goto cleanup; - } - list->PushBack(list, (Object *) copy); - } - - object_destroy(info); - } else { - /* info is the only connection: leave as is */ - list->PushBack(list, (Object *) info); - } + /* info is the only connection: leave as is */ + list->PushBack(list, &info); return list; cleanup: if (list) { - list->DestroyObjects(list); object_destroy(list); } - if (info) { object_destroy(info); } + return NULL; } diff --git a/src/core/connections/ConnectionInfoFactory.h b/src/core/connections/ConnectionInfoFactory.h index 2c3e22b..b7e0b63 100644 --- a/src/core/connections/ConnectionInfoFactory.h +++ b/src/core/connections/ConnectionInfoFactory.h @@ -14,15 +14,16 @@ #include "objects/ObjectContainer.h" #include "reader/model/connections/ConnectionInput.h" #include "core/Component_interface.h" +#include "objects/Vector.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -ObjectContainer * ConnectionInfoFactoryCreateConnectionInfos(ObjectContainer * components, - ConnectionInput * connInput, - Component * sourceCompOverride, - Component * targetCompOverride); +Vector * ConnectionInfoFactoryCreateConnectionInfos(ObjectContainer * components, + ConnectionInput * connInput, + Component * sourceCompOverride, + Component * targetCompOverride); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/core/connections/ConnectionInfo_impl.h b/src/core/connections/ConnectionInfo_impl.h index e2a35c9..455b13a 100644 --- a/src/core/connections/ConnectionInfo_impl.h +++ b/src/core/connections/ConnectionInfo_impl.h @@ -17,6 +17,9 @@ /* for ChannelType */ #include "core/channels/ChannelValue.h" +/* for ChannelDimension */ +#include "core/channels/ChannelDimension.h" + /* for Component */ #include "core/Component.h" @@ -38,6 +41,9 @@ typedef struct ConnectionInfoData { int sourceChannel; int targetChannel; + ChannelDimension * sourceDimension; + ChannelDimension * targetDimension; + // Decouple Info: If this connection is decoupled because of an algebraic loop // in the model (this means that the value of the source for the target is // behind one timestep) diff --git a/src/core/connections/Connection_impl.h b/src/core/connections/Connection_impl.h deleted file mode 100644 index 9facd50..0000000 --- a/src/core/connections/Connection_impl.h +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2020 AVL List GmbH and others - * - * This program and the accompanying materials are made available under the - * terms of the Apache Software License 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -#ifndef MCX_CORE_CONNECTIONS_CONNECTION_IMPL_H -#define MCX_CORE_CONNECTIONS_CONNECTION_IMPL_H - -// for ExtrapolType -#include "core/connections/filters/Filter.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -// ---------------------------------------------------------------------- -// Connection - -// provides information about the connection between -// the input channel it is stored in and the output channel -// that the input channel is connected to - -extern const struct ObjectClass _ConnectionData; - -typedef struct ConnectionData { - Object _; // base class - - // ---------------------------------------------------------------------- - // Structural Information - - // source - struct ChannelOut * out; - - // target - struct ChannelIn * in; - - - // ---------------------------------------------------------------------- - // Value on channel - - const void * value; - int useInitialValue; - - ChannelValue store; - - int isActiveDependency; - - // Meta Data - ConnectionInfo * info; - - // Current state of the connection in state machine - ConnectionState state; - - // Temporary save functions during initialization mode - fConnectionUpdateFromInput NormalUpdateFrom; - fConnectionUpdateToOutput NormalUpdateTo; - const void * normalValue; -} ConnectionData; - -#ifdef __cplusplus -} /* closing brace for extern "C" */ -#endif /* __cplusplus */ - -#endif /* MCX_CORE_CONNECTIONS_CONNECTION_IMPL_H */ \ No newline at end of file diff --git a/src/core/connections/FilteredConnection.c b/src/core/connections/FilteredConnection.c index 57cd8a3..dfa516a 100644 --- a/src/core/connections/FilteredConnection.c +++ b/src/core/connections/FilteredConnection.c @@ -9,56 +9,75 @@ ********************************************************************************/ #include "core/connections/FilteredConnection.h" -#include "core/connections/FilteredConnection_impl.h" #include "core/connections/Connection.h" -#include "core/connections/Connection_impl.h" #include "core/connections/ConnectionInfo.h" #include "core/channels/Channel.h" +#include "core/channels/ChannelInfo.h" #include "core/connections/filters/DiscreteFilter.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -static FilteredConnectionData * FilteredConnectionDataCreate(FilteredConnectionData * data) { - data->filter = NULL; +static McxStatus FilteredConnectionDataInit(FilteredConnectionData * data) { + data->filters = NULL; + data->_filter = NULL; + data->numFilters = 0; - ChannelValueInit(&data->store, CHANNEL_UNKNOWN); + ChannelValueInit(&data->updateBuffer, ChannelTypeClone(&ChannelTypeUnknown)); + ChannelValueInit(&data->store, ChannelTypeClone(&ChannelTypeUnknown)); - return data; + return RETURN_OK; } static void FilteredConnectionDataDestructor(FilteredConnectionData * data) { ChannelValueDestructor(&data->store); - object_destroy(data->filter); -} - -OBJECT_CLASS(FilteredConnectionData, Object); + ChannelValueDestructor(&data->updateBuffer); + if (data->filters) { + size_t i = 0; + for (i = 0; i < data->numFilters; i++) { + object_destroy(data->filters[i]); + } + if (data->numFilters != 1) { + mcx_free(data->filters); + } + } +} static McxStatus FilteredConnectionSetup(Connection * connection, ChannelOut * out, ChannelIn * in, ConnectionInfo * info) { FilteredConnection * filteredConnection = (FilteredConnection *) connection; - ChannelInfo * sourceInfo = ((Channel *)out)->GetInfo((Channel *) out); - ChannelInfo * targetInfo = ((Channel *)in)->GetInfo((Channel *) in); + ChannelInfo * sourceInfo = &((Channel *)out)->info; + ChannelInfo * targetInfo = &((Channel *)in)->info; + + ChannelType * storeType = NULL; McxStatus retVal = RETURN_OK; // Decoupling - if (DECOUPLE_ALWAYS == info->GetDecoupleType(info)) { - info->SetDecoupled(info); + if (DECOUPLE_ALWAYS == info->decoupleType) { + ConnectionInfoSetDecoupled(info); } // filter will be added after model is connected - filteredConnection->data->filter = NULL; + filteredConnection->data.filters = NULL; + filteredConnection->data.numFilters = 0; + + storeType = ChannelTypeFromDimension(sourceInfo->type, info->sourceDimension); + if (!storeType) { + return RETURN_ERROR; + } // value store - ChannelValueInit(&filteredConnection->data->store, sourceInfo->type); + ChannelValueInit(&filteredConnection->data.store, storeType); // steals ownership of storeType -> no clone needed // value reference - connection->data->value = ChannelValueReference(&filteredConnection->data->store); + connection->value_ = ChannelValueDataPointer(&filteredConnection->data.store); + // initialize the buffer for channel function calls + ChannelValueInit(&filteredConnection->data.updateBuffer, ChannelTypeClone(storeType)); // Connection::Setup() // this has to be done last as it connects the channels @@ -72,20 +91,23 @@ static McxStatus FilteredConnectionSetup(Connection * connection, ChannelOut * o static McxStatus FilteredConnectionEnterCommunicationMode(Connection * connection, double time) { FilteredConnection * filteredConnection = (FilteredConnection *) connection; - ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection); McxStatus retVal = RETURN_OK; + size_t i = 0; - if (filter) { - if (filter->EnterCommunicationMode) { - retVal = filter->EnterCommunicationMode(filter, time); - if (RETURN_OK != retVal) { - return RETURN_ERROR; + for (i = 0; i < filteredConnection->data.numFilters; i++) { + ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection, i); + if (filter) { + if (filter->EnterCommunicationMode) { + retVal = filter->EnterCommunicationMode(filter, time); + if (RETURN_OK != retVal) { + return RETURN_ERROR; + } } } } - connection->data->state = InCommunicationMode; + connection->state_ = InCommunicationMode; return RETURN_OK; } @@ -93,84 +115,153 @@ static McxStatus FilteredConnectionEnterCouplingStepMode(Connection * connection , double communicationTimeStepSize, double sourceTimeStepSize, double targetTimeStepSize) { FilteredConnection * filteredConnection = (FilteredConnection *) connection; - ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection); McxStatus retVal = RETURN_OK; + size_t i = 0; - if (filter) { - if (filter->EnterCouplingStepMode) { - retVal = filter->EnterCouplingStepMode(filter, communicationTimeStepSize, sourceTimeStepSize, targetTimeStepSize); - if (RETURN_OK != retVal) { - return RETURN_ERROR; + for (i = 0; i < filteredConnection->data.numFilters; i++) { + ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection, i); + if (filter) { + if (filter->EnterCouplingStepMode) { + retVal = filter->EnterCouplingStepMode(filter, communicationTimeStepSize, sourceTimeStepSize, targetTimeStepSize); + if (RETURN_OK != retVal) { + return RETURN_ERROR; + } } } } - connection->data->state = InCouplingStepMode; + connection->state_ = InCouplingStepMode; return RETURN_OK; } -static ChannelFilter * FilteredConnectionGetFilter(FilteredConnection * connection) { - return connection->data->filter; +static ChannelFilter * FilteredConnectionGetFilter(FilteredConnection * connection, size_t idx) { + if (connection->data.filters && idx < connection->data.numFilters) { + return connection->data.filters[idx]; + } + return NULL; +} + +static size_t FilteredConnectionGetNumFilters(FilteredConnection *connection) { + return connection->data.numFilters; } -static void FilteredConnectionSetResult(FilteredConnection * connection, const void * value) { - ChannelValueSetFromReference(&connection->data->store, value); +static McxStatus FilteredConnectionSetResult(FilteredConnection * connection, const void * value) { + return ChannelValueSetFromReference(&connection->data.store, value); +} + +static size_t GetSliceShift(Connection * connection) { + Channel * channel = (Channel *) connection->GetSource(connection); + ChannelInfo * channelInfo = &channel->info; + ChannelDimension * sourceDimension = channelInfo->dimension; + + ConnectionInfo * connInfo = connection->GetInfo(connection); + ChannelDimension * sliceDimension = connInfo->sourceDimension; + + // only 1D at the moment + return sliceDimension->startIdxs[0] - sourceDimension->startIdxs[0]; } static void FilteredConnectionUpdateFromInput(Connection * connection, TimeInterval * time) { FilteredConnection * filteredConnection = (FilteredConnection *) connection; - ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection); Channel * channel = (Channel *) connection->GetSource(connection); - ChannelInfo * info = channel->GetInfo(channel); + ChannelInfo * info = &channel->info; #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] FCONN (%s) UpdateFromInput", time->startTime, info->GetName(info)); + MCX_DEBUG_LOG("[%f] FCONN (%s) UpdateFromInput", time->startTime, ChannelInfoGetName(info)); } #endif - if (filter && time->startTime >= 0) { - ChannelValueData value = * (ChannelValueData *) channel->GetValueReference(channel); - filter->SetValue(filter, time->startTime, value); + if (ChannelTypeIsScalar(info->type)) { + ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection, 0); + if (filter && time->startTime >= 0) { + ChannelValueData value = *(ChannelValueData *) channel->GetValueReference(channel); + filter->SetValue(filter, time->startTime, value); + } + } else { + size_t i = 0; + size_t shift = GetSliceShift(connection); + ChannelValueData element; + ChannelValueDataInit(&element, ChannelTypeBaseType(info->type)); + + for (i = 0; i < FilteredConnectionGetNumFilters(filteredConnection); i++) { + ChannelFilter * filter = filteredConnection->GetWriteFilter(filteredConnection, i); + + if (filter && time->startTime >= 0) { + ChannelValueData value = *(ChannelValueData *) channel->GetValueReference(channel); + mcx_array_get_elem(&value.a, i + shift, &element); + filter->SetValue(filter, time->startTime, element); + } + } } } -static void FilteredConnectionUpdateToOutput(Connection * connection, TimeInterval * time) { +static McxStatus FilteredConnectionUpdateToOutput(Connection * connection, TimeInterval * time) { FilteredConnection * filteredConnection = (FilteredConnection *) connection; ChannelFilter * filter = NULL; Channel * channel = (Channel *) connection->GetSource(connection); + ChannelInfo * info = &channel->info; ChannelOut * out = (ChannelOut *) channel; - ChannelInfo * info = channel->GetInfo(channel); - #ifdef MCX_DEBUG if (time->startTime < MCX_DEBUG_LOG_TIME) { - ChannelInfo * info = channel->GetInfo(channel); - MCX_DEBUG_LOG("[%f] FCONN (%s) UpdateToOutput", time->startTime, info->GetName(info)); + MCX_DEBUG_LOG("[%f] FCONN (%s) UpdateToOutput", time->startTime, ChannelInfoGetName(info)); } #endif if (out->GetFunction(out)) { proc * p = (proc *) out->GetFunction(out); - double value = 0.0; - value = p->fn(time, p->env); - filteredConnection->SetResult(filteredConnection, &value); + // TODO: Update functions to only update the slices ? + if (RETURN_ERROR == p->fn(time, p->env, &filteredConnection->data.updateBuffer)) { + mcx_log(LOG_ERROR, "FilteredConnection: Function failed"); + return RETURN_ERROR; + } + + if (RETURN_OK != filteredConnection->SetResult(filteredConnection, ChannelValueDataPointer(&filteredConnection->data.updateBuffer))) { + mcx_log(LOG_ERROR, "FilteredConnection: SetResult failed"); + return RETURN_ERROR; + } } else { // only filter if time is not negative (negative time means filter disabled) - if (filteredConnection->GetReadFilter(filteredConnection) && time->startTime >= 0) { - ChannelValueData value; - - filter = filteredConnection->GetReadFilter(filteredConnection); - value = filter->GetValue(filter, time->startTime); - - filteredConnection->SetResult(filteredConnection, &value); + if (filteredConnection->GetReadFilter(filteredConnection, 0) && time->startTime >= 0) { + ChannelValueData value = { 0 }; + + if (ChannelTypeIsScalar(info->type)) { + filter = filteredConnection->GetReadFilter(filteredConnection, 0); + value = filter->GetValue(filter, time->startTime); + + if (RETURN_OK != filteredConnection->SetResult(filteredConnection, &value)) { + mcx_log(LOG_ERROR, "FilteredConnection: SetResult failed"); + return RETURN_ERROR; + } + } else { + size_t i = 0; + size_t numFilters = FilteredConnectionGetNumFilters(filteredConnection); + ChannelType * type = info->type; + + mcx_array * elements = (mcx_array *) ChannelValueDataPointer(&filteredConnection->data.updateBuffer); + char * dest = (char *) elements->data; + for (i = 0; i < numFilters; i++) { + filter = filteredConnection->GetReadFilter(filteredConnection, i); + value = filter->GetValue(filter, time->startTime); + + ChannelValueDataSetToReference(&value, ChannelTypeBaseType(type), (void *) dest); + dest += ChannelValueTypeSize(ChannelTypeBaseType(type)); + } + + if (RETURN_OK != filteredConnection->SetResult(filteredConnection, elements)) { + mcx_log(LOG_ERROR, "FilteredConnection: SetResult failed"); + return RETURN_ERROR; + } + } } } + + return RETURN_OK; } static McxStatus AddFilter(Connection * connection) { @@ -179,25 +270,87 @@ static McxStatus AddFilter(Connection * connection) { McxStatus retVal = RETURN_OK; - if (filteredConnection->data->filter) { + if (filteredConnection->data.filters) { mcx_log(LOG_DEBUG, "Connection: Not inserting filter"); } else { - filteredConnection->data->filter = FilterFactory(connection); - if (NULL == filteredConnection->data->filter) { - mcx_log(LOG_DEBUG, "Connection: No Filter created"); - retVal = RETURN_ERROR; + ConnectionInfo * info = connection->GetInfo(connection); + const char * connString = ConnectionInfoConnectionString(info); + ChannelDimension * dimension = info->sourceDimension; + + if (dimension) { // array + size_t i = 0; + + if (dimension->num > 1) { + mcx_log(LOG_ERROR, "Setting filters for multi-dimensional connections is not supported"); + retVal = RETURN_ERROR; + goto cleanup; + } + + filteredConnection->data.numFilters = dimension->endIdxs[0] - dimension->startIdxs[0] + 1; + filteredConnection->data.filters = (ChannelFilter **) mcx_calloc(filteredConnection->data.numFilters, sizeof(ChannelFilter*)); + if (!filteredConnection->data.filters) { + mcx_log(LOG_ERROR, "Creating array filters failed: no memory"); + retVal = RETURN_ERROR; + goto cleanup; + } + + for (i = 0; i < filteredConnection->data.numFilters; i++) { + filteredConnection->data.filters[i] = FilterFactory(&connection->state_, + info->interExtrapolationType, + &info->interExtrapolationParams, + ChannelTypeBaseType(ConnectionInfoGetType(info)), + info->isInterExtrapolating, + ConnectionInfoIsDecoupled(info), + info->sourceComponent, + info->targetComponent, + connString); + if (NULL == filteredConnection->data.filters[i]) { + mcx_log(LOG_DEBUG, "Connection: Array filter creation failed for index %zu", i); + retVal = RETURN_ERROR; + goto cleanup; + } + } + } else { + filteredConnection->data.numFilters = 1; + filteredConnection->data._filter = FilterFactory(&connection->state_, + info->interExtrapolationType, + &info->interExtrapolationParams, + ConnectionInfoGetType(info), + info->isInterExtrapolating, + ConnectionInfoIsDecoupled(info), + info->sourceComponent, + info->targetComponent, + connString); + if (NULL == filteredConnection->data._filter) { + mcx_log(LOG_DEBUG, "Connection: No Filter created"); + retVal = RETURN_ERROR; + goto cleanup; + } + filteredConnection->data.filters = &filteredConnection->data._filter; + } + +cleanup: + mcx_free(connString); + if (retVal != RETURN_OK) { + return retVal; } } - return retVal; + return RETURN_OK; +} + +static ChannelType * FilteredConnectionGetValueType(Connection * connection) { + FilteredConnection * filteredConnection = (FilteredConnection *) connection; + return filteredConnection->data.store.type; } static void FilteredConnectionDestructor(FilteredConnection * filteredConnection) { - object_destroy(filteredConnection->data); + FilteredConnectionDataDestructor(&filteredConnection->data); } static FilteredConnection * FilteredConnectionCreate(FilteredConnection * filteredConnection) { Connection * connection = (Connection *) filteredConnection; + McxStatus retVal = RETURN_OK; connection->Setup = FilteredConnectionSetup; connection->UpdateFromInput = FilteredConnectionUpdateFromInput; @@ -207,13 +360,18 @@ static FilteredConnection * FilteredConnectionCreate(FilteredConnection * filter connection->EnterCouplingStepMode = FilteredConnectionEnterCouplingStepMode; connection->AddFilter = AddFilter; + connection->GetValueType = FilteredConnectionGetValueType; filteredConnection->GetReadFilter = FilteredConnectionGetFilter; filteredConnection->GetWriteFilter = FilteredConnectionGetFilter; filteredConnection->SetResult = FilteredConnectionSetResult; - filteredConnection->data = (FilteredConnectionData *) object_create(FilteredConnectionData); + retVal = FilteredConnectionDataInit(&filteredConnection->data); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "FilteredConnectionCreate: FilteredConnectionDataInit failed"); + return NULL; + } return filteredConnection; } diff --git a/src/core/connections/FilteredConnection.h b/src/core/connections/FilteredConnection.h index ef2f335..8a6f546 100644 --- a/src/core/connections/FilteredConnection.h +++ b/src/core/connections/FilteredConnection.h @@ -13,16 +13,32 @@ #include "core/connections/Connection.h" #include "core/Conversion.h" +#include "core/channels/ChannelValue.h" +#include "core/connections/filters/Filter.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ +typedef struct FilteredConnectionData { + + // storage of the filtered value provided by the output channel + ChannelValue store; + + // storage for temporary results during out channel updates + ChannelValue updateBuffer; + + ChannelFilter ** filters; + ChannelFilter * _filter; + size_t numFilters; + +} FilteredConnectionData; + typedef struct FilteredConnection FilteredConnection; -typedef struct ChannelFilter * (* fConnectionGetFilter)(FilteredConnection * connection); +typedef struct ChannelFilter * (* fConnectionGetFilter)(FilteredConnection * connection, size_t idx); -typedef void (* fFilteredConnectionSetResult)(FilteredConnection * connection, const void * value); +typedef McxStatus (* fFilteredConnectionSetResult)(FilteredConnection * connection, const void * value); extern const struct ObjectClass _FilteredConnection; @@ -34,7 +50,7 @@ struct FilteredConnection { fFilteredConnectionSetResult SetResult; - struct FilteredConnectionData * data; + FilteredConnectionData data; } ; #ifdef __cplusplus diff --git a/src/core/connections/FilteredConnection_impl.h b/src/core/connections/FilteredConnection_impl.h deleted file mode 100644 index 09ab299..0000000 --- a/src/core/connections/FilteredConnection_impl.h +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2020 AVL List GmbH and others - * - * This program and the accompanying materials are made available under the - * terms of the Apache Software License 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -#ifndef MCX_CORE_CONNECTIONS_FILTEREDCONNECTIONDATA_H -#define MCX_CORE_CONNECTIONS_FILTEREDCONNECTIONDATA_H - -#include "core/Conversion.h" - -// for ExtrapolType -#include "core/connections/filters/Filter.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -extern const struct ObjectClass _FilteredConnectionData; - -typedef struct FilteredConnectionData { - Object _; /* super class */ - - // storage of the filtered value provided by the output channel - ChannelValue store; - - ChannelFilter * filter; - -} FilteredConnectionData; - -#ifdef __cplusplus -} /* closing brace for extern "C" */ -#endif /* __cplusplus */ - -#endif /* MCX_CORE_CONNECTIONS_FILTEREDCONNECTIONDATA_H */ \ No newline at end of file diff --git a/src/core/connections/filters/DiscreteFilter.c b/src/core/connections/filters/DiscreteFilter.c index ad80218..2ad8241 100644 --- a/src/core/connections/filters/DiscreteFilter.c +++ b/src/core/connections/filters/DiscreteFilter.c @@ -18,7 +18,9 @@ static McxStatus DiscreteFilterSetValue(ChannelFilter * filter, double time, Cha DiscreteFilter * discreteFilter = (DiscreteFilter *) filter; if (InCommunicationMode != * filter->state) { - ChannelValueSetFromReference(&discreteFilter->lastCouplingStepValue, &value); + if (RETURN_OK != ChannelValueSetFromReference(&discreteFilter->lastCouplingStepValue, &value)) { + return RETURN_ERROR; + } } return RETURN_OK; @@ -27,7 +29,7 @@ static McxStatus DiscreteFilterSetValue(ChannelFilter * filter, double time, Cha static ChannelValueData DiscreteFilterGetValue(ChannelFilter * filter, double time) { DiscreteFilter * discreteFilter = (DiscreteFilter *) filter; - return * (ChannelValueData *) ChannelValueReference(&discreteFilter->lastSynchronizationStepValue); + return * (ChannelValueData *) ChannelValueDataPointer(&discreteFilter->lastSynchronizationStepValue); } static McxStatus DiscreteFilterEnterCouplingStepMode(ChannelFilter * filter @@ -44,9 +46,9 @@ static McxStatus DiscreteFilterEnterCommunicationMode(ChannelFilter * filter, do return RETURN_OK; } -static McxStatus DiscreteFilterSetup(DiscreteFilter * filter, ChannelType type) { - ChannelValueInit(&filter->lastSynchronizationStepValue, type); - ChannelValueInit(&filter->lastCouplingStepValue, type); +static McxStatus DiscreteFilterSetup(DiscreteFilter * filter, ChannelType * type) { + ChannelValueInit(&filter->lastSynchronizationStepValue, ChannelTypeClone(type)); + ChannelValueInit(&filter->lastCouplingStepValue, ChannelTypeClone(type)); return RETURN_OK; } @@ -67,8 +69,8 @@ static DiscreteFilter * DiscreteFilterCreate(DiscreteFilter * discreteFilter) { discreteFilter->Setup = DiscreteFilterSetup; - ChannelValueInit(&discreteFilter->lastSynchronizationStepValue, CHANNEL_UNKNOWN); - ChannelValueInit(&discreteFilter->lastCouplingStepValue, CHANNEL_UNKNOWN); + ChannelValueInit(&discreteFilter->lastSynchronizationStepValue, ChannelTypeClone(&ChannelTypeUnknown)); + ChannelValueInit(&discreteFilter->lastCouplingStepValue, ChannelTypeClone(&ChannelTypeUnknown)); return discreteFilter; } diff --git a/src/core/connections/filters/DiscreteFilter.h b/src/core/connections/filters/DiscreteFilter.h index e98af60..cca3e6e 100644 --- a/src/core/connections/filters/DiscreteFilter.h +++ b/src/core/connections/filters/DiscreteFilter.h @@ -19,7 +19,7 @@ extern "C" { typedef struct DiscreteFilter DiscreteFilter; -typedef McxStatus (* fDiscreteFilterSetup)(DiscreteFilter * filter, ChannelType type); +typedef McxStatus (* fDiscreteFilterSetup)(DiscreteFilter * filter, ChannelType * type); extern const struct ObjectClass _DiscreteFilter; diff --git a/src/core/connections/filters/IntExtFilter.c b/src/core/connections/filters/IntExtFilter.c index 00ee864..37d61d9 100644 --- a/src/core/connections/filters/IntExtFilter.c +++ b/src/core/connections/filters/IntExtFilter.c @@ -104,8 +104,8 @@ static McxStatus IntExtFilterEnterCommunicationMode(ChannelFilter * filter, doub return RETURN_OK; } -static McxStatus IntExtFilterSetup(IntExtFilter * intExtFilter, int degreeExtrapolation, int degreeInterpolation) { - if (RETURN_ERROR == intExtFilter->filterInt->Setup(intExtFilter->filterInt, degreeInterpolation)) { +static McxStatus IntExtFilterSetup(IntExtFilter * intExtFilter, int degreeExtrapolation, int degreeInterpolation, size_t buffSize) { + if (RETURN_ERROR == intExtFilter->filterInt->Setup(intExtFilter->filterInt, degreeInterpolation, buffSize)) { mcx_log(LOG_ERROR, "Connection: IntExtFilter: Setup of interpolation filter failed"); return RETURN_ERROR; } diff --git a/src/core/connections/filters/IntExtFilter.h b/src/core/connections/filters/IntExtFilter.h index 571d956..3b9e758 100644 --- a/src/core/connections/filters/IntExtFilter.h +++ b/src/core/connections/filters/IntExtFilter.h @@ -22,7 +22,7 @@ extern "C" { typedef struct IntExtFilter IntExtFilter; -typedef McxStatus (* fIntExtFilterSetup)(IntExtFilter * intExtFilter, int degreeExtrapolation, int degreeInterpolation); +typedef McxStatus (* fIntExtFilterSetup)(IntExtFilter * intExtFilter, int degreeExtrapolation, int degreeInterpolation, size_t buffSize); extern const struct ObjectClass _IntExtFilter; diff --git a/src/core/connections/filters/IntFilter.c b/src/core/connections/filters/IntFilter.c index 1b399a3..08de7c2 100644 --- a/src/core/connections/filters/IntFilter.c +++ b/src/core/connections/filters/IntFilter.c @@ -165,7 +165,7 @@ static McxStatus IntFilterEnterCommunicationMode(ChannelFilter * filter, double return RETURN_OK; } -static McxStatus IntFilterSetup(IntFilter * intFilter, int degree){ +static McxStatus IntFilterSetup(IntFilter * intFilter, int degree, size_t buffSize){ ChannelFilter * filter = (ChannelFilter *) intFilter; mcx_table_interp_type intType = MCX_TABLE_INTERP_NOT_SET; @@ -173,6 +173,28 @@ static McxStatus IntFilterSetup(IntFilter * intFilter, int degree){ int ret = 0; + if (buffSize == 0) { + mcx_log(LOG_ERROR, "IntFilter: Buffer size %zu not supported", buffSize); + return RETURN_ERROR; + } + + intFilter->dataLen = buffSize; + + intFilter->read_x_data = (double*)mcx_malloc(intFilter->dataLen * sizeof(double)); + intFilter->read_y_data = (double*)mcx_malloc(intFilter->dataLen * sizeof(double)); + + intFilter->write_x_data = (double*)mcx_malloc(intFilter->dataLen * sizeof(double)); + intFilter->write_y_data = (double*)mcx_malloc(intFilter->dataLen * sizeof(double)); + + if (!intFilter->read_x_data || + !intFilter->read_y_data || + !intFilter->write_x_data || + !intFilter->write_y_data) + { + mcx_log(LOG_ERROR, "IntFilter: Buffer allocation failed"); + return RETURN_ERROR; + } + intFilter->couplingPolyDegree = degree; switch (degree) { @@ -201,11 +223,11 @@ static McxStatus IntFilterSetup(IntFilter * intFilter, int degree){ static void IntFilterDestructor(IntFilter * filter){ mcx_interp_free_table(filter->T); - mcx_free(filter->read_x_data); - mcx_free(filter->read_y_data); + if (filter->read_x_data) { mcx_free(filter->read_x_data); } + if (filter->read_y_data) { mcx_free(filter->read_y_data); } - mcx_free(filter->write_x_data); - mcx_free(filter->write_y_data); + if (filter->write_x_data) { mcx_free(filter->write_x_data); } + if (filter->write_y_data) { mcx_free(filter->write_y_data); } } static IntFilter * IntFilterCreate(IntFilter * intFilter){ @@ -226,14 +248,13 @@ static IntFilter * IntFilterCreate(IntFilter * intFilter){ intFilter->T = mcx_interp_new_table(); - /* this is just a generous heuristic value */ - intFilter->dataLen = 1000; + intFilter->dataLen = 0; - intFilter->read_x_data = (double *) mcx_malloc(intFilter->dataLen * sizeof(double)); - intFilter->read_y_data = (double *) mcx_malloc(intFilter->dataLen * sizeof(double)); + intFilter->read_x_data = NULL; + intFilter->read_y_data = NULL; - intFilter->write_x_data = (double *) mcx_malloc(intFilter->dataLen * sizeof(double)); - intFilter->write_y_data = (double *) mcx_malloc(intFilter->dataLen * sizeof(double)); + intFilter->write_x_data = NULL; + intFilter->write_y_data = NULL; return intFilter; } diff --git a/src/core/connections/filters/IntFilter.h b/src/core/connections/filters/IntFilter.h index 74d5052..d847a5c 100644 --- a/src/core/connections/filters/IntFilter.h +++ b/src/core/connections/filters/IntFilter.h @@ -22,7 +22,7 @@ extern "C" { typedef struct IntFilter IntFilter; -typedef McxStatus (* fIntFilterSetup)(IntFilter * filter, int degree); +typedef McxStatus (* fIntFilterSetup)(IntFilter * filter, int degree, size_t buffSize); extern const struct ObjectClass _IntFilter; diff --git a/src/core/connections/filters/MemoryFilter.c b/src/core/connections/filters/MemoryFilter.c new file mode 100644 index 0000000..ac14fa0 --- /dev/null +++ b/src/core/connections/filters/MemoryFilter.c @@ -0,0 +1,331 @@ +/******************************************************************************** + * Copyright (c) 2022 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include "core/connections/filters/MemoryFilter.h" + +#include "util/compare.h" + +#include + +#ifndef SIZE_MAX +#define SIZE_MAX ((size_t) (-1)) +#endif // !SIZE_MAX + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +static McxStatus MemoryFilterSetValue(ChannelFilter * filter, double time, ChannelValueData value) { + MemoryFilter * memoryFilter = (MemoryFilter *) filter; + + if (InCommunicationMode != * filter->state) { + if (memoryFilter->numEntriesWrite >= memoryFilter->historySize) { + mcx_log(LOG_ERROR, "MemoryFilter: History buffer too small"); + return RETURN_ERROR; + } + + ChannelValueSetFromReference(memoryFilter->valueHistoryWrite + memoryFilter->numEntriesWrite, &value); + memoryFilter->timeHistoryWrite[memoryFilter->numEntriesWrite] = time; + memoryFilter->numEntriesWrite++; + +#ifdef MCX_DEBUG + if (time < MCX_DEBUG_LOG_TIME) { + if (ChannelTypeEq(memoryFilter->valueHistoryWrite[0].type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("MemoryFilter: F SET (%x) (%f, %f)", filter, time, value.d); + } else { + MCX_DEBUG_LOG("MemoryFilter: F SET (%x) (%f, -)", filter, time); + } + MCX_DEBUG_LOG("MemoryFilter: NumEntriesWrite: %zu", memoryFilter->numEntriesWrite); + } +#endif // MCX_DEBUG + } + + return RETURN_OK; +} + +static ChannelValueData MemoryFilterGetValueReverse(ChannelFilter * filter, double time) { + MemoryFilter * memoryFilter = (MemoryFilter *) filter; + size_t i = 0; + size_t smallerIdx = SIZE_MAX; + size_t biggerIdx = SIZE_MAX; + + for (i = memoryFilter->numEntriesRead - 1 ; i >= 0; --i) { + if (double_eq(memoryFilter->timeHistoryRead[i], time)) { +#ifdef MCX_DEBUG + if (time < MCX_DEBUG_LOG_TIME) { + if (ChannelTypeEq(memoryFilter->valueHistoryRead[i].type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("MemoryFilter: F GET (%x) (%f, %f)", filter, time, memoryFilter->valueHistoryRead[i].value.d); + } else { + MCX_DEBUG_LOG("MemoryFilter: F GET (%x) (%f, -)", filter, time); + } + } +#endif // MCX_DEBUG + + return memoryFilter->valueHistoryRead[i].value; + } + + // find out closest stored time points + if (time < memoryFilter->timeHistoryRead[i]) { + biggerIdx = i; + } else if (smallerIdx == SIZE_MAX) { + smallerIdx = i; + } else { + break; + } + } + + if (smallerIdx == SIZE_MAX) { + i = biggerIdx; + } else if (biggerIdx == SIZE_MAX) { + i = smallerIdx; + } else if ((time - memoryFilter->timeHistoryRead[smallerIdx]) < (memoryFilter->timeHistoryRead[biggerIdx] - time)) { + i = smallerIdx; + } else { + i = biggerIdx; + } + +#ifdef MCX_DEBUG + if (time < MCX_DEBUG_LOG_TIME) { + if (ChannelTypeEq(memoryFilter->valueHistoryRead[i].type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("MemoryFilter: F GET CLOSEST (%x) (%f, %f)", filter, time, memoryFilter->valueHistoryRead[i].value.d); + } else { + MCX_DEBUG_LOG("MemoryFilter: F GET CLOSEST (%x) (%f, -)", filter, time); + } + } +#endif // MCX_DEBUG + + return memoryFilter->valueHistoryRead[i].value; +} + +static ChannelValueData MemoryFilterGetValue(ChannelFilter * filter, double time) { + MemoryFilter * memoryFilter = (MemoryFilter *) filter; + size_t i = 0; + size_t smallerIdx = SIZE_MAX; + size_t biggerIdx = SIZE_MAX; + + for (i = 0; i < memoryFilter->numEntriesRead; ++i) { + if (double_eq(memoryFilter->timeHistoryRead[i], time)) { +#ifdef MCX_DEBUG + if (time < MCX_DEBUG_LOG_TIME) { + if (ChannelTypeEq(memoryFilter->valueHistoryRead[i].type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("MemoryFilter: F GET (%x) (%f, %f)", filter, time, memoryFilter->valueHistoryRead[i].value.d); + } else { + MCX_DEBUG_LOG("MemoryFilter: F GET (%x) (%f, -)", filter, time); + } + } +#endif // MCX_DEBUG + + return memoryFilter->valueHistoryRead[i].value; + } + + // find out closest stored time points + if (time > memoryFilter->timeHistoryRead[i]) { + smallerIdx = i; + } else if (biggerIdx == SIZE_MAX) { + biggerIdx = i; + } else { + break; + } + } + + if (smallerIdx == SIZE_MAX) { + i = biggerIdx; + } else if (biggerIdx == SIZE_MAX) { + i = smallerIdx; + } else if ((time - memoryFilter->timeHistoryRead[smallerIdx]) < (memoryFilter->timeHistoryRead[biggerIdx] - time)) { + i = smallerIdx; + } else { + i = biggerIdx; + } + +#ifdef MCX_DEBUG + if (time < MCX_DEBUG_LOG_TIME) { + if (ChannelTypeEq(memoryFilter->valueHistoryRead[i].type, &ChannelTypeDouble)) { + MCX_DEBUG_LOG("MemoryFilter: F GET CLOSEST (%x) (%f, %f)", filter, time, memoryFilter->valueHistoryRead[i].value.d); + } else { + MCX_DEBUG_LOG("MemoryFilter: F GET CLOSEST (%x) (%f, -)", filter, time); + } + } +#endif // MCX_DEBUG + + return memoryFilter->valueHistoryRead[i].value; +} + +static McxStatus MemoryFilterEnterCouplingStepMode(ChannelFilter * filter, + double communicationTimeStepSize, + double sourceTimeStepSize, + double targetTimeStepSize) { + MemoryFilter * memoryFilter = (MemoryFilter *) filter; + + MCX_DEBUG_LOG("MemoryFilter: Enter coupling mode (%x): NumEntriesRead: %d, NumEntriesWrite: %d", + filter, memoryFilter->numEntriesRead, memoryFilter->numEntriesWrite); + + return RETURN_OK; +} + +static McxStatus MemoryFilterEnterCommunicationMode(ChannelFilter * filter, double _time) { + MemoryFilter* memoryFilter = (MemoryFilter*)filter; + + MCX_DEBUG_LOG("MemoryFilter: Enter synchronization mode (%x): NumEntriesRead: %d, NumEntriesWrite: %d", + filter, memoryFilter->numEntriesRead, memoryFilter->numEntriesWrite); + + if (memoryFilter->numEntriesWrite > 0) { + size_t i = 0; + if (memoryFilter->numEntriesRead > 1) { + ChannelValueSetFromReference(&memoryFilter->valueHistoryRead[0], &memoryFilter->valueHistoryRead[memoryFilter->numEntriesRead - 1].value); + memoryFilter->timeHistoryRead[0] = memoryFilter->timeHistoryRead[memoryFilter->numEntriesRead - 1]; + memoryFilter->numEntriesRead = 1; + } + + for (i = 0; i < memoryFilter->numEntriesWrite; i++) { +#ifdef MCX_DEBUG + if (i + memoryFilter->numEntriesRead >= memoryFilter->historySize) { + mcx_log(LOG_ERROR, "MemoryFilter: Trying to write outside of allocated buffer " + "(HistorySize: %zu, NumEntriesRead: %zu, NumEntriesWrite: %zu", + memoryFilter->historySize, memoryFilter->numEntriesRead, memoryFilter->numEntriesWrite); + return RETURN_ERROR; + } +#endif // MCX_DEBUG + ChannelValueSetFromReference(&memoryFilter->valueHistoryRead[i + memoryFilter->numEntriesRead], &memoryFilter->valueHistoryWrite[i].value); + memoryFilter->timeHistoryRead[i + memoryFilter->numEntriesRead] = memoryFilter->timeHistoryWrite[i]; + } + + memoryFilter->numEntriesRead += memoryFilter->numEntriesWrite; + memoryFilter->numEntriesWrite = 0; + } + + return RETURN_OK; +} + +static McxStatus MemoryFilterSetup(MemoryFilter * filter, ChannelType * type, size_t historySize, int reverseSearch) { + ChannelFilter * channelFilter = (ChannelFilter *)filter; + size_t i = 0; + + channelFilter->GetValue = reverseSearch ? MemoryFilterGetValueReverse : MemoryFilterGetValue; + + filter->historySize = historySize; + filter->numEntriesRead = 0; + filter->numEntriesWrite = 0; + + filter->valueHistoryRead = (ChannelValue *) mcx_malloc(filter->historySize * sizeof(ChannelValue)); + if (!filter->valueHistoryRead) { + mcx_log(LOG_ERROR, "MemoryFilterSetup: No memory for value buffer (read)"); + goto cleanup; + } + + filter->valueHistoryWrite = (ChannelValue*)mcx_malloc(filter->historySize * sizeof(ChannelValue)); + if (!filter->valueHistoryWrite) { + mcx_log(LOG_ERROR, "MemoryFilterSetup: No memory for value buffer (write)"); + goto cleanup; + } + + filter->timeHistoryRead = (double *) mcx_calloc(filter->historySize, sizeof(double)); + if (!filter->timeHistoryRead) { + mcx_log(LOG_ERROR, "MemoryFilterSetup: No memory for time buffer (read)"); + goto cleanup; + } + + filter->timeHistoryWrite = (double*)mcx_calloc(filter->historySize, sizeof(double)); + if (!filter->timeHistoryWrite) { + mcx_log(LOG_ERROR, "MemoryFilterSetup: No memory for time buffer (write)"); + goto cleanup; + } + + for (i = 0; i < filter->historySize; i++) { + ChannelValueInit(filter->valueHistoryRead + i, ChannelTypeClone(type)); + } + + for (i = 0; i < filter->historySize; i++) { + ChannelValueInit(filter->valueHistoryWrite + i, ChannelTypeClone(type)); + } + + return RETURN_OK; + +cleanup: + if (filter->valueHistoryRead) { + mcx_free(filter->valueHistoryRead); + } + + if (filter->valueHistoryWrite) { + mcx_free(filter->valueHistoryWrite); + } + + if (filter->timeHistoryRead) { + mcx_free(filter->timeHistoryRead); + } + + if (filter->timeHistoryWrite) { + mcx_free(filter->timeHistoryWrite); + } + + return RETURN_ERROR; +} + +static void MemoryFilterDestructor(MemoryFilter * filter) { + if (filter->valueHistoryRead) { + size_t i = 0; + + for (i = 0; i < filter->numEntriesRead; i++) { + ChannelValueDestructor(&filter->valueHistoryRead[i]); + } + + mcx_free(filter->valueHistoryRead); + } + + if (filter->timeHistoryRead) { + mcx_free(filter->timeHistoryRead); + } + + if (filter->valueHistoryWrite) { + size_t i = 0; + + for (i = 0; i < filter->numEntriesWrite; i++) { + ChannelValueDestructor(&filter->valueHistoryWrite[i]); + } + + mcx_free(filter->valueHistoryWrite); + } + + if (filter->timeHistoryWrite) { + mcx_free(filter->timeHistoryWrite); + } +} + +static MemoryFilter * MemoryFilterCreate(MemoryFilter * memoryFilter) { + ChannelFilter * filter = (ChannelFilter *) memoryFilter; + + filter->SetValue = MemoryFilterSetValue; + filter->GetValue = NULL; + + filter->EnterCommunicationMode = MemoryFilterEnterCommunicationMode; + filter->EnterCouplingStepMode = MemoryFilterEnterCouplingStepMode; + + memoryFilter->Setup = MemoryFilterSetup; + + memoryFilter->valueHistoryRead = NULL; + memoryFilter->valueHistoryWrite = NULL; + memoryFilter->timeHistoryRead = NULL; + memoryFilter->timeHistoryWrite = NULL; + + memoryFilter->numEntriesRead = 0; + memoryFilter->numEntriesWrite = 0; + + memoryFilter->historySize = 0; + + return memoryFilter; +} + +OBJECT_CLASS(MemoryFilter, ChannelFilter); + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ \ No newline at end of file diff --git a/src/core/connections/filters/MemoryFilter.h b/src/core/connections/filters/MemoryFilter.h new file mode 100644 index 0000000..1561fe6 --- /dev/null +++ b/src/core/connections/filters/MemoryFilter.h @@ -0,0 +1,45 @@ +/******************************************************************************** + * Copyright (c) 2022 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef MCX_CORE_CONNECTIONS_FILTERS_MEMORY_FILTER_H +#define MCX_CORE_CONNECTIONS_FILTERS_MEMORY_FILTER_H + +#include "core/connections/filters/Filter.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +typedef struct MemoryFilter MemoryFilter; + +typedef McxStatus (* fMemoryFilterSetup)(MemoryFilter * filter, ChannelType * type, size_t historySize, int reverseSearch); + +extern const struct ObjectClass _MemoryFilter; + +struct MemoryFilter { + ChannelFilter _; + + fMemoryFilterSetup Setup; + + ChannelValue * valueHistoryRead; + ChannelValue * valueHistoryWrite; + double * timeHistoryRead; + double * timeHistoryWrite; + + size_t numEntriesRead; + size_t numEntriesWrite; + size_t historySize; +} ; + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ + +#endif /* MCX_CORE_CONNECTIONS_FILTERS_MEMORY_FILTER_H */ \ No newline at end of file diff --git a/src/core/parameters/ParameterProxies.c b/src/core/parameters/ParameterProxies.c new file mode 100644 index 0000000..e48e4ae --- /dev/null +++ b/src/core/parameters/ParameterProxies.c @@ -0,0 +1,217 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include "core/parameters/ParameterProxies.h" +#include "util/string.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +static void ScalarParameterProxySetValue(ScalarParameterProxy * proxy, Fmu2Value * value) { + proxy->value_ = value; +} + +static ChannelType * ScalarParameterProxyGetType(ScalarParameterProxy * proxy) { + if (proxy->value_) { + return ChannelValueType(&proxy->value_->val); + } + + return &ChannelTypeUnknown; +} + +static Fmu2Value * ScalarParameterProxyGetValue(ScalarParameterProxy * proxy) { + return proxy->value_; +} + +static void ScalarParameterProxyDestructor(ScalarParameterProxy * proxy) { + // don't destroy value as it is just a weak reference +} + +static ScalarParameterProxy * ScalarParameterProxyCreate(ScalarParameterProxy * proxy) { + proxy->SetValue = ScalarParameterProxySetValue; + proxy->GetType = ScalarParameterProxyGetType; + proxy->GetValue = ScalarParameterProxyGetValue; + + proxy->value_ = NULL; + + return proxy; +} + +OBJECT_CLASS(ScalarParameterProxy, Object); + + + +static McxStatus ArrayParameterProxyAddValue(ArrayParameterProxy * proxy, Fmu2Value * value) { + McxStatus retVal = RETURN_OK; + + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * val = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + + // check that data types match + if (!ChannelTypeEq(ChannelValueType(&val->val), ChannelValueType(&value->val))) { + mcx_log(LOG_ERROR, "Adding value of '%s' to array proxy '%s' failed: Data type mismatch", value->name, proxy->name_); + return RETURN_ERROR; + } + + // check that units match + if (!val->unit && value->unit || val->unit && !value->unit || val->unit && value->unit && strcmp(val->unit, value->unit) != 0) { + mcx_log(LOG_ERROR, "Adding value of '%s' to array proxy '%s' failed: Unit mismatch", value->name, proxy->name_); + return RETURN_ERROR; + } + } + + // add the value to the internal container + retVal = proxy->values_->PushBackNamed(proxy->values_, (Object *)value, value->name); + if (retVal == RETURN_ERROR) { + mcx_log(LOG_ERROR, "Adding value of '%s' to array proxy '%s' failed", value->name, proxy->name_); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +static McxStatus ArrayParameterProxySetup(ArrayParameterProxy * proxy, const char * name, size_t numDims, size_t * dims) { + proxy->name_ = mcx_string_copy(name); + if (name && !proxy->name_) { + mcx_log(LOG_ERROR, "Array proxy setup failed: Not enough memory"); + return RETURN_ERROR; + } + + proxy->numDims_ = numDims; + proxy->dims_ = (size_t *)mcx_calloc(numDims, sizeof(size_t)); + if (!proxy->dims_) { + mcx_log(LOG_ERROR, "Array proxy setup failed: Not enough memory"); + return RETURN_ERROR; + } + + memcpy((void *)proxy->dims_, (void *)dims, numDims * sizeof(size_t)); + + return RETURN_OK; +} + +static const char * ArrayParameterProxyGetName(ArrayParameterProxy * proxy) { + return proxy->name_; +} + +static const char * ArrayParameterProxyGetDesc(ArrayParameterProxy * proxy) { + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + return value->info->desc; + } + + return NULL; +} + +static const char * ArrayParameterProxyGetUnit(ArrayParameterProxy * proxy) { + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + return value->unit; + } + + return NULL; +} + +static ObjectContainer * ArrayParameterProxyGetValues(ArrayParameterProxy * proxy) { + return proxy->values_; +} + +static size_t ArrayParameterProxyGetNumDims(ArrayParameterProxy * proxy) { + return proxy->numDims_; +} + +static size_t ArrayParameterProxyGetDim(ArrayParameterProxy * proxy, size_t idx) { + if (idx >= proxy->numDims_) { + return (size_t)(-1); + } + + return proxy->dims_[idx]; +} + +static ChannelType * ArrayParameterProxyGetType(ArrayParameterProxy * proxy) { + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + return ChannelValueType(&value->val); + } + + return &ChannelTypeUnknown; +} + +static void ArrayParameterProxyDestructor(ArrayParameterProxy * proxy) { + if (proxy->name_) { mcx_free(proxy->name_); } + if (proxy->dims_) { mcx_free(proxy->dims_); } + + proxy->numDims_ = 0; + + // don't destroy the contained objects as they are just weak references + object_destroy(proxy->values_); +} + +static fmi2_value_reference_t ArrayParameterProxyGetValueReference(ArrayParameterProxy * proxy, size_t idx) { + if (idx < proxy->values_->Size(proxy->values_)) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, idx); + return value->data->vr.scalar; + } + + return (fmi2_value_reference_t)(-1);; +} + +static ChannelValueData * ArrayParameterProxyGetMin(ArrayParameterProxy * proxy) { + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + return value->info->min; + } + + return NULL; +} + +static ChannelValueData * ArrayParameterProxyGetMax(ArrayParameterProxy * proxy) { + if (proxy->values_->Size(proxy->values_) > 0) { + Fmu2Value * value = (Fmu2Value *)proxy->values_->At(proxy->values_, 0); + return value->info->max; + } + + return NULL; +} + +static ArrayParameterProxy * ArrayParameterProxyCreate(ArrayParameterProxy * proxy) { + proxy->Setup = ArrayParameterProxySetup; + proxy->AddValue = ArrayParameterProxyAddValue; + + proxy->GetName = ArrayParameterProxyGetName; + proxy->GetDesc = ArrayParameterProxyGetDesc; + proxy->GetUnit = ArrayParameterProxyGetUnit; + proxy->GetValues = ArrayParameterProxyGetValues; + proxy->GetDim = ArrayParameterProxyGetDim; + proxy->GetNumDims = ArrayParameterProxyGetNumDims; + proxy->GetType = ArrayParameterProxyGetType; + proxy->GetValueReference = ArrayParameterProxyGetValueReference; + proxy->GetMin = ArrayParameterProxyGetMin; + proxy->GetMax = ArrayParameterProxyGetMax; + + proxy->values_ = (ObjectContainer *)object_create(ObjectContainer); + if (!proxy->values_) { + return NULL; + } + + proxy->name_ = NULL; + proxy->dims_ = NULL; + proxy->numDims_ = 0; + + return proxy; +} + +OBJECT_CLASS(ArrayParameterProxy, Object); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ \ No newline at end of file diff --git a/src/core/parameters/ParameterProxies.h b/src/core/parameters/ParameterProxies.h new file mode 100644 index 0000000..f4cf7a8 --- /dev/null +++ b/src/core/parameters/ParameterProxies.h @@ -0,0 +1,92 @@ +/******************************************************************************** + * Copyright (c) 2021 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef MCX_CORE_PARAMETERS_PARAMETER_PROXIES_H +#define MCX_CORE_PARAMETERS_PARAMETER_PROXIES_H + +#include "CentralParts.h" + +#include "fmu/Fmu2Value.h" +#include "objects/ObjectContainer.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +struct ScalarParameterProxy; +typedef struct ScalarParameterProxy ScalarParameterProxy; + +typedef void (*fScalarParameterProxySetValue)(ScalarParameterProxy * proxy, Fmu2Value * value); +typedef ChannelType * (*fScalarParameterProxyGetType)(ScalarParameterProxy * proxy); +typedef Fmu2Value * (*fScalarParameterProxyGetValue)(ScalarParameterProxy * proxy); + +extern const struct ObjectClass _ScalarParameterProxy; + +struct ScalarParameterProxy { + Object _; + + fScalarParameterProxySetValue SetValue; + fScalarParameterProxyGetType GetType; + fScalarParameterProxyGetValue GetValue; + + Fmu2Value * value_; +}; + + +struct ArrayParameterProxy; +typedef struct ArrayParameterProxy ArrayParameterProxy; + +typedef McxStatus(*fArrayParameterProxyAddValue)(ArrayParameterProxy * proxy, Fmu2Value * value); +typedef McxStatus(*fArrayParameterProxySetup)(ArrayParameterProxy * proxy, const char * name, size_t numDims, size_t * dims); +typedef const char * (*fArrayParameterProxyGetName)(ArrayParameterProxy * proxy); +typedef const char * (*fArrayParameterProxyGetDesc)(ArrayParameterProxy * proxy); +typedef const char * (*fArrayParameterProxyGetUnit)(ArrayParameterProxy * proxy); +typedef size_t (*fArrayParameterProxyGetNumDims)(ArrayParameterProxy * proxy); +typedef size_t (*fArrayParameterProxyGetDim)(ArrayParameterProxy * proxy, size_t idx); +typedef ObjectContainer * (*fArrayParameterProxyGetValues)(ArrayParameterProxy * proxy); +typedef ChannelType * (*fArrayParameterProxyGetType)(ArrayParameterProxy * proxy); +typedef fmi2_value_reference_t (*fArrayParameterProxyGetValueReference)(ArrayParameterProxy * proxy, size_t idx); +typedef ChannelValueData * (*fArrayParameterProxyGetMin)(ArrayParameterProxy * proxy); +typedef ChannelValueData * (*fArrayParameterProxyGetMax)(ArrayParameterProxy * proxy); + +extern const struct ObjectClass _ArrayParameterProxy; + +struct ArrayParameterProxy { + Object _; + + fArrayParameterProxySetup Setup; + fArrayParameterProxyAddValue AddValue; + fArrayParameterProxyGetValues GetValues; + fArrayParameterProxyGetName GetName; + fArrayParameterProxyGetDesc GetDesc; + fArrayParameterProxyGetUnit GetUnit; + fArrayParameterProxyGetNumDims GetNumDims; + fArrayParameterProxyGetDim GetDim; + fArrayParameterProxyGetType GetType; + fArrayParameterProxyGetValueReference GetValueReference; + fArrayParameterProxyGetMin GetMin; + fArrayParameterProxyGetMax GetMax; + + size_t numDims_; + size_t * dims_; + + char * name_; + + ObjectContainer * values_; // of Fmu2Value +}; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* MCX_CORE_PARAMETERS_PARAMETER_PROXIES_H */ \ No newline at end of file diff --git a/src/fmu/Fmu1Value.c b/src/fmu/Fmu1Value.c index f5cc149..7f2818a 100644 --- a/src/fmu/Fmu1Value.c +++ b/src/fmu/Fmu1Value.c @@ -13,69 +13,294 @@ #include "fmu/common_fmu1.h" #include "util/string.h" +#include "util/stdlib.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ + +static void Fmu1ValueDataDestructor(Fmu1ValueData * data) { + if (data->type == FMU1_VALUE_ARRAY) { + if (data->var.array.dims) { + mcx_free(data->var.array.dims); + } + if (data->var.array.values) { + mcx_free(data->var.array.values); + } + data->var.array.numDims = 0; + + if (data->vr.array.values) { + mcx_free(data->vr.array.values); + } + } + + data->type = FMU1_VALUE_INVALID; +} + +static Fmu1ValueData * Fmu1ValueDataCreate(Fmu1ValueData * data) { + memset(data, 0, sizeof(Fmu1ValueData)); + + data->type = FMU1_VALUE_INVALID; + + return data; +} + +OBJECT_CLASS(Fmu1ValueData, Object); + + +size_t Fmu1ValueDataArrayNumElems(const Fmu1ValueData * data) { + size_t i = 0; + size_t num = 1; + + if (data->type != FMU1_VALUE_ARRAY) { + return 0; + } + + for (i = 0; i < data->var.array.numDims; i++) { + num *= data->var.array.dims[i]; + } + + return num; +} + + +static Fmu1ValueData * Fmu1ValueDataScalarMake(fmi1_import_variable_t * scalar) { + Fmu1ValueData * data = NULL; + + if (!scalar) { + return NULL; + } + + data = (Fmu1ValueData *) object_create(Fmu1ValueData); + if (data) { + data->type = FMU1_VALUE_SCALAR; + data->var.scalar = scalar; + data->vr.scalar = fmi1_import_get_variable_vr(scalar); + } + + return data; +} + +static Fmu1ValueData * Fmu1ValueDataArrayMake(size_t numDims, size_t dims[], fmi1_import_variable_t ** values) { + Fmu1ValueData * data = NULL; + + if (numDims == 0) { + return NULL; + } + + data = (Fmu1ValueData *) object_create(Fmu1ValueData); + if (data) { + size_t i = 0; + size_t num = 1; + + for (i = 0; i < numDims; i++) { + num *= dims[i]; + } + + data->type = FMU1_VALUE_ARRAY; + + data->var.array.numDims = numDims; + data->var.array.dims = mcx_copy(dims, sizeof(size_t) * numDims); + if (!data->var.array.dims) { + goto cleanup; + } + + data->var.array.values = mcx_copy(values, sizeof(fmi1_import_variable_t *) * num); + if (!data->var.array.values) { + goto cleanup; + } + + data->vr.array.values = mcx_calloc(num, sizeof(fmi1_value_reference_t)); + if (!data->vr.array.values) { + goto cleanup; + } + + for (i = 0; i < num; i++) { + data->vr.array.values[i] = fmi2_import_get_variable_vr(data->var.array.values[i]); + } + } + return data; + +cleanup: + object_destroy(data); + return NULL; +} + + static McxStatus Fmu1ValueSetFromChannelValue(Fmu1Value * v, ChannelValue * val) { return ChannelValueSet(&v->val, val); } +static McxStatus Fmu1ValueSetup(Fmu1Value * value, const char * name, Fmu1ValueData * data, Channel * channel) { + if (!name || !data) { + mcx_log(LOG_ERROR, "Fmu1Value: Setup failed: Name or data missing"); + return RETURN_ERROR; + } + + value->name = mcx_string_copy(name); + value->data = data; + value->channel = channel; + + if (!value->name) { + mcx_log(LOG_ERROR, "Fmu1Value: Setup failed: Can not copy name"); + return RETURN_ERROR; + } + + switch (data->type) { + case FMU1_VALUE_SCALAR: + { + fmi1_base_type_enu_t t = fmi1_import_get_variable_base_type(data->var.scalar); + ChannelValueInit(&value->val, ChannelTypeClone(Fmi1TypeToChannelType(t))); + break; + } + case FMU1_VALUE_ARRAY: + { + fmi1_base_type_enu_t t = fmi1_import_get_variable_base_type(data->var.array.values[0]); + ChannelValueInit(&value->val, ChannelTypeArray(Fmi1TypeToChannelType(t), data->var.array.numDims, data->var.array.dims)); + break; + } + default: + mcx_log(LOG_ERROR, "Fmu1Value: Setup failed: Invalid data type"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + void Fmu1ValueDestructor(Fmu1Value * v) { if (v->name) { mcx_free(v->name); v->name = NULL; } + object_destroy(v->data); + ChannelValueDestructor(&v->val); } Fmu1Value * Fmu1ValueCreate(Fmu1Value * v) { v->SetFromChannelValue = Fmu1ValueSetFromChannelValue; + v->Setup = Fmu1ValueSetup; v->name = NULL; - v->var = NULL; + v->data = NULL; v->channel = NULL; - ChannelValueInit(&v->val, CHANNEL_UNKNOWN); + ChannelValueInit(&v->val, ChannelTypeClone(&ChannelTypeUnknown)); return v; } OBJECT_CLASS(Fmu1Value, Object); -Fmu1Value * Fmu1ValueMake(const char * name, fmi1_import_variable_t * var, Channel * channel) { + +static Fmu1Value * Fmu1ValueMake(const char * name, Fmu1ValueData * data, Channel * channel) { Fmu1Value * value = (Fmu1Value *)object_create(Fmu1Value); if (value) { - McxStatus retVal = RETURN_OK; - fmi1_base_type_enu_t t; - - if (!name || !var) { - mcx_log(LOG_ERROR, "Fmu1Value: Setup failed: Name or data missing"); - mcx_free(value); + if (RETURN_OK != value->Setup(value, name, data, channel)) { + object_destroy(value); return NULL; } + } - value->channel = channel; + return value; +} - t = fmi1_import_get_variable_base_type(var); +Fmu1Value * Fmu1ValueScalarMake(const char * name, fmi1_import_variable_t * var, Channel * channel) { + Fmu1ValueData * data = Fmu1ValueDataScalarMake(var); + return Fmu1ValueMake(name, data, channel); +} - value->name = mcx_string_copy(name); - value->vr = fmi1_import_get_variable_vr(var); - value->var = var; - ChannelValueInit(&value->val, Fmi1TypeToChannelType(t)); +Fmu1Value * Fmu1ValueArrayMake(const char * name, size_t numDims, size_t * dims, fmi1_import_variable_t ** vars, Channel * channel) { + Fmu1ValueData * data = Fmu1ValueDataArrayMake(numDims, dims, vars); + return Fmu1ValueMake(name, data, channel); +} - if (!value->name) { - mcx_log(LOG_ERROR, "Fmu1Value: Setup failed: Cannot copy name"); - mcx_free(value); - return NULL; +Fmu1Value * Fmu1ValueReadScalar(const char * logPrefix, ChannelType * type, Channel * channel, const char * channelName, fmi1_import_t * fmiImport) { + Fmu1Value * value = NULL; + fmi1_import_variable_t * var = NULL; + + var = fmi1_import_get_variable_by_name(fmiImport, channelName); + if (!var) { + mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix, channelName); + return NULL; + } + + if (!ChannelTypeEq(type, Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))) { + mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelName); + mcx_log(LOG_ERROR, + "%s: Expected: %s, Imported from FMU: %s", + logPrefix, + ChannelTypeToString(type), + ChannelTypeToString(Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))); + return NULL; + } + + value = Fmu1ValueScalarMake(channelName, var, channel); + if (!value) { + mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix, channelName); + return RETURN_ERROR; + } + + return value; +} + +Fmu1Value * Fmu1ValueReadArray(const char * logPrefix, ChannelType * type, Channel * channel, const char * channelName, ChannelDimension * dimension, fmi1_import_t * fmiImport) { + Fmu1Value * value = NULL; + fmi1_import_variable_t * var = NULL; + + if (dimension->num > 1) { + mcx_log(LOG_ERROR, "%s: Port %s: Invalid dimension", logPrefix, channelName); + goto cleanup; + } + + size_t i = 0; + size_t startIdx = dimension->startIdxs[0]; + size_t endIdx = dimension->endIdxs[0]; + + fmi1_import_variable_t ** vars = mcx_calloc(endIdx - startIdx + 1, sizeof(fmi1_import_variable_t *)); + if (!vars) { + goto cleanup; + } + + for (i = startIdx; i <= endIdx; i++) { + char * indexedChannelName = CreateIndexedName(channelName, i); + fmi1_import_variable_t * var = fmi1_import_get_variable_by_name(fmiImport, indexedChannelName); + if (!var) { + mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix, indexedChannelName); + goto cleanup; + } + if (!ChannelTypeEq(ChannelTypeArrayInner(type), Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))) { + mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, indexedChannelName); + mcx_log(LOG_ERROR, + "%s: Expected: %s, Imported from FMU: %s", + logPrefix, + ChannelTypeToString(ChannelTypeArrayInner(type)), + ChannelTypeToString(Fmi1TypeToChannelType(fmi1_import_get_variable_base_type(var)))); + goto cleanup; } + vars[i - startIdx] = var; + + mcx_free(indexedChannelName); + } + + size_t dims[] = {endIdx - startIdx + 1}; + value = Fmu1ValueArrayMake(channelName, 1 /* numDims */, dims, vars, channel); + if (!value) { + mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix, channelName); + goto cleanup; + } + +cleanup: + if (vars) { + mcx_free(vars); } return value; } + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/fmu/Fmu1Value.h b/src/fmu/Fmu1Value.h index 4fe99dd..3844657 100644 --- a/src/fmu/Fmu1Value.h +++ b/src/fmu/Fmu1Value.h @@ -19,11 +19,43 @@ extern "C" { #endif /* __cplusplus */ + +typedef enum Fmu1ValueType { + FMU1_VALUE_SCALAR, + FMU1_VALUE_ARRAY, + FMU1_VALUE_INVALID +} Fmu1ValueType; + +extern const struct ObjectClass _Fmu1ValueData; + +typedef struct Fmu1ValueData { + Object _; + + Fmu1ValueType type; + union { + fmi1_import_variable_t * scalar; + struct { + size_t numDims; + size_t * dims; + fmi1_import_variable_t ** values; + } array; + } var; + union { + fmi1_value_reference_t scalar; + struct { + fmi1_value_reference_t * values; + } array; + } vr; +} Fmu1ValueData; + +size_t Fmu1ValueDataArrayNumElems(const Fmu1ValueData * data); + struct Fmu1Value; typedef struct Fmu1Value Fmu1Value; typedef McxStatus(*fFmu1ValueSetFromChannelValue)(Fmu1Value * v, ChannelValue * val); +typedef McxStatus (*fFmu1ValueSetup)(Fmu1Value * value, const char * name, Fmu1ValueData * data, Channel * channel); extern const struct ObjectClass _Fmu1Value; @@ -31,16 +63,30 @@ struct Fmu1Value { Object _; /* base class */ fFmu1ValueSetFromChannelValue SetFromChannelValue; + fFmu1ValueSetup Setup; char * name; Channel * channel; - fmi1_value_reference_t vr; - fmi1_import_variable_t * var; + Fmu1ValueData * data; ChannelValue val; }; -Fmu1Value * Fmu1ValueMake(const char * name, fmi1_import_variable_t * var, Channel * channel); +Fmu1Value * Fmu1ValueScalarMake(const char * name, fmi1_import_variable_t * var, Channel * channel); +Fmu1Value * Fmu1ValueArrayMake(const char * name, size_t numDims, size_t * dims, fmi1_import_variable_t ** vars, Channel * channel); + +Fmu1Value * Fmu1ValueReadScalar(const char * logPrefix, + ChannelType * type, + Channel * channel, + const char * channelName, + fmi1_import_t * fmiImport); +Fmu1Value * Fmu1ValueReadArray(const char * logPrefix, + ChannelType * type, + Channel * channel, + const char * channelName, + ChannelDimension * dimension, + fmi1_import_t * fmiImport); + #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/fmu/Fmu2Value.c b/src/fmu/Fmu2Value.c index 68b2779..cf2e0e5 100644 --- a/src/fmu/Fmu2Value.c +++ b/src/fmu/Fmu2Value.c @@ -11,8 +11,10 @@ #include "fmu/Fmu2Value.h" #include "core/channels/ChannelValue.h" +#include "core/connections/ConnectionInfoFactory.h" #include "CentralParts.h" #include "util/string.h" +#include "util/stdlib.h" #include "fmu/common_fmu2.h" #ifdef __cplusplus @@ -20,20 +22,124 @@ extern "C" { #endif /* __cplusplus */ static void Fmu2ValueDataDestructor(Fmu2ValueData * data) { + if (data->type == FMU2_VALUE_ARRAY) { + mcx_free(data->data.array.dims); + mcx_free(data->data.array.values); + + mcx_free(data->vr.array.values); + } } static Fmu2ValueData * Fmu2ValueDataCreate(Fmu2ValueData * data) { - data->type = FMU2_VALUE_INVALID; + memset(data, 0, sizeof(Fmu2ValueData)); - data->data.binary.lo = NULL; - data->data.binary.hi = NULL; - data->data.binary.size = NULL; + data->type = FMU2_VALUE_INVALID; return data; } OBJECT_CLASS(Fmu2ValueData, Object); +Fmu2VariableInfo * Fmu2VariableInfoMake(fmi2_import_variable_t * var) { + Fmu2VariableInfo * info = (Fmu2VariableInfo *)object_create(Fmu2VariableInfo); + + if (info) { + fmi2_base_type_enu_t type = fmi2_import_get_variable_base_type(var); + ChannelValueData min = { 0 }; + int minDefined = FALSE; + ChannelValueData max = { 0 }; + int maxDefined = FALSE; + + char * xmlDesc = fmi2_import_get_variable_description(var); + info->desc = mcx_string_copy(xmlDesc); + if (xmlDesc && !info->desc) { + goto cleanup; + } + + switch (type) { + case fmi2_base_type_real: + info->type = &ChannelTypeDouble; + min.d = fmi2_import_get_real_variable_min(fmi2_import_get_variable_as_real(var)); + minDefined = min.d != -DBL_MAX; + max.d = fmi2_import_get_real_variable_max(fmi2_import_get_variable_as_real(var)); + maxDefined = max.d != DBL_MAX; + break; + case fmi2_base_type_int: + info->type = &ChannelTypeInteger; + min.i = fmi2_import_get_integer_variable_min(fmi2_import_get_variable_as_integer(var)); + minDefined = min.i != -INT_MIN; + max.i = fmi2_import_get_integer_variable_max(fmi2_import_get_variable_as_integer(var)); + maxDefined = max.i != INT_MAX; + break; + case fmi2_base_type_enum: + info->type = &ChannelTypeInteger; + min.i = fmi2_import_get_enum_variable_min(fmi2_import_get_variable_as_enum(var)); + minDefined = min.i != -INT_MIN; + max.i = fmi2_import_get_enum_variable_max(fmi2_import_get_variable_as_enum(var)); + maxDefined = max.i != INT_MAX; + break; + case fmi2_base_type_str: + info->type = &ChannelTypeString; + break; + case fmi2_base_type_bool: + info->type = &ChannelTypeBool; + break; + default: + info->type = &ChannelTypeUnknown; + break; + } + + if (minDefined) { + info->min = (ChannelValueData *)mcx_calloc(1, sizeof(ChannelValueData)); + if (!info->min) { + goto cleanup; + } + ChannelValueDataSetFromReference(info->min, info->type, &min); + } + + if (maxDefined) { + info->max = (ChannelValueData*)mcx_calloc(1, sizeof(ChannelValueData)); + if (!info->max) { + goto cleanup; + } + ChannelValueDataSetFromReference(info->max, info->type, &max); + } + } + + return info; + +cleanup: + object_destroy(info); + return NULL; +} + +static void Fmu2VariableInfoDestructor(Fmu2VariableInfo * info) { + if (info->min) { + ChannelValueDataDestructor(info->min, info->type); + mcx_free(info->min); + } + if (info->max) { + ChannelValueDataDestructor(info->max, info->type); + mcx_free(info->max); + } + + if (info->desc) { mcx_free(info->desc); } +} + +static Fmu2VariableInfo * Fmu2VariableInfoCreate(Fmu2VariableInfo * info) { + info->type = &ChannelTypeUnknown; + + info->min = NULL; + info->max = NULL; + + info->desc = NULL; + + return info; +} + +OBJECT_CLASS(Fmu2VariableInfo, Object); + + Fmu2ValueData * Fmu2ValueDataScalarMake(fmi2_import_variable_t * scalar) { Fmu2ValueData * data = (Fmu2ValueData *) object_create(Fmu2ValueData); @@ -50,6 +156,44 @@ Fmu2ValueData * Fmu2ValueDataScalarMake(fmi2_import_variable_t * scalar) { return data; } +Fmu2ValueData * Fmu2ValueDataArrayMake(size_t numDims, size_t dims[], fmi2_import_variable_t ** values) { + Fmu2ValueData * data = NULL; + + if (!numDims) { + return NULL; + } + + data = (Fmu2ValueData *) object_create(Fmu2ValueData); + if (data) { + size_t num = 1; + size_t i = 0; + + for (i = 0; i < numDims; i++) { + num *= dims[i]; + } + + data->type = FMU2_VALUE_ARRAY; + data->data.array.numDims = numDims; + data->data.array.dims = mcx_copy(dims, sizeof(size_t) * numDims); + if (!data->data.array.dims) { goto error; } + + data->data.array.values = mcx_copy(values, num * sizeof(fmi2_import_variable_t *)); + if (!data->data.array.values) { goto error; } + + data->vr.array.values = mcx_calloc(num, sizeof(fmi2_value_reference_t)); + if (!data->vr.array.values) { goto error; } + + for (i = 0; i < num; i++) { + data->vr.array.values[i] = fmi2_import_get_variable_vr(data->data.array.values[i]); + } + } + + return data; +error: + if (data) { object_destroy(data); } + return NULL; +} + Fmu2ValueData * Fmu2ValueDataBinaryMake(fmi2_import_variable_t * hi, fmi2_import_variable_t * lo, fmi2_import_variable_t * size) { Fmu2ValueData * data = (Fmu2ValueData *) object_create(Fmu2ValueData); @@ -75,47 +219,157 @@ static McxStatus Fmu2ValueSetFromChannelValue(Fmu2Value * v, ChannelValue * val) return ChannelValueSet(&v->val, val); } -static McxStatus Fmu2ValueSetup(Fmu2Value * v, const char * name, Fmu2ValueData * data, const char * unit, Channel * channel) { +static McxStatus Fmu2ValueGetVariableStart(fmi2_base_type_enu_t t, fmi2_import_variable_t * var, ChannelValue * value) { + + switch (t) { + case fmi2_base_type_real: + value->value.d = fmi2_import_get_real_variable_start(fmi2_import_get_variable_as_real(var)); + break; + case fmi2_base_type_int: + value->value.i = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(var)); + break; + case fmi2_base_type_bool: + value->value.i = fmi2_import_get_boolean_variable_start(fmi2_import_get_variable_as_boolean(var)); + break; + case fmi2_base_type_str: { + const char * buffer = fmi2_import_get_string_variable_start(fmi2_import_get_variable_as_string(var)); + if (RETURN_OK != ChannelValueSetFromReference(value, &buffer)) { + return RETURN_ERROR; + } + break; + } + case fmi2_base_type_enum: + value->value.i = fmi2_import_get_enum_variable_start(fmi2_import_get_variable_as_enum(var)); + break; + default: + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Base type %s not supported", fmi2_base_type_to_string(t)); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +static McxStatus Fmu2ValueGetArrayVariableStart(fmi2_base_type_enu_t t, fmi2_import_variable_t * var, mcx_array * a, size_t i) { + + switch (t) { + case fmi2_base_type_real: + ((double *)a->data)[i] = fmi2_import_get_real_variable_start(fmi2_import_get_variable_as_real(var)); + break; + case fmi2_base_type_int: + ((int *)a->data)[i] = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(var)); + break; + case fmi2_base_type_enum: + ((int *)a->data)[i] = fmi2_import_get_enum_variable_start(fmi2_import_get_variable_as_enum(var)); + break; + case fmi2_base_type_bool: + ((int *)a->data)[i] = fmi2_import_get_boolean_variable_start(fmi2_import_get_variable_as_boolean(var)); + break; + default: + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Array base type %s not supported", fmi2_base_type_to_string(t)); + return RETURN_ERROR; + } + + return RETURN_OK; +} + +static McxStatus Fmu2ValueGetBinaryVariableStart(fmi2_import_variable_t * varHi, fmi2_import_variable_t * varLo, fmi2_import_variable_t * varSize, ChannelValue * value) { fmi2_base_type_enu_t t; + t = fmi2_import_get_variable_base_type(varHi); + if (t != fmi2_base_type_int) { + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Binary base type (hi) %s not supported", fmi2_base_type_to_string(t)); + return RETURN_ERROR; + } + t = fmi2_import_get_variable_base_type(varLo); + if (t != fmi2_base_type_int) { + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Binary base type (lo) %s not supported", fmi2_base_type_to_string(t)); + return RETURN_ERROR; + } + t = fmi2_import_get_variable_base_type(varSize); + if (t != fmi2_base_type_int) { + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Binary base type (size) %s not supported", fmi2_base_type_to_string(t)); + return RETURN_ERROR; + } + + fmi2_integer_t hi = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(varHi)); + fmi2_integer_t lo = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(varLo)); + fmi2_integer_t size = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(varSize)); + + binary_string b; + + b.len = size; + b.data = (char *) ((((long long)hi & 0xffffffff) << 32) | (lo & 0xffffffff)); + + if (RETURN_OK != ChannelValueSetFromReference(value, &b)) { + mcx_log(LOG_ERROR, "Fmu2Value: Could not set value"); + return RETURN_ERROR; + } + + return RETURN_OK; +} + + +static McxStatus Fmu2ValueSetup(Fmu2Value * v, const char * name, Fmu2ValueData * data, const char * unit, Channel * channel) { if (!name || !data) { mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Name or data missing"); return RETURN_ERROR; } - t = fmi2_import_get_variable_base_type(data->data.scalar); - v->name = mcx_string_copy(name); v->unit = mcx_string_copy(unit); v->data = data; v->channel = channel; - ChannelValueInit(&v->val, Fmi2TypeToChannelType(t)); if (!v->name) { mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Cannot copy name"); return RETURN_ERROR; } - switch (t) { - case fmi2_base_type_real: - v->val.value.d = fmi2_import_get_real_variable_start(fmi2_import_get_variable_as_real(data->data.scalar)); - break; - case fmi2_base_type_int: - v->val.value.i = fmi2_import_get_integer_variable_start(fmi2_import_get_variable_as_integer(data->data.scalar)); - break; - case fmi2_base_type_bool: - v->val.value.i = fmi2_import_get_boolean_variable_start(fmi2_import_get_variable_as_boolean(data->data.scalar)); - break; - case fmi2_base_type_str: { - const char * buffer = fmi2_import_get_string_variable_start(fmi2_import_get_variable_as_string(data->data.scalar)); - ChannelValueSetFromReference(&v->val, &buffer); - break; - } - case fmi2_base_type_enum: - v->val.value.i = fmi2_import_get_enum_variable_start(fmi2_import_get_variable_as_enum(data->data.scalar)); - break; - default: - mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Base type %s not supported", fmi2_base_type_to_string(t)); + if (v->data->type == FMU2_VALUE_SCALAR) { + fmi2_base_type_enu_t t = fmi2_import_get_variable_base_type(data->data.scalar); + + ChannelValueInit(&v->val, ChannelTypeClone(Fmi2TypeToChannelType(t))); + + + if (RETURN_OK != Fmu2ValueGetVariableStart(t, data->data.scalar, &v->val)) { + return RETURN_ERROR; + } + } else if (v->data->type == FMU2_VALUE_ARRAY) { + fmi2_base_type_enu_t t = fmi2_import_get_variable_base_type(data->data.array.values[0]); + + ChannelValueInit(&v->val, ChannelTypeArray(Fmi2TypeToChannelType(t), data->data.array.numDims, data->data.array.dims)); + + if (data->data.array.numDims == 0) { + mcx_log(LOG_ERROR, "Fmu2Value: Setup failed: Array of dimension 0 is not supported"); + return RETURN_ERROR; + } + + size_t i = 0, n = 1; + + for (i = 0; i < data->data.array.numDims; i++) { + n *= data->data.array.dims[i]; + } + + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&v->val); + + for (i = 0; i < n; i++) { + if (RETURN_OK != Fmu2ValueGetArrayVariableStart(t, data->data.array.values[i], a, i)) { + return RETURN_ERROR; + } + } + } else if (v->data->type == FMU2_VALUE_BINARY_OSI) { + ChannelValueInit(&v->val, &ChannelTypeBinary); + + if (RETURN_OK != Fmu2ValueGetBinaryVariableStart( + data->data.binary.hi, + data->data.binary.lo, + data->data.binary.size, + &v->val)) { + return RETURN_ERROR; + } + + + } else { return RETURN_ERROR; } @@ -135,7 +389,9 @@ static void Fmu2ValueDestructor(Fmu2Value * v) { mcx_free(v->unit); v->unit = NULL; } + Fmu2ValueDataDestructor(v->data); object_destroy(v->data); + object_destroy(v->info); ChannelValueDestructor(&v->val); } @@ -148,7 +404,9 @@ static Fmu2Value * Fmu2ValueCreate(Fmu2Value * v) { v->unit = NULL; v->data = NULL; v->channel = NULL; - ChannelValueInit(&v->val, CHANNEL_UNKNOWN); + v->info = NULL; + + ChannelValueInit(&v->val, ChannelTypeClone(&ChannelTypeUnknown)); return v; } @@ -174,6 +432,15 @@ Fmu2Value * Fmu2ValueScalarMake(const char * name, fmi2_import_variable_t * scal Fmu2ValueData * data = Fmu2ValueDataScalarMake(scalar); Fmu2Value * value = Fmu2ValueMake(name, data, unit, channel); + value->info = Fmu2VariableInfoMake(scalar); + + return value; +} + +Fmu2Value * Fmu2ValueArrayMake(const char * name, size_t numDims, size_t dims[], fmi2_import_variable_t ** values, const char * unit, Channel * channel) { + Fmu2ValueData * data = Fmu2ValueDataArrayMake(numDims, dims, values); + Fmu2Value * value = Fmu2ValueMake(name, data, unit, channel); + return value; } @@ -188,6 +455,86 @@ void Fmu2ValuePrintDebug(Fmu2Value * val) { mcx_log(LOG_DEBUG, "Fmu2Value { name: \"%s\" }", val->name); } +Fmu2Value * Fmu2ReadFmu2ScalarValue(const char * logPrefix, ChannelType * type, const char * channelName, const char * unitString, fmi2_import_t * fmiImport) { + Fmu2Value * val = NULL; + fmi2_import_variable_t * var = NULL; + + var = fmi2_import_get_variable_by_name(fmiImport, channelName); + if (!var) { + mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix, channelName); + return NULL; + } + + if (!ChannelTypeEq(type, Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))) { + mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, channelName); + mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, + ChannelTypeToString(type), + ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))); + return NULL; + } + + val = Fmu2ValueScalarMake(channelName, var, unitString, NULL); + if (!val) { + mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix, channelName); + return NULL; + } + + return val; +} + +Fmu2Value * Fmu2ReadFmu2ArrayValue(const char * logPrefix, ChannelType * type, const char * channelName, ChannelDimension * dimension, const char * unitString, fmi2_import_t * fmiImport) { + Fmu2Value * val = NULL; + fmi2_import_variable_t * var = NULL; + + if (dimension->num > 1) { + mcx_log(LOG_ERROR, "%s: Port %s: Invalid dimension", logPrefix, channelName); + goto cleanup; + } + + size_t i = 0; + size_t startIdx = dimension->startIdxs[0]; + size_t endIdx = dimension->endIdxs[0]; + + fmi2_import_variable_t ** vars = mcx_calloc(endIdx - startIdx + 1, sizeof(fmi2_import_variable_t *)); + if (!vars) { + goto cleanup; + } + + for (i = startIdx; i <= endIdx; i++) { + char * indexedChannelName = CreateIndexedName(channelName, i); + fmi2_import_variable_t * var = fmi2_import_get_variable_by_name(fmiImport, indexedChannelName); + if (!var) { + mcx_log(LOG_ERROR, "%s: Could not get variable %s", logPrefix, indexedChannelName); + goto cleanup; + } + if (!ChannelTypeEq(ChannelTypeArrayInner(type), Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))) { + mcx_log(LOG_ERROR, "%s: Variable types of %s do not match", logPrefix, indexedChannelName); + mcx_log(LOG_ERROR, "%s: Expected: %s, Imported from FMU: %s", logPrefix, + ChannelTypeToString(ChannelTypeArrayInner(type)), + ChannelTypeToString(Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)))); + goto cleanup; + } + vars[i - startIdx] = var; + + mcx_free(indexedChannelName); + } + + size_t dims[] = { endIdx - startIdx + 1 }; + val = Fmu2ValueArrayMake(channelName, 1 /* numDims */, dims, vars, unitString, NULL); + if (!val) { + mcx_log(LOG_ERROR, "%s: Could not set value for channel %s", logPrefix, channelName); + goto cleanup; + } + +cleanup: + if (vars) { + mcx_free(vars); + } + + return val; +} + + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/fmu/Fmu2Value.h b/src/fmu/Fmu2Value.h index 7664554..fb85f7e 100644 --- a/src/fmu/Fmu2Value.h +++ b/src/fmu/Fmu2Value.h @@ -13,6 +13,7 @@ #include "CentralParts.h" #include "core/channels/Channel.h" +#include "core/channels/ChannelDimension.h" #include "fmilib.h" #ifdef __cplusplus @@ -26,9 +27,10 @@ typedef struct Fmu2ValueData Fmu2ValueData; extern const struct ObjectClass _Fmu2ValueData; typedef enum Fmu2ValueType { - FMU2_VALUE_SCALAR - , FMU2_VALUE_BINARY_OSI - , FMU2_VALUE_INVALID + FMU2_VALUE_SCALAR, + FMU2_VALUE_ARRAY, + FMU2_VALUE_BINARY_OSI, + FMU2_VALUE_INVALID } Fmu2ValueType; struct Fmu2ValueData { @@ -37,6 +39,11 @@ struct Fmu2ValueData { Fmu2ValueType type; union { fmi2_import_variable_t * scalar; + struct { + size_t numDims; + size_t * dims; + fmi2_import_variable_t ** values; + } array; struct { fmi2_import_variable_t * lo; fmi2_import_variable_t * hi; @@ -45,6 +52,9 @@ struct Fmu2ValueData { } data; union { fmi2_value_reference_t scalar; + struct { + fmi2_value_reference_t * values; + } array; struct { fmi2_value_reference_t lo; fmi2_value_reference_t hi; @@ -54,8 +64,24 @@ struct Fmu2ValueData { }; Fmu2ValueData * Fmu2ValueDataScalarMake(fmi2_import_variable_t * scalar); +Fmu2ValueData * Fmu2ValueDataArrayMake(size_t numDims, size_t dims[], fmi2_import_variable_t ** values); Fmu2ValueData * Fmu2ValueDataBinaryMake(fmi2_import_variable_t * hi, fmi2_import_variable_t * lo, fmi2_import_variable_t * size); + +extern const struct ObjectClass _Fmu2VariableInfo; + +typedef struct Fmu2VariableInfo { + Object _; + + ChannelType * type; + + ChannelValueData * min; + ChannelValueData * max; + + char * desc; +} Fmu2VariableInfo; + + struct Fmu2Value; typedef struct Fmu2Value Fmu2Value; @@ -78,15 +104,20 @@ struct Fmu2Value { Channel * channel; Fmu2ValueData * data; + Fmu2VariableInfo * info; ChannelValue val; }; Fmu2Value * Fmu2ValueMake(const char * name, Fmu2ValueData * data, const char * unit, Channel * channel); Fmu2Value * Fmu2ValueScalarMake(const char * name, fmi2_import_variable_t * scalar, const char * unit, Channel * channel); +Fmu2Value * Fmu2ValueArrayMake(const char * name, size_t numDims, size_t dims[], fmi2_import_variable_t ** values, const char * unit, Channel * channel); Fmu2Value * Fmu2ValueBinaryMake(const char * name, fmi2_import_variable_t * hi, fmi2_import_variable_t * lo, fmi2_import_variable_t * size, Channel * channel); void Fmu2ValuePrintDebug(Fmu2Value * val); +Fmu2Value * Fmu2ReadFmu2ScalarValue(const char * logPrefix, ChannelType * type, const char * channelName, const char * unitString, fmi2_import_t * fmiImport); +Fmu2Value * Fmu2ReadFmu2ArrayValue(const char * logPrefix, ChannelType * type, const char * channelName, ChannelDimension * dimension, const char * unitString, fmi2_import_t * fmiImport); + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ diff --git a/src/fmu/common_fmu1.c b/src/fmu/common_fmu1.c index 446599d..949e66d 100644 --- a/src/fmu/common_fmu1.c +++ b/src/fmu/common_fmu1.c @@ -15,6 +15,7 @@ #include "reader/model/parameters/ParameterInput.h" #include "util/string.h" +#include "util/signals.h" #include "fmilib.h" @@ -110,20 +111,20 @@ static fmi1_callback_functions_t fmi1Callbacks = { NULL }; -ChannelType Fmi1TypeToChannelType(fmi1_base_type_enu_t type) { +ChannelType * Fmi1TypeToChannelType(fmi1_base_type_enu_t type) { switch (type) { case fmi1_base_type_real: - return CHANNEL_DOUBLE; + return &ChannelTypeDouble; case fmi1_base_type_int: - return CHANNEL_INTEGER; + return &ChannelTypeInteger; case fmi1_base_type_bool: - return CHANNEL_BOOL; + return &ChannelTypeBool; case fmi1_base_type_str: - return CHANNEL_STRING; + return &ChannelTypeString; case fmi1_base_type_enum: - return CHANNEL_INTEGER; + return &ChannelTypeInteger; default: - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } } @@ -281,15 +282,17 @@ Fmu1Value * Fmu1ReadParamValue(ScalarParameterInput * input, fmi1_import_t * imp return NULL; } - ChannelValueInit(&chVal, input->type); - ChannelValueSetFromReference(&chVal, &input->value.value); + ChannelValueInit(&chVal, ChannelTypeClone(input->type)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &input->value.value)) { + return NULL; + } var = fmi1_import_get_variable_by_name(import, input->name); if (!var) { return NULL; } - val = Fmu1ValueMake(input->name, var, NULL); + val = Fmu1ValueScalarMake(input->name, var, NULL); if (!val) { return NULL; } @@ -372,19 +375,23 @@ static ObjectContainer * Fmu1ReadArrayParamValues(const char * name, goto cleanup_1; } - val = Fmu1ValueMake(varName, var, NULL); + val = Fmu1ValueScalarMake(varName, var, NULL); if (!val) { retVal = RETURN_ERROR; goto cleanup_1; } - if (input->type == CHANNEL_DOUBLE) { - ChannelValueInit(&chVal, CHANNEL_DOUBLE); - ChannelValueSetFromReference(&chVal, &((double *)input->values)[index]); + if (ChannelTypeEq(input->type, &ChannelTypeDouble)) { + ChannelValueInit(&chVal, ChannelTypeClone(&ChannelTypeDouble)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &((double *)input->values)[index])) { + return RETURN_ERROR; + } } else { // integer - ChannelValueInit(&chVal, CHANNEL_INTEGER); - ChannelValueSetFromReference(&chVal, &((int *)input->values)[index]); + ChannelValueInit(&chVal, ChannelTypeClone(&ChannelTypeInteger)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &((int *)input->values)[index])) { + return RETURN_ERROR; + } } retVal = val->SetFromChannelValue(val, &chVal); @@ -466,16 +473,6 @@ ObjectContainer * Fmu1ReadParams(ParametersInput * input, fmi1_import_t * import } if (parameterInput->type == PARAMETER_ARRAY) { - // read parameter dimensions (if any) - should only be defined for array parameters - if (parameterInput->parameter.arrayParameter->numDims >= 2 && - parameterInput->parameter.arrayParameter->dims[1] && - !parameterInput->parameter.arrayParameter->dims[0]) { - mcx_log(LOG_ERROR, "FMU: Array parameter %s: Missing definition for the first dimension " - "while the second dimension is defined.", parameterInput->parameter.arrayParameter->name); - ret = NULL; - goto cleanup; - } - // array - split it into scalars vals = Fmu1ReadArrayParamValues(name, parameterInput->parameter.arrayParameter, import, params); if (vals == NULL) { @@ -531,9 +528,6 @@ ObjectContainer * Fmu1ReadParams(ParametersInput * input, fmi1_import_t * import McxStatus Fmu1SetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { fmi1_status_t status = fmi1_status_ok; - fmi1_import_variable_t * var = fmuVal->var; - fmi1_value_reference_t vr[] = { fmuVal->vr }; - Channel * channel = fmuVal->channel; if (channel && FALSE == channel->IsDefinedDuringInit(channel)) { MCX_DEBUG_LOG("Fmu1SetVariable: %s not set: no defined value during initialization", fmuVal->name); @@ -541,13 +535,14 @@ McxStatus Fmu1SetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { } ChannelValue * const chVal = &fmuVal->val; - ChannelType type = ChannelValueType(chVal); + ChannelType * type = ChannelValueType(chVal); - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; double value = chVal->value.d; - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { value *= -1.; } status = fmi1_import_set_real(fmu->fmiImport, vr, 1, &value); @@ -555,8 +550,9 @@ McxStatus Fmu1SetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { break; case CHANNEL_INTEGER: { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; int value = chVal->value.i; - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { value *= -1; } status = fmi1_import_set_integer(fmu->fmiImport, vr, 1, &value); @@ -564,16 +560,38 @@ McxStatus Fmu1SetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { break; case CHANNEL_BOOL: { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; fmi1_boolean_t value = chVal->value.i; - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { value = !value; } status = fmi1_import_set_boolean(fmu->fmiImport, vr, 1, &value); } break; case CHANNEL_STRING: + { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; status = fmi1_import_set_string(fmu->fmiImport, vr, 1, (fmi1_string_t *) &chVal->value.s); break; + } + case CHANNEL_ARRAY: + { + fmi1_value_reference_t * vrs = fmuVal->data->vr.array.values; + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&fmuVal->val); + + size_t num = mcx_array_num_elements(a); + void * vals = a->data; + + if (ChannelTypeEq(a->type, &ChannelTypeDouble)) { + status = fmi1_import_set_real(fmu->fmiImport, vrs, num, vals); + } else if (ChannelTypeEq(a->type, &ChannelTypeInteger)) { + status = fmi1_import_set_integer(fmu->fmiImport, vrs, num, vals); + } else { + mcx_log(LOG_ERROR, "FMU: Unsupported array variable type: %s", ChannelTypeToString(a->type)); + return RETURN_ERROR; + } + break; + } default: mcx_log(LOG_WARNING, "FMU: Unknown variable type"); break; @@ -582,13 +600,13 @@ McxStatus Fmu1SetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { if (fmi1_status_ok != status) { if (fmi1_status_error == status || fmi1_status_fatal == status) { fmu->runOk = fmi1_false; - mcx_log(LOG_ERROR, "FMU: Setting of variable %s (%d) failed", fmi1_import_get_variable_name(var), vr[0]); + mcx_log(LOG_ERROR, "FMU: Setting of variable %s failed", fmuVal->name); return RETURN_ERROR; } else { if (fmi1_status_warning == status) { - mcx_log(LOG_WARNING, "FMU: Setting of variable %s (%d) returned with a warning", fmi1_import_get_variable_name(var), vr[0]); + mcx_log(LOG_WARNING, "FMU: Setting of variable %s returned with a warning", fmuVal->name); } else if (fmi1_status_discard == status) { - mcx_log(LOG_WARNING, "FMU: Setting of variable %s (%d) discarded", fmi1_import_get_variable_name(var), vr[0]); + mcx_log(LOG_WARNING, "FMU: Setting of variable %s discarded", fmuVal->name); } } } else { @@ -601,14 +619,19 @@ McxStatus Fmu1SetVariableArray(Fmu1CommonStruct * fmu, ObjectContainer * vals) { size_t i = 0; size_t numVars = vals->Size(vals); + mcx_signal_handler_set_this_function(); + for (i = 0; i < numVars; i++) { Fmu1Value * fmuVal = (Fmu1Value *) vals->At(vals, i); if (RETURN_ERROR == Fmu1SetVariable(fmu, fmuVal)) { + mcx_signal_handler_unset_function(); return RETURN_ERROR; } } + mcx_signal_handler_unset_function(); + return RETURN_OK; } @@ -616,37 +639,64 @@ McxStatus Fmu1SetVariableArray(Fmu1CommonStruct * fmu, ObjectContainer * vals) { McxStatus Fmu1GetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { fmi1_status_t status = fmi1_status_ok; - fmi1_import_variable_t * var = fmuVal->var; - fmi1_value_reference_t vr[] = { fmuVal->vr }; - ChannelValue * const chVal = &fmuVal->val; - ChannelType type = ChannelValueType(chVal); + ChannelType * type = ChannelValueType(chVal); - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: - status = fmi1_import_get_real(fmu->fmiImport, vr, 1, (fmi1_real_t *)ChannelValueReference(chVal)); - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; + status = fmi1_import_get_real(fmu->fmiImport, vr, 1, (fmi1_real_t *) ChannelValueDataPointer(chVal)); + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { fmuVal->val.value.d *= -1.; } break; + } case CHANNEL_INTEGER: - status = fmi1_import_get_integer(fmu->fmiImport, vr, 1, (fmi1_integer_t *)ChannelValueReference(chVal)); - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; + status = fmi1_import_get_integer(fmu->fmiImport, vr, 1, (fmi1_integer_t *) ChannelValueDataPointer(chVal)); + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { fmuVal->val.value.i *= -1; } break; + } case CHANNEL_BOOL: - status = fmi1_import_get_boolean(fmu->fmiImport, vr, 1, (fmi1_boolean_t *)ChannelValueReference(chVal)); - if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(var)) { + { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; + status = fmi1_import_get_boolean(fmu->fmiImport, vr, 1, (fmi1_boolean_t *) ChannelValueDataPointer(chVal)); + if (fmi1_variable_is_negated_alias == fmi1_import_get_variable_alias_kind(fmuVal->data->var.scalar)) { fmuVal->val.value.i = !fmuVal->val.value.i; } break; + } case CHANNEL_STRING: { + fmi1_value_reference_t vr[] = {fmuVal->data->vr.scalar}; char * buffer = NULL; status = fmi1_import_get_string(fmu->fmiImport, vr, 1, (fmi1_string_t *)&buffer); - ChannelValueSetFromReference(chVal, &buffer); + if (RETURN_OK != ChannelValueSetFromReference(chVal, &buffer)) { + return RETURN_ERROR; + } + break; + } + case CHANNEL_ARRAY: + { + fmi1_value_reference_t * vrs = fmuVal->data->vr.array.values; + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&fmuVal->val); + + size_t num = mcx_array_num_elements(a); + void * vals = a->data; + + if (ChannelTypeEq(a->type, &ChannelTypeDouble)) { + status = fmi1_import_get_real(fmu->fmiImport, vrs, num, vals); + } else if (ChannelTypeEq(a->type, &ChannelTypeInteger)) { + status = fmi1_import_get_integer(fmu->fmiImport, vrs, num, vals); + } else { + mcx_log(LOG_ERROR, "FMU: Unsupported array variable type: %s", ChannelTypeToString(a->type)); + return RETURN_ERROR; + } break; } default: @@ -657,7 +707,7 @@ McxStatus Fmu1GetVariable(Fmu1CommonStruct * fmu, Fmu1Value * fmuVal) { if (fmi1_status_ok != status) { if (fmi1_status_error == status || fmi1_status_fatal == status) { fmu->runOk = fmi1_false; - mcx_log(LOG_ERROR, "FMU: Getting of variable %s (%d) failed", fmi1_import_get_variable_name(var), vr[0]); + mcx_log(LOG_ERROR, "FMU: Getting of variable %s failed", fmuVal->name); return RETURN_ERROR; } else { // TODO: handle warning @@ -672,15 +722,20 @@ McxStatus Fmu1GetVariableArray(Fmu1CommonStruct * fmu, ObjectContainer * vals) { size_t i = 0; size_t numVars = vals->Size(vals); + mcx_signal_handler_set_this_function(); + for (i = 0; i < numVars; i++) { McxStatus retVal = RETURN_OK; Fmu1Value * fmuVal = (Fmu1Value *) vals->At(vals, i); retVal = Fmu1GetVariable(fmu, fmuVal); if (RETURN_ERROR == retVal) { + mcx_signal_handler_unset_function(); return RETURN_ERROR; } } + mcx_signal_handler_unset_function(); + return RETURN_OK; } @@ -704,7 +759,7 @@ McxStatus fmi1CreateValuesOutOfVariables(ObjectContainer * vals, fmi1_import_var Fmu1Value * val = NULL; const char * name = fmi1_import_get_variable_name(actualVar); - val = Fmu1ValueMake(name, actualVar, NULL); + val = Fmu1ValueScalarMake(name, actualVar, NULL); retVal = vals->PushBack(vals, (Object *)val); if (RETURN_ERROR == retVal) { @@ -726,7 +781,7 @@ McxStatus fmi1AddLocalChannelsFromLocalValues(ObjectContainer * vals, const char for (i = 0; i < sizeList; i++) { Fmu1Value * val = (Fmu1Value *) vals->At(vals, i); - fmi1_import_variable_t * actualVar = val->var; + fmi1_import_variable_t * actualVar = val->data->var.scalar; // TODO array const char * name = NULL; fmi1_base_type_enu_t type; @@ -751,7 +806,7 @@ McxStatus fmi1AddLocalChannelsFromLocalValues(ObjectContainer * vals, const char } - retVal = DatabusAddLocalChannel(db, name, buffer, unitName, ChannelValueReference(&val->val), ChannelValueType(&val->val)); + retVal = DatabusAddLocalChannel(db, name, buffer, unitName, ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); mcx_free(buffer); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "%s: Adding channel %s to databus failed", compName, name); diff --git a/src/fmu/common_fmu1.h b/src/fmu/common_fmu1.h index eed6676..945e655 100644 --- a/src/fmu/common_fmu1.h +++ b/src/fmu/common_fmu1.h @@ -36,7 +36,7 @@ typedef enum enum_VAR_TYPE { VAR_STRING } FMI_VAR_TYPE; -ChannelType Fmi1TypeToChannelType(fmi1_base_type_enu_t type); +ChannelType * Fmi1TypeToChannelType(fmi1_base_type_enu_t type); typedef struct Fmu1CommonStruct { diff --git a/src/fmu/common_fmu2.c b/src/fmu/common_fmu2.c index 1f1913a..d801886 100644 --- a/src/fmu/common_fmu2.c +++ b/src/fmu/common_fmu2.c @@ -9,16 +9,23 @@ ********************************************************************************/ #include "fmu/common_fmu2.h" +#include "core/channels/ChannelValue.h" #include "fmu/common_fmu.h" /* for jm callbacks */ #include "fmu/Fmu2Value.h" +#include "core/channels/ChannelInfo.h" +#include "core/parameters/ParameterProxies.h" + #include "reader/model/parameters/ArrayParameterDimensionInput.h" #include "reader/model/parameters/ParameterInput.h" #include "reader/model/parameters/ParametersInput.h" #include "util/string.h" #include "util/stdlib.h" +#include "util/signals.h" + +#include "objects/Map.h" #include "fmilib.h" @@ -27,8 +34,8 @@ extern "C" { #endif /* __cplusplus */ -fmi2_base_type_enu_t ChannelTypeToFmi2Type(ChannelType type) { - switch (type) { +fmi2_base_type_enu_t ChannelTypeToFmi2Type(ChannelType * type) { + switch (type->con) { case CHANNEL_DOUBLE: return fmi2_base_type_real; case CHANNEL_INTEGER: @@ -42,23 +49,40 @@ fmi2_base_type_enu_t ChannelTypeToFmi2Type(ChannelType type) { } } -ChannelType Fmi2TypeToChannelType(fmi2_base_type_enu_t type) { +ChannelType * Fmi2TypeToChannelType(fmi2_base_type_enu_t type) { switch (type) { case fmi2_base_type_real: - return CHANNEL_DOUBLE; + return &ChannelTypeDouble; case fmi2_base_type_int: - return CHANNEL_INTEGER; + return &ChannelTypeInteger; case fmi2_base_type_bool: - return CHANNEL_BOOL; + return &ChannelTypeBool; case fmi2_base_type_str: - return CHANNEL_STRING; + return &ChannelTypeString; case fmi2_base_type_enum: - return CHANNEL_INTEGER; + return &ChannelTypeInteger; default: - return CHANNEL_UNKNOWN; + return &ChannelTypeUnknown; } } +const char * Fmi2TypeToString(fmi2_base_type_enu_t type) { + switch (type) { + case fmi2_base_type_real: + return "fmi2Real"; + case fmi2_base_type_int: + return "fmi2Integer"; + case fmi2_base_type_bool: + return "fmi2Bool"; + case fmi2_base_type_str: + return "fmi2String"; + case fmi2_base_type_enum: + return "fmi2Enum"; + } + return "fmi2Unknown"; +} + + McxStatus Fmu2CommonStructInit(Fmu2CommonStruct * fmu) { fmu->fmiImport = NULL; @@ -73,6 +97,10 @@ McxStatus Fmu2CommonStructInit(Fmu2CommonStruct * fmu) { fmu->tunableParams = (ObjectContainer *) object_create(ObjectContainer); fmu->initialValues = (ObjectContainer *) object_create(ObjectContainer); + fmu->arrayParams = (ObjectContainer *) object_create(ObjectContainer); + + fmu->connectedIn = (ObjectContainer *) object_create(ObjectContainer); + fmu->numLogCategories = 0; fmu->logCategories = NULL; @@ -170,11 +198,13 @@ McxStatus Fmu2CommonStructSetup(FmuCommon * common, Fmu2CommonStruct * fmu2, fmi } mcx_log(LOG_DEBUG, "%s: instantiatefn: %x", common->instanceName, fmi2_import_instantiate); + mcx_signal_handler_set_function("fmi2_import_instantiate"), jmStatus = fmi2_import_instantiate(fmu2->fmiImport, common->instanceName, fmu_type, NULL, fmi2_false /* visible */); + mcx_signal_handler_unset_function(); if (jm_status_error == jmStatus) { mcx_log(LOG_ERROR, "%s: Instantiate failed", common->instanceName); return RETURN_ERROR; @@ -219,6 +249,11 @@ void Fmu2CommonStructDestructor(Fmu2CommonStruct * fmu) { object_destroy(fmu->params); } + if (fmu->arrayParams) { + fmu->arrayParams->DestroyObjects(fmu->arrayParams); + object_destroy(fmu->arrayParams); + } + if (fmu->initialValues) { fmu->initialValues->DestroyObjects(fmu->initialValues); object_destroy(fmu->initialValues); @@ -234,6 +269,10 @@ void Fmu2CommonStructDestructor(Fmu2CommonStruct * fmu) { object_destroy(fmu->tunableParams); } + if (fmu->connectedIn) { + object_destroy(fmu->connectedIn); + } + if (fmu->fmiImport) { fmi2_import_free(fmu->fmiImport); fmu->fmiImport = NULL; @@ -262,8 +301,10 @@ Fmu2Value * Fmu2ReadParamValue(ScalarParameterInput * input, return NULL; } - ChannelValueInit(&chVal, input->type); - ChannelValueSetFromReference(&chVal, &input->value.value); + ChannelValueInit(&chVal, ChannelTypeClone(input->type)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &input->value.value)) { + return NULL; + } var = fmi2_import_get_variable_by_name(import, input->name); if (!var) { @@ -320,8 +361,8 @@ static ObjectContainer* Fmu2ReadArrayParamValues(const char * name, end2 = input->dims[1]->end; } - for (k = start2; k <= end2; k++) { - for (j = start1; j <= end1; j++, index++) { + for (k = start1; k <= end1; k++) { + for (j = start2; j <= end2; j++, index++) { Fmu2Value * val = NULL; char * varName = (char *) mcx_calloc(stringBufferLength, sizeof(char)); fmi2_import_variable_t * var = NULL; @@ -335,7 +376,7 @@ static ObjectContainer* Fmu2ReadArrayParamValues(const char * name, if (input->numDims == 2) { snprintf(varName, stringBufferLength, "%s[%zu,%zu]", name, k, j); } else { - snprintf(varName, stringBufferLength, "%s[%zu]", name, j); + snprintf(varName, stringBufferLength, "%s[%zu]", name, k); } var = fmi2_import_get_variable_by_name(import, varName); @@ -351,12 +392,18 @@ static ObjectContainer* Fmu2ReadArrayParamValues(const char * name, goto fmu2_read_array_param_values_for_cleanup; } - if (input->type == CHANNEL_DOUBLE) { - ChannelValueInit(&chVal, CHANNEL_DOUBLE); - ChannelValueSetFromReference(&chVal, &((double *)input->values)[index]); + if (ChannelTypeEq(input->type, &ChannelTypeDouble)) { + ChannelValueInit(&chVal, ChannelTypeClone(&ChannelTypeDouble)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &((double *)input->values)[index])) { + retVal = RETURN_ERROR; + goto fmu2_read_array_param_values_for_cleanup; + } } else { // integer - ChannelValueInit(&chVal, CHANNEL_INTEGER); - ChannelValueSetFromReference(&chVal, &((int *)input->values)[index]); + ChannelValueInit(&chVal, ChannelTypeClone(&ChannelTypeInteger)); + if (RETURN_OK != ChannelValueSetFromReference(&chVal, &((int *)input->values)[index])) { + retVal = RETURN_ERROR; + goto fmu2_read_array_param_values_for_cleanup; + } } retVal = val->SetFromChannelValue(val, &chVal); @@ -423,98 +470,131 @@ static ObjectContainer* Fmu2ReadArrayParamValues(const char * name, } // Reads parameters from the input file (both scalar and array). -// +// If arrayParams is given, creates proxy views to array elements. // Ignores parameters provided via the `ignore` argument. -ObjectContainer * Fmu2ReadParams(ParametersInput * input, fmi2_import_t * import, ObjectContainer * ignore) { - ObjectContainer * params = (ObjectContainer *) object_create(ObjectContainer); - ObjectContainer * ret = params; // used for unified cleanup via goto +McxStatus Fmu2ReadParams(ObjectContainer * params, ObjectContainer * arrayParams, ParametersInput * input, fmi2_import_t * import, ObjectContainer * ignore) { + McxStatus retVal = RETURN_OK; size_t i = 0; size_t num = 0; - McxStatus retVal = RETURN_OK; if (!params) { - return NULL; + return RETURN_ERROR; } num = input->parameters->Size(input->parameters); for (i = 0; i < num; i++) { ParameterInput * parameterInput = (ParameterInput *) input->parameters->At(input->parameters, i); - char * name = NULL; - Fmu2Value * val = NULL; - ObjectContainer * vals = NULL; - name = mcx_string_copy(parameterInput->parameter.arrayParameter->name); if (!name) { - ret = NULL; - goto fmu2_read_params_for_cleanup; + retVal = RETURN_ERROR; + goto cleanup_0; } // ignore the parameter if it is in the `ignore` container if (ignore && ignore->GetNameIndex(ignore, name) >= 0) { - goto fmu2_read_params_for_cleanup; + goto cleanup_0; } if (parameterInput->type == PARAMETER_ARRAY) { - // read parameter dimensions (if any) - should only be defined for array parameters - if (parameterInput->parameter.arrayParameter->numDims >=2 && - parameterInput->parameter.arrayParameter->dims[1] && - !parameterInput->parameter.arrayParameter->dims[0]) { - mcx_log(LOG_ERROR, "FMU: Array parameter %s: Missing definition for the first dimension " - "while the second dimension is defined.", parameterInput->parameter.arrayParameter->name); - ret = NULL; - goto fmu2_read_params_for_cleanup; - } + ObjectContainer * vals = NULL; + ArrayParameterProxy * proxy = NULL; + size_t j = 0; // array - split it into scalars vals = Fmu2ReadArrayParamValues(name, parameterInput->parameter.arrayParameter, import, params); if (vals == NULL) { mcx_log(LOG_ERROR, "FMU: Could not read array parameter %s", name); - ret = NULL; - goto fmu2_read_params_for_cleanup; + retVal = RETURN_ERROR; + goto cleanup_1; + } + + if (arrayParams) { + // set up a proxy that will reference the individual scalars + proxy = (ArrayParameterProxy *) object_create(ArrayParameterProxy); + if (!proxy) { + mcx_log(LOG_ERROR, "FMU: Creating an array proxy failed: No memory"); + retVal = RETURN_ERROR; + goto cleanup_1; + } + + retVal = proxy->Setup(proxy, name, parameterInput->parameter.arrayParameter->numDims, parameterInput->parameter.arrayParameter->dims); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "FMU Array parameter %s: Array proxy setup failed", name); + goto cleanup_1; + } } // store the scalar values - size_t j = 0; for (j = 0; j < vals->Size(vals); j++) { - Object * v = vals->At(vals, j); - retVal = params->PushBackNamed(params, v, ((Fmu2Value*)v)->name); + Fmu2Value * v = (Fmu2Value *) vals->At(vals, j); + retVal = params->PushBackNamed(params, (Object *) v, v->name); if (RETURN_OK != retVal) { - ret = NULL; - goto fmu2_read_params_for_cleanup; + mcx_log(LOG_ERROR, "FMU: Adding element #%zu of parameter %s failed", j, name); + goto cleanup_1; + } + + vals->SetAt(vals, j, NULL); + + if (arrayParams) { + retVal = proxy->AddValue(proxy, v); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "FMU: Adding proxy to element #%zu of parameter %s failed", j, name); + goto cleanup_1; + } + } + } + + if (arrayParams) { + retVal = arrayParams->PushBackNamed(arrayParams, (Object *) proxy, proxy->GetName(proxy)); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "FMU: Adding proxy for %s failed", name); + goto cleanup_1; + } + } + +cleanup_1: + if (RETURN_ERROR == retVal) { + object_destroy(proxy); + if (vals) { + vals->DestroyObjects(vals); } } object_destroy(vals); + + if (RETURN_ERROR == retVal) { + goto cleanup_0; + } } else { + Fmu2Value * val = NULL; + // read the scalar value val = Fmu2ReadParamValue(parameterInput->parameter.scalarParameter, import); if (val == NULL) { mcx_log(LOG_ERROR, "FMU: Could not read parameter value of parameter %s", name); - ret = NULL; - goto fmu2_read_params_for_cleanup; + retVal = RETURN_ERROR; + goto cleanup_2; } // store the read value retVal = params->PushBackNamed(params, (Object * ) val, name); if (RETURN_OK != retVal) { - ret = NULL; - goto fmu2_read_params_for_cleanup; + goto cleanup_2; } - } -fmu2_read_params_for_cleanup: - if (name) { mcx_free(name); } - if (ret == NULL) { - if (val) { object_destroy(val); } - if (vals) { - vals->DestroyObjects(vals); - object_destroy(vals); +cleanup_2: + if (RETURN_ERROR == retVal) { + object_destroy(val); } + } - goto cleanup; +cleanup_0: + if (name) { mcx_free(name); } + if (retVal == RETURN_ERROR) { + return RETURN_ERROR; } } @@ -527,30 +607,22 @@ ObjectContainer * Fmu2ReadParams(ParametersInput * input, fmi2_import_t * import status = params->Sort(params, NaturalComp, NULL); if (RETURN_OK != status) { mcx_log(LOG_ERROR, "FMU: Unable to sort parameters"); - ret = NULL; - goto cleanup; + return RETURN_ERROR; } for (i = 0; i < n - 1; i++) { Fmu2Value * a = (Fmu2Value *) params->At(params, i); Fmu2Value * b = (Fmu2Value *) params->At(params, i + 1); - if (! strcmp(a->name, b->name)) { + if (!strcmp(a->name, b->name)) { mcx_log(LOG_ERROR, "FMU: Duplicate definition of parameter %s", a->name); - ret = NULL; - goto cleanup; + return RETURN_ERROR; } } } } -cleanup: - if (ret == NULL) { - params->DestroyObjects(params); - object_destroy(params); - } - - return ret; + return retVal; } @@ -589,11 +661,357 @@ McxStatus Fmu2UpdateTunableParamValues(ObjectContainer * tunableParams, ObjectCo return retVal; } +typedef struct ConnectedElems{ + int is_connected; + size_t num_elems; + size_t * elems; +} ConnectedElems; -McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { - fmi2_status_t status = fmi2_status_ok; +typedef struct ChannelElement { + size_t channel_idx; + size_t elem_idx; +} ChannelElement; - char * const name = fmuVal->name; +static Vector * GetAllElems(ChannelElement * elems, size_t num, size_t channel_idx) { + size_t i = 0; + Vector * indices = (Vector *) object_create(Vector); + + if (!indices) { + mcx_log(LOG_ERROR, "GetAllElems: Not enough memory"); + return NULL; + } + + indices->Setup(indices, sizeof(size_t), NULL, NULL, NULL); + + for (i = 0; i < num; i++) { + if (elems[i].channel_idx == channel_idx) { + if (RETURN_ERROR == indices->PushBack(indices, &elems[i].elem_idx)) { + mcx_log(LOG_ERROR, "GetAllElems: Collecting element indices failed"); + object_destroy(indices); + return NULL; + } + } + } + + return indices; +} + +McxStatus Fmu2SetDependencies(Fmu2CommonStruct * fmu2, Databus * db, Dependencies * deps, int init) { + McxStatus ret_val = RETURN_OK; + + size_t *start_index = NULL; + size_t *dependency = NULL; + char *factor_kind = NULL; + + size_t i = 0, j = 0, k = 0; + size_t num_dependencies = 0; + size_t dep_idx = 0; + + // mapping between dependency indices (from the modelDescription file) and the dependency <-> channel mapping + SizeTSizeTMap *dependencies_to_in_channels = (SizeTSizeTMap*)object_create(SizeTSizeTMap); + // mapping between unknown indices (from the modelDescription file) and the unknowns <-> channel list + SizeTSizeTMap *unknowns_to_out_channels = (SizeTSizeTMap*)object_create(SizeTSizeTMap); + + // get dependency information via the fmi library + fmi2_import_variable_list_t * init_unknowns = NULL; + + if (init) { + init_unknowns = fmi2_import_get_initial_unknowns_list(fmu2->fmiImport); + fmi2_import_get_initial_unknowns_dependencies(fmu2->fmiImport, &start_index, &dependency, &factor_kind); + } else { + init_unknowns = fmi2_import_get_outputs_list(fmu2->fmiImport); + fmi2_import_get_outputs_dependencies(fmu2->fmiImport, &start_index, &dependency, &factor_kind); + } + + size_t num_init_unknowns = fmi2_import_get_variable_list_size(init_unknowns); + + // the dependency information in is encoded via variable indices in modelDescription.xml + // our dependency matrix uses channel indices + // to align those 2 index types we use helper dictionaries which store the mapping between them + + // map each dependency index to an input channel index + ObjectContainer *in_vars = fmu2->in; + size_t num_in_vars = in_vars->Size(in_vars); + + DatabusInfo * db_info = DatabusGetInInfo(db); + size_t num_in_channels = DatabusInfoGetChannelNum(db_info); + + // list describing for each channel which channel elements are connected + ConnectedElems * in_channel_connectivity = (ConnectedElems *) mcx_calloc(num_in_channels, sizeof(ConnectedElems)); + if (!in_channel_connectivity) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Input connectivity map allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + + // List which for each dependency describes which channel and element index it corresponds to + // The index of elements in this list doesn't correspond to the dependency index from the modelDescription file + ChannelElement * dependencies_to_inputs = (ChannelElement *) mcx_calloc(DatabusGetInChannelsElemNum(db), sizeof(ChannelElement)); + if (!dependencies_to_inputs) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Dependencies to inputs map allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + + // list used to know the mapping between unknowns and channels/elements + ChannelElement * unknowns_to_outputs = (ChannelElement *) mcx_calloc(DatabusGetOutChannelsElemNum(db), sizeof(ChannelElement)); + if (!unknowns_to_outputs) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Unknowns to outputs map allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + + // List used to later find ommitted elements + ChannelElement * processed_output_elems = (ChannelElement *) mcx_calloc(DatabusGetOutChannelsElemNum(db), sizeof(ChannelElement)); + if (!processed_output_elems) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Processed output elements allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + + for (i = 0; i < num_in_vars; ++i) { + Fmu2Value *val = (Fmu2Value *)in_vars->At(in_vars, i); + Channel * ch = (Channel *) DatabusGetInChannel(db, i); + ChannelIn * in = (ChannelIn *) ch; + ChannelInfo * info = DatabusInfoGetChannel(db_info, i); + if (ch->IsConnected(ch)) { + if (ChannelTypeIsArray(info->type)) { + in_channel_connectivity[i].is_connected = TRUE; + in_channel_connectivity[i].num_elems = 0; + in_channel_connectivity[i].elems = (int *) mcx_calloc(ChannelDimensionNumElements(info->dimension), sizeof(size_t)); + if (!in_channel_connectivity[i].elems) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Input connectivity element container allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + + // if an element index appears in elems, it means that element is connected + Vector * connInfos = in->GetConnectionInfos(in); + for (j = 0; j < connInfos->Size(connInfos); j++) { + ConnectionInfo * connInfo = *(ConnectionInfo**) connInfos->At(connInfos, j); + size_t k = 0; + + for (k = 0; k < ChannelDimensionNumElements(connInfo->targetDimension); k++) { + size_t idx = ChannelDimensionGetIndex(connInfo->targetDimension, k, info->type->ty.a.dims) - info->dimension->startIdxs[0]; + in_channel_connectivity[i].elems[in_channel_connectivity[i].num_elems++] = idx; + } + } + object_destroy(connInfos); + } else { + in_channel_connectivity[i].is_connected = TRUE; + // scalar channels are treated like they have 1 element (equal to zero) + in_channel_connectivity[i].num_elems = 1; + in_channel_connectivity[i].elems = (int*)mcx_calloc(1, sizeof(size_t)); + if (!in_channel_connectivity[i].elems) { + mcx_log(LOG_ERROR, "SetDependenciesFMU2: Input connectivity element allocation failed"); + ret_val = RETURN_ERROR; + goto cleanup; + } + in_channel_connectivity[i].elems[0] = 0; + } + } + + if (val->data->type == FMU2_VALUE_SCALAR) { + fmi2_import_variable_t *var = val->data->data.scalar; + size_t idx = fmi2_import_get_variable_original_order(var) + 1; + dependencies_to_in_channels->Add(dependencies_to_in_channels, idx, dep_idx); + + dependencies_to_inputs[dep_idx].channel_idx = i; + dep_idx++; + } else if (val->data->type == FMU2_VALUE_ARRAY) { + size_t num_elems = 1; + size_t j = 0; + + for (j = 0; j < val->data->data.array.numDims; j++) { + num_elems *= val->data->data.array.dims[j]; + } + + for (j = 0; j < num_elems; j++) { + fmi2_import_variable_t * var = val->data->data.array.values[j]; + size_t idx = fmi2_import_get_variable_original_order(var) + 1; + dependencies_to_in_channels->Add(dependencies_to_in_channels, idx, dep_idx); + + dependencies_to_inputs[dep_idx].channel_idx = i; + dependencies_to_inputs[dep_idx].elem_idx = j; + dep_idx++; + } + } + } + + // element is not present in modelDescription.xml + // The dependency matrix consists of only 1 (if input is connected) + if (start_index == NULL) { + for (i = 0; i < GetDependencyNumOut(deps); ++i) { + for (j = 0; j < GetDependencyNumIn(deps); ++j) { + if (in_channel_connectivity[j].is_connected) { + ret_val = SetDependency(deps, j, i, DEP_DEPENDENT); + if (RETURN_OK != ret_val) { + goto cleanup; + } + } + } + } + + goto cleanup; + } + + // map each initial_unkown index to an output channel index + // for array channels, there might be multiple entries initial_unknown_idx -> channel_idx + ObjectContainer *out_vars = fmu2->out; + size_t num_out_vars = out_vars->Size(out_vars); + size_t unknown_idx = 0; + for (i = 0; i < num_out_vars; ++i) { + Fmu2Value *val = (Fmu2Value *)out_vars->At(out_vars, i); + + if (val->data->type == FMU2_VALUE_SCALAR) { + fmi2_import_variable_t *var = val->data->data.scalar; + size_t idx = fmi2_import_get_variable_original_order(var) + 1; + unknowns_to_out_channels->Add(unknowns_to_out_channels, idx, unknown_idx); + + unknowns_to_outputs[unknown_idx].channel_idx = i; + unknown_idx++; + } else if (val->data->type == FMU2_VALUE_ARRAY) { + size_t num_elems = 1; + size_t j = 0; + + for (j = 0; j < val->data->data.array.numDims; j++) { + num_elems *= val->data->data.array.dims[j]; + } + + for (j = 0; j < num_elems; j++) { + fmi2_import_variable_t * var = val->data->data.array.values[j]; + size_t idx = fmi2_import_get_variable_original_order(var) + 1; + unknowns_to_out_channels->Add(unknowns_to_out_channels, idx, unknown_idx); + + unknowns_to_outputs[unknown_idx].channel_idx = i; + unknowns_to_outputs[unknown_idx].elem_idx = j; + unknown_idx++; + } + } + } + + // fill up the dependency matrix + size_t processed_elems = 0; + for (i = 0; i < num_init_unknowns; ++i) { + fmi2_import_variable_t *init_unknown = fmi2_import_get_variable(init_unknowns, i); + size_t init_unknown_idx = fmi2_import_get_variable_original_order(init_unknown) + 1; + + SizeTSizeTElem * out_pair = unknowns_to_out_channels->Get(unknowns_to_out_channels, init_unknown_idx); + if (out_pair == NULL) { + continue; // in case some variables are ommitted from the input file + } + + ChannelElement * out_elem = &unknowns_to_outputs[out_pair->value]; + + processed_output_elems[processed_elems].channel_idx = out_elem->channel_idx; + processed_output_elems[processed_elems].elem_idx = out_elem->elem_idx; + processed_elems++; + + num_dependencies = start_index[i + 1] - start_index[i]; + for (j = 0; j < num_dependencies; ++j) { + dep_idx = dependency[start_index[i] + j]; + if (dep_idx == 0) { + // The element does not explicitly define a `dependencies` attribute + // In this case it depends on all inputs + for (k = 0; k < num_in_channels; ++k) { + if (in_channel_connectivity[k].is_connected) { + ret_val = SetDependency(deps, k, out_elem->channel_idx, DEP_DEPENDENT); + if (RETURN_OK != ret_val) { + goto cleanup; + } + } + } + } else { + // The element explicitly defines its dependencies + SizeTSizeTElem * in_pair = dependencies_to_in_channels->Get(dependencies_to_in_channels, dep_idx); + if (in_pair) { + ChannelElement * dep = &dependencies_to_inputs[in_pair->value]; + + ConnectedElems * elems = &in_channel_connectivity[dep->channel_idx]; + if (elems->is_connected) { + size_t k = 0; + for (k = 0; k < elems->num_elems; k++) { + if (elems->elems[k] == dep->elem_idx) { + ret_val = SetDependency(deps, dep->channel_idx, out_elem->channel_idx, DEP_DEPENDENT); + if (RETURN_OK != ret_val) { + goto cleanup; + } + break; + } + } + } + } + } + } + } + + // Initial unknowns which are ommitted from the element in + // modelDescription.xml file depend on all inputs + for (i = 0; i < num_out_vars; ++i) { + Fmu2Value * val = (Fmu2Value *) out_vars->At(out_vars, i); + + Vector * elems = GetAllElems(processed_output_elems, processed_elems, i); + + if (val->data->type == FMU2_VALUE_ARRAY) { + size_t num_elems = 1; + size_t j = 0; + + for (j = 0; j < val->data->data.array.numDims; j++) { + num_elems *= val->data->data.array.dims[j]; + } + + for (j = 0; j < num_elems; j++) { + if (!elems->Contains(elems, &j)) { + if (fmi2_import_get_initial(val->data->data.array.values[j]) != fmi2_initial_enu_exact) { + for (k = 0; k < num_in_channels; ++k) { + if (in_channel_connectivity[k].is_connected) { + ret_val = SetDependency(deps, k, i, DEP_DEPENDENT); + if (RETURN_OK != ret_val) { + goto cleanup; + } + } + } + } + } + } + } else { + if (elems->Size(elems) == 0) { + if (fmi2_import_get_initial(val->data->data.scalar) != fmi2_initial_enu_exact) { + for (k = 0; k < num_in_channels; ++k) { + if (in_channel_connectivity[k].is_connected) { + ret_val = SetDependency(deps, k, i, DEP_DEPENDENT); + if (RETURN_OK != ret_val) { + goto cleanup_1; + } + } + } + } + } + } + + object_destroy(elems); + continue; + +cleanup_1: + object_destroy(elems); + goto cleanup; + } + +cleanup: // free dynamically allocated objects + object_destroy(dependencies_to_in_channels); + object_destroy(unknowns_to_out_channels); + if (in_channel_connectivity) { mcx_free(in_channel_connectivity); } + if (dependencies_to_inputs) { mcx_free(dependencies_to_inputs); } + if (unknowns_to_outputs) { mcx_free(unknowns_to_outputs); } + if (processed_output_elems) { mcx_free(processed_output_elems); } + fmi2_import_free_variable_list(init_unknowns); + + return ret_val; +} + + +McxStatus Fmu2SetVariableInitialize(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { + McxStatus status = RETURN_OK; Channel * channel = fmuVal->channel; if (channel && FALSE == channel->IsDefinedDuringInit(channel)) { @@ -601,17 +1019,24 @@ McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { return RETURN_OK; } + return Fmu2SetVariable(fmu, fmuVal); +} + +// TODO: move into fmu2value? +McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { + fmi2_status_t status = fmi2_status_ok; + ChannelValue * const chVal = &fmuVal->val; - ChannelType type = ChannelValueType(chVal); + ChannelType * type = ChannelValueType(chVal); - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: { fmi2_value_reference_t vr[] = {fmuVal->data->vr.scalar}; - status = fmi2_import_set_real(fmu->fmiImport, vr, 1, (const fmi2_real_t *) ChannelValueReference(chVal)); + status = fmi2_import_set_real(fmu->fmiImport, vr, 1, (const fmi2_real_t *) ChannelValueDataPointer(chVal)); - MCX_DEBUG_LOG("Set %s(%d)=%f", fmuVal->name, vr[0], *(double*)ChannelValueReference(chVal)); + MCX_DEBUG_LOG("Set %s(%d)=%f", fmuVal->name, vr[0], *(double*)ChannelValueDataPointer(chVal)); break; } @@ -619,9 +1044,9 @@ McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_set_integer(fmu->fmiImport, vr, 1, (const fmi2_integer_t *) ChannelValueReference(chVal)); + status = fmi2_import_set_integer(fmu->fmiImport, vr, 1, (const fmi2_integer_t *) ChannelValueDataPointer(chVal)); - MCX_DEBUG_LOG("Set %s(%d)=%d", fmuVal->name, vr[0], *(int*)ChannelValueReference(chVal)); + MCX_DEBUG_LOG("Set %s(%d)=%d", fmuVal->name, vr[0], *(int*)ChannelValueDataPointer(chVal)); break; } @@ -629,7 +1054,7 @@ McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_set_boolean(fmu->fmiImport, vr, 1, (const fmi2_boolean_t *) ChannelValueReference(chVal)); + status = fmi2_import_set_boolean(fmu->fmiImport, vr, 1, (const fmi2_boolean_t *) ChannelValueDataPointer(chVal)); break; } @@ -637,14 +1062,14 @@ McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_set_string(fmu->fmiImport, vr, 1, (fmi2_string_t *) ChannelValueReference(chVal)); + status = fmi2_import_set_string(fmu->fmiImport, vr, 1, (fmi2_string_t *) ChannelValueDataPointer(chVal)); break; } case CHANNEL_BINARY: case CHANNEL_BINARY_REFERENCE: { - binary_string * binary = (binary_string *) ChannelValueReference(chVal); + binary_string * binary = (binary_string *) ChannelValueDataPointer(chVal); fmi2_value_reference_t vrs [] = { fmuVal->data->vr.binary.lo , fmuVal->data->vr.binary.hi @@ -660,21 +1085,40 @@ McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { break; } + case CHANNEL_ARRAY: + { + fmi2_value_reference_t * vrs = fmuVal->data->vr.array.values; + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&fmuVal->val); + + size_t num = mcx_array_num_elements(a); + void * vals = a->data; + + if (ChannelTypeEq(a->type, &ChannelTypeDouble)) { + status = fmi2_import_set_real(fmu->fmiImport, vrs, num, vals); + } else if (ChannelTypeEq(a->type, &ChannelTypeInteger)) { + status = fmi2_import_set_integer(fmu->fmiImport, vrs, num, vals); + } else { + mcx_log(LOG_ERROR, "FMU: Unsupported array variable type: %s", ChannelTypeToString(a->type)); + return RETURN_ERROR; + } + + break; + } default: - mcx_log(LOG_ERROR, "FMU: Unknown variable type"); + mcx_log(LOG_ERROR, "FMU: Unknown variable type: %s", ChannelTypeToString(type)); return RETURN_ERROR; } if (fmi2_status_ok != status) { if (fmi2_status_error == status || fmi2_status_fatal == status) { fmu->runOk = fmi2_false; - mcx_log(LOG_ERROR, "FMU: Setting of variable %s failed", name); + mcx_log(LOG_ERROR, "FMU: Setting of variable %s failed", fmuVal->name); return RETURN_ERROR; } else { if (fmi2_status_warning == status) { - mcx_log(LOG_WARNING, "FMU: Setting of variable %s return with a warning", name); + mcx_log(LOG_WARNING, "FMU: Setting of variable %s return with a warning", fmuVal->name); } else if (fmi2_status_discard == status) { - mcx_log(LOG_WARNING, "FMU: Setting of variable %s discarded", name); + mcx_log(LOG_WARNING, "FMU: Setting of variable %s discarded", fmuVal->name); } } } @@ -688,15 +1132,43 @@ McxStatus Fmu2SetVariableArray(Fmu2CommonStruct * fmu, ObjectContainer * vals) { McxStatus retVal = RETURN_OK; + mcx_signal_handler_set_this_function(); + for (i = 0; i < numVars; i++) { Fmu2Value * const fmuVal = (Fmu2Value *) vals->At(vals, i); retVal = Fmu2SetVariable(fmu, fmuVal); if (RETURN_ERROR == retVal) { + mcx_signal_handler_unset_function(); + return RETURN_ERROR; + } + } + + mcx_signal_handler_unset_function(); + + return RETURN_OK; +} + +McxStatus Fmu2SetVariableArrayInitialize(Fmu2CommonStruct * fmu, ObjectContainer * vals) { + size_t i = 0; + size_t numVars = vals->Size(vals); + + McxStatus retVal = RETURN_OK; + + mcx_signal_handler_set_this_function(); + + for (i = 0; i < numVars; i++) { + Fmu2Value * const fmuVal = (Fmu2Value *) vals->At(vals, i); + + retVal = Fmu2SetVariableInitialize(fmu, fmuVal); + if (RETURN_ERROR == retVal) { + mcx_signal_handler_unset_function(); return RETURN_ERROR; } } + mcx_signal_handler_unset_function(); + return RETURN_OK; } @@ -706,16 +1178,16 @@ McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { char * const name = fmuVal->name; ChannelValue * const chVal = &fmuVal->val; - ChannelType type = ChannelValueType(chVal); + ChannelType * type = ChannelValueType(chVal); - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_get_real(fmu->fmiImport, vr, 1, (fmi2_real_t *) ChannelValueReference(chVal)); + status = fmi2_import_get_real(fmu->fmiImport, vr, 1, (fmi2_real_t *) ChannelValueDataPointer(chVal)); - MCX_DEBUG_LOG("Get %s(%d)=%f", fmuVal->name, vr[0], *(double*)ChannelValueReference(chVal)); + MCX_DEBUG_LOG("Get %s(%d)=%f", fmuVal->name, vr[0], *(double*)ChannelValueDataPointer(chVal)); break; } @@ -723,7 +1195,7 @@ McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_get_integer(fmu->fmiImport, vr, 1, (fmi2_integer_t *) ChannelValueReference(chVal)); + status = fmi2_import_get_integer(fmu->fmiImport, vr, 1, (fmi2_integer_t *) ChannelValueDataPointer(chVal)); break; } @@ -731,7 +1203,7 @@ McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { { fmi2_value_reference_t vr[] = { fmuVal->data->vr.scalar }; - status = fmi2_import_get_boolean(fmu->fmiImport, vr, 1, (fmi2_boolean_t *) ChannelValueReference(chVal)); + status = fmi2_import_get_boolean(fmu->fmiImport, vr, 1, (fmi2_boolean_t *) ChannelValueDataPointer(chVal)); break; } @@ -742,7 +1214,9 @@ McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { char * buffer = NULL; status = fmi2_import_get_string(fmu->fmiImport, vr, 1, (fmi2_string_t *) &buffer); - ChannelValueSetFromReference(chVal, &buffer); + if (RETURN_OK != ChannelValueSetFromReference(chVal, &buffer)) { + return RETURN_ERROR; + } break; } @@ -760,10 +1234,31 @@ McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal) { status = fmi2_import_get_integer(fmu->fmiImport, vrs, 3, vs); - binary.len = vs[2]; - binary.data = (char *) ((((long long)vs[1] & 0xffffffff) << 32) | (vs[0] & 0xffffffff)); + binary.len = vs[2]; + binary.data = (char *) ((((long long)vs[1] & 0xffffffff) << 32) | (vs[0] & 0xffffffff)); + + if (RETURN_OK != ChannelValueSetFromReference(chVal, &binary)) { + return RETURN_ERROR; + } + + break; + } + case CHANNEL_ARRAY: + { + fmi2_value_reference_t * vrs = fmuVal->data->vr.array.values; + mcx_array * a = (mcx_array *) ChannelValueDataPointer(&fmuVal->val); + + size_t num = mcx_array_num_elements(a); + void * vals = a->data; - ChannelValueSetFromReference(chVal, &binary); + if (ChannelTypeEq(a->type, &ChannelTypeDouble)) { + status = fmi2_import_get_real(fmu->fmiImport, vrs, num, vals); + } else if (ChannelTypeEq(a->type, &ChannelTypeInteger)) { + status = fmi2_import_get_integer(fmu->fmiImport, vrs, num, vals); + } else { + // TODO: log message + return RETURN_ERROR; + } break; } @@ -795,16 +1290,21 @@ McxStatus Fmu2GetVariableArray(Fmu2CommonStruct * fmu, ObjectContainer * vals) { McxStatus retVal = RETURN_OK; + mcx_signal_handler_set_this_function(); + for (i = 0; i < numVars; i++) { Fmu2Value * const fmuVal = (Fmu2Value *) vals->At(vals, i); retVal = Fmu2GetVariable(fmu, fmuVal); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "FMU: Getting of variable array failed at element %u", i); + mcx_signal_handler_unset_function(); return RETURN_ERROR; } } + mcx_signal_handler_unset_function(); + return RETURN_OK; } @@ -840,9 +1340,9 @@ McxStatus Fmi2RegisterLocalChannelsAtDatabus(ObjectContainer * vals, const char const char * name = val->name; fmi2_import_unit_t * unit = NULL; const char * unitName; - ChannelType type = ChannelValueType(&val->val); + ChannelType * type = ChannelValueType(&val->val); - if (CHANNEL_DOUBLE == type) { + if (ChannelTypeEq(&ChannelTypeDouble, type)) { unit = fmi2_import_get_real_variable_unit(fmi2_import_get_variable_as_real(val->data->data.scalar)); } if (unit) { @@ -857,7 +1357,7 @@ McxStatus Fmi2RegisterLocalChannelsAtDatabus(ObjectContainer * vals, const char return RETURN_ERROR; } - retVal = DatabusAddLocalChannel(db, name, buffer, unitName, ChannelValueReference(&val->val), ChannelValueType(&val->val)); + retVal = DatabusAddLocalChannel(db, name, buffer, unitName, ChannelValueDataPointer(&val->val), ChannelValueType(&val->val)); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "%s: Adding channel %s to databus failed", compName, name); return RETURN_ERROR; @@ -881,11 +1381,20 @@ ObjectContainer * Fmu2ValueScalarListFromVarList(fmi2_import_variable_list_t * v for (i = 0; i < num; i++) { fmi2_import_variable_t * var = fmi2_import_get_variable(vars, i); char * name = (char *)fmi2_import_get_variable_name(var); - ChannelType type = Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)); + ChannelType * type = Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)); + fmi2_import_unit_t * unit = NULL; + const char * unitName = NULL; + + if (ChannelTypeEq(&ChannelTypeDouble, type)) { + unit = fmi2_import_get_real_variable_unit(fmi2_import_get_variable_as_real(var)); + if (unit) { + unitName = fmi2_import_get_unit_name(unit); + } + } - Fmu2Value * value = Fmu2ValueScalarMake(name, var, NULL, NULL); + Fmu2Value * value = Fmu2ValueScalarMake(name, var, unitName, NULL); if (value) { - list->PushBack(list, (Object *) value); + list->PushBackNamed(list, (Object *) value, name); } else { list->DestroyObjects(list); object_destroy(list); @@ -914,7 +1423,7 @@ ObjectContainer * Fmu2ValueScalarListFromValVarList(ObjectContainer * vals, fmi2 for (i = 0; i < num; i++) { fmi2_import_variable_t * var = fmi2_import_get_variable(vars, i); char * name = (char *)fmi2_import_get_variable_name(var); - ChannelType type = Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)); + ChannelType * type = Fmi2TypeToChannelType(fmi2_import_get_variable_base_type(var)); ChannelValue * chVal = (ChannelValue *) vals->At(vals, i); Fmu2Value * value = NULL; @@ -1030,8 +1539,33 @@ void Fmu2MarkTunableParamsAsInputAsDiscrete(ObjectContainer * in) { if (fmi2_causality_enu_input != causality) { ChannelIn * in = (ChannelIn *) val->channel; - ChannelInfo * info = ((Channel*)in)->GetInfo((Channel*)in); - mcx_log(LOG_DEBUG, "Setting input \"%s\" as discrete", info->GetLogName(info)); + ChannelInfo * info = &((Channel*)in)->info; + mcx_log(LOG_DEBUG, "Setting input \"%s\" as discrete", ChannelInfoGetLogName(info)); + in->SetDiscrete(in); + } + } else if (val->data->type == FMU2_VALUE_ARRAY) { + size_t num_elems = 1; + size_t j = 0; + int all_tunable = TRUE; + + for (j = 0; j < val->data->data.array.numDims; j++) { + num_elems *= val->data->data.array.dims[j]; + } + + for (j = 0; j < num_elems; j++) { + fmi2_import_variable_t * var = val->data->data.array.values[j]; + fmi2_causality_enu_t causality = fmi2_import_get_causality(var); + + if (fmi2_causality_enu_input == causality) { + all_tunable = FALSE; + break; + } + } + + if (all_tunable) { + ChannelIn * in = (ChannelIn *) val->channel; + ChannelInfo * info = &((Channel *) in)->info; + mcx_log(LOG_DEBUG, "Setting input \"%s\" as discrete", ChannelInfoGetLogName(info)); in->SetDiscrete(in); } } diff --git a/src/fmu/common_fmu2.h b/src/fmu/common_fmu2.h index d4c2764..9624941 100644 --- a/src/fmu/common_fmu2.h +++ b/src/fmu/common_fmu2.h @@ -19,22 +19,29 @@ #include "reader/model/components/specific_data/FmuInput.h" #include "reader/model/parameters/ParametersInput.h" +#include "core/Dependency.h" + #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ -ChannelType Fmi2TypeToChannelType(fmi2_base_type_enu_t type); +ChannelType * Fmi2TypeToChannelType(fmi2_base_type_enu_t type); +const char * Fmi2TypeToString(fmi2_base_type_enu_t type); struct Fmu2CommonStruct; typedef struct Fmu2CommonStruct Fmu2CommonStruct; -ObjectContainer * Fmu2ReadParams(ParametersInput * input, fmi2_import_t * import, ObjectContainer * ignore); +McxStatus Fmu2ReadParams(ObjectContainer * params, ObjectContainer * arrayParams, ParametersInput * input, fmi2_import_t * import, ObjectContainer * ignore); + +McxStatus Fmu2SetDependencies(Fmu2CommonStruct * fmu2, Databus * db, Dependencies * deps, int init); // TODO: rename all variablearrays to something better +McxStatus Fmu2SetVariableArrayInitialize(Fmu2CommonStruct * fmu, ObjectContainer * vals); McxStatus Fmu2SetVariableArray(Fmu2CommonStruct * fmu, ObjectContainer * vals); McxStatus Fmu2GetVariableArray(Fmu2CommonStruct * fmu, ObjectContainer * vals); +McxStatus Fmu2SetVariableInitialize(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal); McxStatus Fmu2SetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal); McxStatus Fmu2GetVariable(Fmu2CommonStruct * fmu, Fmu2Value * fmuVal); @@ -52,6 +59,10 @@ struct Fmu2CommonStruct { ObjectContainer * params; ObjectContainer * initialValues; + ObjectContainer * arrayParams; // proxy views to array parameter elements (from params) (type: ArrayParameterProxy) + + ObjectContainer * connectedIn; + ObjectContainer * localValues; ObjectContainer * tunableParams; diff --git a/src/objects/ObjectContainer.c b/src/objects/ObjectContainer.c index 610d724..48304d1 100644 --- a/src/objects/ObjectContainer.c +++ b/src/objects/ObjectContainer.c @@ -23,6 +23,268 @@ typedef struct ObjectContainerElement { void * value; } ObjectContainerElement; +typedef struct { + int (*cmp)(const void *, const void *, void *); + void * arg; +} StrCmpCtx; + +static int ObjectContainerElementCmp(const void * first, const void * second, void * ctx) { + StrCmpCtx * data = (StrCmpCtx *)ctx; + + ObjectContainerElement * firstElement = (ObjectContainerElement *)first; + ObjectContainerElement * secondElement = (ObjectContainerElement *)second; + + return data->cmp(&(firstElement->object), &(secondElement->object), data->arg); +} + + + +static size_t ObjectListSize(const ObjectList * container) { + return container->size; +} + +static McxStatus ObjectListResize(ObjectList * container, size_t size) { + size_t oldSize = container->size; + size_t oldCapacity = container->capacity; + size_t i = 0; + + container->size = size; + if (oldCapacity < size) { + container->capacity = size + container->increment; + container->elements = (Object * *)mcx_realloc(container->elements, container->capacity * sizeof(Object *)); + if (!container->elements) { + mcx_log(LOG_ERROR, "ObjectList: Resize: Memory allocation failed"); + return RETURN_ERROR; + } + } + + // if we make the container larger, init new elements with NULL + for (i = oldSize; i < size; i++) { + container->elements[i] = NULL; + } + + return RETURN_OK; +} + + +static McxStatus ObjectListPushBack(ObjectList * container, Object * obj) { + McxStatus retVal = container->Resize(container, container->size + 1); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ObjectList: PushBack: Resize failed"); + return RETURN_ERROR; + } + container->elements[container->size - 1] = obj; + + return RETURN_OK; +} + +static McxStatus ObjectListSort(ObjectList * container, int (*cmp)(const void *, const void *, void *), void * arg) { + size_t i = 0; + size_t n = container->size; + + StrCmpCtx ctx; + ctx.cmp = cmp; + ctx.arg = arg; + + ObjectContainerElement * elements = mcx_malloc(n * sizeof(ObjectContainerElement)); + if (!elements) { + return RETURN_ERROR; + } + + for (i = 0; i < n; i++) { + elements[i].object = container->elements[i]; + } + + mcx_sort(elements, n, sizeof(ObjectContainerElement), ObjectContainerElementCmp, &ctx); + + for (i = 0; i < n; i++) { + container->elements[i] = elements[i].object; + } + + mcx_free(elements); + + return RETURN_OK; +} + +static Object * ObjectListAt(const ObjectList * container, size_t pos) { + if (pos < container->size) { + return container->elements[pos]; + } else { + return NULL; + } +} + +static McxStatus ObjectListSetAt(ObjectList * container, size_t pos, Object * obj) { + if (pos >= container->size) { + container->Resize(container, pos + 1); + } + + container->elements[pos] = obj; + + return RETURN_OK; +} + +static ObjectList * ObjectListCopy(ObjectList * container) { + McxStatus retVal; + size_t i = 0; + + ObjectList * newContainer = (ObjectList *) object_create(ObjectList); + + if (!newContainer) { + mcx_log(LOG_ERROR, "ObjectContainer: Copy: Memory allocation failed"); + return NULL; + } + + retVal = newContainer->Resize(newContainer, container->Size(container)); + if (RETURN_OK != retVal) { + object_destroy(newContainer); + return NULL; + } + + for (i = 0; i < newContainer->Size(newContainer); i++) { + newContainer->elements[i] = container->elements[i]; + } + + return newContainer; +} + +static McxStatus ObjectListAppend(ObjectList * container, ObjectList * appendee) { + size_t appendeeSize = 0; + size_t size = 0; + size_t i = 0; + + McxStatus retVal = RETURN_OK; + + if (!appendee) { + mcx_log(LOG_ERROR, "ObjectContainer: Append: Appendee missing"); + return RETURN_ERROR; + } + + appendeeSize = appendee->Size(appendee); + for (i = 0; i < appendeeSize; i++) { + retVal = container->PushBack(container, appendee->At(appendee, i)); + if (RETURN_OK != retVal) { + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +static Object ** ObjectListData(ObjectList * container) { + return container->elements; +} + +static void ObjectListAssignArray(ObjectList * container, size_t size, Object ** objs) { + container->size = size; + + if (container->elements) { + mcx_free(container->elements); + } + container->elements = objs; +} + +static void ObjectListDestroyObjects(ObjectList * container) { + size_t i = 0; + + for (i = 0; i < container->size; i++) { + Object * obj = container->At(container, i); + object_destroy(obj); + } + + container->Resize(container, 0); +} + +static int ObjectListContains(ObjectList * container, Object * obj) { + size_t i = 0; + for (i = 0; i < container->size; i++) { + if (container->At(container, i) == obj) { + return TRUE; + } + } + return FALSE; +} + +static ObjectList * ObjectListFilter(ObjectList * container, fObjectPredicate predicate) { + ObjectList * filtered = (ObjectList *) object_create(ObjectList); + + size_t i = 0; + + for (i = 0; i < container->size; i++) { + Object * obj = container->At(container, i); + if (predicate(obj)) { + filtered->PushBack(filtered, obj); + } + } + + return filtered; +} + +static ObjectList * ObjectListFilterCtx(ObjectList * container, fObjectPredicateCtx predicate, void * ctx) { + ObjectList * filtered = (ObjectList *) object_create(ObjectList); + + size_t i = 0; + + for (i = 0; i < container->size; i++) { + Object * obj = container->At(container, i); + if (predicate(obj, ctx)) { + filtered->PushBack(filtered, obj); + } + } + + return filtered; +} + +static void ObjectListIterate(ObjectList * container, fObjectIter iter) { + size_t i = 0; + for (i = 0; i < container->size; i++) { + Object * obj = container->At(container, i); + iter(obj); + } +} + +static void ObjectListDestructor(ObjectList * container) { + if (container->elements) { + mcx_free(container->elements); + } +} + +static ObjectList * ObjectListCreate(ObjectList * container) { + container->Size = ObjectListSize; + container->Resize = ObjectListResize; + container->PushBack = ObjectListPushBack; + container->At = ObjectListAt; + container->SetAt = ObjectListSetAt; + container->Copy = ObjectListCopy; + container->Append = ObjectListAppend; + container->Data = ObjectListData; + container->AssignArray = ObjectListAssignArray; + + container->DestroyObjects = ObjectListDestroyObjects; + + container->Contains = ObjectListContains; + container->Filter = ObjectListFilter; + container->FilterCtx = ObjectListFilterCtx; + + container->Iterate = ObjectListIterate; + container->Sort = ObjectListSort; + + container->elements = NULL; + container->size = 0; + container->capacity = 0; + container->increment = 10; + + return container; +} + +OBJECT_CLASS(ObjectList, Object); + + + + + + +///////////////// static size_t ObjectContainerSize(const ObjectContainer * container) { return container->size; @@ -30,14 +292,17 @@ static size_t ObjectContainerSize(const ObjectContainer * container) { static McxStatus ObjectContainerResize(ObjectContainer * container, size_t size) { size_t oldSize = container->size; + size_t oldCapacity = container->capacity; size_t i = 0; - container->size = size; - container->elements = (Object * *) mcx_realloc(container->elements, - size * sizeof(Object *)); - if (!container->elements && 0 < size) { - mcx_log(LOG_ERROR, "ObjectContainer: Resize: Memory allocation failed"); - return RETURN_ERROR; + container->size = size; + if (oldCapacity < size) { + container->capacity = size + container->increment; + container->elements = (Object * *)mcx_realloc(container->elements, container->capacity * sizeof(Object *)); + if (!container->elements) { + mcx_log(LOG_ERROR, "ObjectContainer: Resize: Memory allocation failed"); + return RETURN_ERROR; + } } /* if we make the container larger, init new elements with NULL */ @@ -49,14 +314,11 @@ static McxStatus ObjectContainerResize(ObjectContainer * container, size_t size) } static McxStatus ObjectContainerPushBack(ObjectContainer * container, Object * obj) { - container->size += 1; - container->elements = (Object * *) mcx_realloc(container->elements, - container->size * sizeof(Object *)); - if (!container->elements) { - mcx_log(LOG_ERROR, "ObjectContainer: PushBack: Memory allocation failed"); + McxStatus retVal = container->Resize(container, container->size + 1); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "ObjectContainer: PushBack: Resize failed"); return RETURN_ERROR; } - container->elements[container->size - 1] = obj; return StringContainerResize(container->strToIdx, container->size); @@ -77,19 +339,6 @@ static McxStatus ObjectContainerPushBackNamed(ObjectContainer * container, Obje return RETURN_OK; } -typedef struct { - int (*cmp)(const void *, const void *, void *); - void * arg; -} StrCmpCtx; - -static int ObjectContainerElementCmp(const void * first, const void * second, void * ctx) { - StrCmpCtx * data = (StrCmpCtx *)ctx; - - ObjectContainerElement * firstElement = (ObjectContainerElement *) first; - ObjectContainerElement * secondElement = (ObjectContainerElement *) second; - - return data->cmp(&(firstElement->object), &(secondElement->object), data->arg); -} static McxStatus ObjectContainerSort(ObjectContainer * container, int (*cmp)(const void *, const void *, void *), void * arg) { size_t i = 0; @@ -145,7 +394,7 @@ static ObjectContainer * ObjectContainerCopy(ObjectContainer * container) { McxStatus retVal; size_t i = 0; - ObjectContainer * newContainer = (ObjectContainer *) object_create(ObjectContainer); + ObjectContainer * newContainer = (ObjectContainer *)object_create(ObjectContainer); if (!newContainer) { mcx_log(LOG_ERROR, "ObjectContainer: Copy: Memory allocation failed"); @@ -161,7 +410,7 @@ static ObjectContainer * ObjectContainerCopy(ObjectContainer * container) { for (i = 0; i < newContainer->Size(newContainer); i++) { newContainer->elements[i] = container->elements[i]; retVal = StringContainerSetString(newContainer->strToIdx, i, - StringContainerGetString(container->strToIdx, i)); + StringContainerGetString(container->strToIdx, i)); if (retVal != RETURN_OK) { return NULL; } @@ -170,9 +419,7 @@ static ObjectContainer * ObjectContainerCopy(ObjectContainer * container) { return newContainer; } -static McxStatus ObjectContainerAppend( - ObjectContainer * container, - ObjectContainer * appendee) { +static McxStatus ObjectContainerAppend(ObjectContainer * container, ObjectContainer * appendee) { size_t appendeeSize = 0; size_t size = 0; size_t i = 0; @@ -192,7 +439,7 @@ static McxStatus ObjectContainerAppend( } retVal = container->SetElementName(container, container->Size(container) - 1, - appendee->GetElementName(appendee, i)); + appendee->GetElementName(appendee, i)); if (RETURN_OK != retVal) { return RETURN_ERROR; } @@ -205,9 +452,7 @@ static Object ** ObjectContainerData(ObjectContainer * container) { return container->elements; } -static void ObjectContainerAssignArray(ObjectContainer * container, - size_t size, - Object ** objs) { +static void ObjectContainerAssignArray(ObjectContainer * container, size_t size, Object ** objs) { container->size = size; if (container->elements) { @@ -228,33 +473,30 @@ static void ObjectContainerDestroyObjects(ObjectContainer * container) { } static McxStatus ObjectContainerSetElementName(ObjectContainer * container, - size_t pos, - const char * name) { + size_t pos, + const char * name) { if (pos >= container->size) { - mcx_log(LOG_ERROR, "ObjectContainer: SetElementName: Position %u out of bounds, max is %u", pos, container->size); + mcx_log(LOG_ERROR, "ObjectContainer: SetElementName: Position %zu out of bounds, max is %zu", pos, container->size); return RETURN_ERROR; } return StringContainerSetString(container->strToIdx, pos, name); } -static const char * ObjectContainerGetElementName(ObjectContainer * container, - size_t pos) { +static const char * ObjectContainerGetElementName(ObjectContainer * container, size_t pos) { return StringContainerGetString(container->strToIdx, pos); } -static int ObjectContainerGetNameIndex(ObjectContainer * container, - const char * name) { +static int ObjectContainerGetNameIndex(ObjectContainer * container, const char * name) { return StringContainerGetIndex(container->strToIdx, name); } static Object * ObjectContainerGetByName(const ObjectContainer * container, const char * name) { return container->At(container, container->GetNameIndex((ObjectContainer *)container, name)); } -static int ObjectContainerContains(ObjectContainer * container, - Object * obj) { +static int ObjectContainerContains(ObjectContainer * container, Object * obj) { size_t i = 0; - for (i = 0; i < container->Size(container); i++) { + for (i = 0; i < container->size; i++) { if (container->At(container, i) == obj) { return TRUE; } @@ -263,11 +505,10 @@ static int ObjectContainerContains(ObjectContainer * container, } static ObjectContainer * ObjectContainerFilter(ObjectContainer * container, fObjectPredicate predicate) { - ObjectContainer * filtered = (ObjectContainer *) object_create(ObjectContainer); - + ObjectContainer * filtered = (ObjectContainer *)object_create(ObjectContainer); size_t i = 0; - for (i = 0; i < container->Size(container); i++) { + for (i = 0; i < container->size; i++) { Object * obj = container->At(container, i); if (predicate(obj)) { filtered->PushBack(filtered, obj); @@ -278,14 +519,14 @@ static ObjectContainer * ObjectContainerFilter(ObjectContainer * container, fObj } static ObjectContainer * ObjectContainerFilterCtx(ObjectContainer * container, fObjectPredicateCtx predicate, void * ctx) { - ObjectContainer * filtered = (ObjectContainer *) object_create(ObjectContainer); + ObjectContainer * filtered = (ObjectContainer *)object_create(ObjectContainer); size_t i = 0; - for (i = 0; i < container->Size(container); i++) { + for (i = 0; i < container->size; i++) { Object * obj = container->At(container, i); if (predicate(obj, ctx)) { - filtered->PushBack(filtered, obj); + filtered->PushBackNamed(filtered, obj, container->GetElementName(container, i)); } } @@ -294,7 +535,7 @@ static ObjectContainer * ObjectContainerFilterCtx(ObjectContainer * container, f static void ObjectContainerIterate(ObjectContainer * container, fObjectIter iter) { size_t i = 0; - for (i = 0; i < container->Size(container); i++) { + for (i = 0; i < container->size; i++) { Object * obj = container->At(container, i); iter(obj); } @@ -337,8 +578,10 @@ static ObjectContainer * ObjectContainerCreate(ObjectContainer * container) { container->elements = NULL; container->size = 0; + container->capacity = 0; + container->increment = 10; - container->strToIdx = (StringContainer *) mcx_malloc(sizeof(StringContainer)); + container->strToIdx = (StringContainer *)mcx_malloc(sizeof(StringContainer)); if (!container->strToIdx) { return NULL; } StringContainerInit(container->strToIdx, 0); @@ -348,6 +591,7 @@ static ObjectContainer * ObjectContainerCreate(ObjectContainer * container) { OBJECT_CLASS(ObjectContainer, Object); + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/objects/ObjectContainer.h b/src/objects/ObjectContainer.h index a9fbf00..30c948c 100644 --- a/src/objects/ObjectContainer.h +++ b/src/objects/ObjectContainer.h @@ -17,44 +17,86 @@ extern "C" { #endif /* __cplusplus */ -typedef struct ObjectContainer ObjectContainer; -struct StringContainer; +typedef struct ObjectList ObjectList; typedef int (* fObjectPredicate)(Object * obj); typedef int (* fObjectPredicateCtx)(Object * obj, void * ctx); typedef void (* fObjectIter)(Object * obj); -typedef size_t (* fObjectContainerSize)(const ObjectContainer * container); -typedef McxStatus (* fObjectContainerResize)(ObjectContainer * container, size_t size); -typedef McxStatus (* fObjectContainerPushBack)(ObjectContainer * container, Object * obj); -typedef McxStatus (* fObjectContainerPushBackNamed)(ObjectContainer * container, Object * obj, const char * name); -typedef Object * (* fObjectContainerAt)(const ObjectContainer * container, size_t pos); -typedef Object * (* fObjectContainerGetByName)(const ObjectContainer * container, const char * name); -typedef McxStatus (* fObjectContainerSetAt)(ObjectContainer * container, size_t pos, Object * obj); -typedef ObjectContainer * (* fObjectContainerCopy)(ObjectContainer * container); -typedef McxStatus (* fObjectContainerAppend)( - ObjectContainer * container, - ObjectContainer * appendee); -typedef Object ** (* fObjectContainerData)(ObjectContainer * container); -typedef void (* fObjectContainerAssignArray)(ObjectContainer * container, - size_t size, - Object ** objs); -typedef void (* fObjectContainerDestroyObjects)(ObjectContainer * container); -typedef McxStatus (* fObjectContainerSetElementName)(ObjectContainer * container, - size_t pos, - const char * name); -typedef const char * (* fObjectContainerGetElementName)(ObjectContainer * container, size_t pos); -typedef int (* fObjectContainerGetNameIndex)(ObjectContainer * container, - const char * name); -typedef int (* fObjectContainerContains)(ObjectContainer * container, - Object * obj); -typedef ObjectContainer * (* fObjectContainerFilter)(ObjectContainer * container, fObjectPredicate predicate); -typedef ObjectContainer * (* fObjectContainerFilterCtx)(ObjectContainer * container, fObjectPredicateCtx predicate, void * ctx); - -typedef McxStatus (*fObjectContainerSort)(ObjectContainer * container, int (*cmp)(const void *, const void *, void *), void * arg); - - -typedef void (* fObjectContainerIterate)(ObjectContainer * container, fObjectIter iter); +typedef size_t(*fObjectListSize)(const ObjectList * container); +typedef McxStatus(*fObjectListResize)(ObjectList * container, size_t size); +typedef McxStatus(*fObjectListPushBack)(ObjectList * container, Object * obj); +typedef Object * (*fObjectListAt)(const ObjectList * container, size_t pos); +typedef McxStatus(*fObjectListSetAt)(ObjectList * container, size_t pos, Object * obj); +typedef ObjectList * (*fObjectListCopy)(ObjectList * container); +typedef McxStatus(*fObjectListAppend)(ObjectList * container, ObjectList * appendee); +typedef Object ** (*fObjectListData)(ObjectList * container); +typedef void (*fObjectListAssignArray)(ObjectList * container, size_t size, Object** objs); +typedef void (*fObjectListDestroyObjects)(ObjectList * container); +typedef int (*fObjectListContains)(ObjectList * container, Object * obj); +typedef ObjectList * (*fObjectListFilter)(ObjectList * container, fObjectPredicate predicate); +typedef ObjectList * (*fObjectListFilterCtx)(ObjectList * container, fObjectPredicateCtx predicate, void * ctx); + +typedef McxStatus(*fObjectListSort)(ObjectList * container, int (*cmp)(const void *, const void *, void *), void * arg); +typedef void (*fObjectListIterate)(ObjectList * container, fObjectIter iter); + +extern const struct ObjectClass _ObjectList; + +typedef struct ObjectList { + Object _; /* super class first */ + + fObjectListSize Size; + fObjectListResize Resize; + fObjectListPushBack PushBack; + fObjectListAt At; + fObjectListSetAt SetAt; + fObjectListCopy Copy; + fObjectListAppend Append; + fObjectListData Data; + fObjectListAssignArray AssignArray; + + fObjectListDestroyObjects DestroyObjects; + + fObjectListContains Contains; + fObjectListFilter Filter; + fObjectListFilterCtx FilterCtx; + + fObjectListSort Sort; + fObjectListIterate Iterate; + + struct Object ** elements; + size_t size; + size_t capacity; + size_t increment; +} ObjectList; + +typedef struct ObjectContainer ObjectContainer; +struct StringContainer; + +typedef size_t(*fObjectContainerSize)(const ObjectContainer * container); +typedef McxStatus(*fObjectContainerResize)(ObjectContainer * container, size_t size); +typedef McxStatus(*fObjectContainerPushBack)(ObjectContainer * container, Object * obj); +typedef Object * (*fObjectContainerAt)(const ObjectContainer * container, size_t pos); +typedef McxStatus(*fObjectContainerSetAt)(ObjectContainer * container, size_t pos, Object * obj); +typedef ObjectContainer * (*fObjectContainerCopy)(ObjectContainer * container); +typedef McxStatus(*fObjectContainerAppend)(ObjectContainer * container, ObjectContainer * appendee); +typedef Object ** (*fObjectContainerData)(ObjectContainer * container); +typedef void (*fObjectContainerAssignArray)(ObjectContainer * container, size_t size, Object** objs); +typedef void (*fObjectContainerDestroyObjects)(ObjectContainer * container); +typedef int (*fObjectContainerContains)(ObjectContainer * container, Object * obj); +typedef ObjectContainer * (*fObjectContainerFilter)(ObjectContainer * container, fObjectPredicate predicate); +typedef ObjectContainer * (*fObjectContainerFilterCtx)(ObjectContainer * container, fObjectPredicateCtx predicate, void * ctx); + +typedef McxStatus(*fObjectContainerSort)(ObjectContainer * container, int (*cmp)(const void *, const void *, void *), void * arg); +typedef void (*fObjectContainerIterate)(ObjectContainer * container, fObjectIter iter); + + +typedef McxStatus(*fObjectContainerSetElementName)(ObjectContainer * container, size_t pos, const char * name); +typedef int (*fObjectContainerGetNameIndex)(ObjectContainer * container, const char * name); +typedef McxStatus(*fObjectContainerPushBackNamed)(ObjectContainer * container, Object * obj, const char * name); +typedef Object * (*fObjectContainerGetByName)(const ObjectContainer * container, const char * name); +typedef const char * (*fObjectContainerGetElementName)(ObjectContainer * container, size_t pos); + extern const struct ObjectClass _ObjectContainer; @@ -89,6 +131,8 @@ typedef struct ObjectContainer { struct Object ** elements; size_t size; + size_t capacity; + size_t increment; struct StringContainer * strToIdx; } ObjectContainer; diff --git a/src/objects/Vector.c b/src/objects/Vector.c new file mode 100644 index 0000000..49915e3 --- /dev/null +++ b/src/objects/Vector.c @@ -0,0 +1,290 @@ +/******************************************************************************** + * Copyright (c) 2022 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include "objects/Vector.h" + +#include "common/logging.h" +#include "common/memory.h" + +#include + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +static size_t VectorSize(const Vector * vector) { + return vector->size_; +} + +static void * VectorAt(const Vector * vector, size_t idx) { + if (idx < vector->size_) { + char * it = (char *) vector->elements_; + return (void *) (it + idx * vector->elemSize_); + } else { + return NULL; + } +} + +static McxStatus VectorResize(Vector * vector, size_t size) { + size_t oldSize = vector->size_; + size_t oldCapacity = vector->capacity_; + size_t i = 0; + McxStatus retVal = RETURN_OK; + + vector->size_ = size; + if (oldCapacity < size) { + vector->capacity_ = size + vector->increment_; + vector->elements_ = mcx_realloc(vector->elements_, vector->capacity_ * vector->elemSize_); + if (!vector->elements_) { + mcx_log(LOG_ERROR, "Vector: Resize: Memory allocation failed"); + return RETURN_ERROR; + } + } + + // if we make the vector larger, init new elements + if (vector->elemInitializer_) { + for (i = oldSize; i < size; ++i) { + retVal = vector->elemInitializer_(vector->At(vector, i)); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Vector: Resize: Element initialization failed"); + return RETURN_ERROR; + } + } + } + + return RETURN_OK; +} + +static McxStatus VectorSetAt(Vector * vector, size_t pos, void * elem) { + McxStatus retVal = RETURN_OK; + + if (pos >= vector->size_) { + VectorResize(vector, pos + 1); + } + + if (vector->elemSetter_) { + retVal = vector->elemSetter_(vector->At(vector, pos), elem); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Vector: SetAt: Element setting failed"); + return RETURN_ERROR; + } + } else { + memcpy(vector->At(vector, pos), elem, vector->elemSize_); + } + + return RETURN_OK; +} + +static size_t VectorFindIdx(const Vector * vector, fVectorElemPredicate pred, void * args) { + size_t i = 0; + char * it = NULL; + + for (i = 0, it = (char*) vector->elements_; i < vector->size_; ++i, it += vector->elemSize_) { + if (pred((void *) it, args)) { + return i; + } + } + + return SIZE_T_ERROR; +} + +static void * VectorFind(const Vector * vector, fVectorElemPredicate pred, void * args) { + size_t idx = vector->FindIdx(vector, pred, args); + + if (idx == SIZE_T_ERROR) { + return NULL; + } + + return vector->At(vector, idx); +} + +static McxStatus VectorReserve(Vector * vector, size_t newCapacity) { + size_t oldCapacity = vector->capacity_; + + if (oldCapacity < newCapacity) { + vector->capacity_ = oldCapacity + newCapacity; + vector->elements_ = mcx_realloc(vector->elements_, vector->capacity_ * vector->elemSize_); + if (!vector->elements_) { + mcx_log(LOG_ERROR, "Vector: Reserve: Memory allocation failed"); + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +static McxStatus VectorPushBack(Vector * vector, void * elem) { + McxStatus retVal = VectorResize(vector, vector->size_ + 1); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Vector: PushBack: Resize failed"); + return RETURN_ERROR; + } + + if (vector->elemSetter_) { + retVal = vector->elemSetter_(vector->At(vector, vector->size_ - 1), elem); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Vector: PushBack: Element setting failed"); + return RETURN_ERROR; + } + } else { + memcpy(vector->At(vector, vector->size_ - 1), elem, vector->elemSize_); + } + + return RETURN_OK; +} + +static McxStatus VectorAppend(Vector * vector, Vector * appendee) { + size_t appendeeSize = 0; + size_t i = 0; + + McxStatus retVal = RETURN_OK; + + if (!appendee) { + mcx_log(LOG_ERROR, "Vector: Append: Appendee missing"); + return RETURN_ERROR; + } + + appendeeSize = appendee->Size(appendee); + retVal = VectorReserve(vector, vector->size_ + appendeeSize); + if (RETURN_ERROR == retVal) { + return RETURN_ERROR; + } + + for (i = 0; i < appendeeSize; i++) { + retVal = vector->PushBack(vector, appendee->At(appendee, i)); + if (RETURN_OK != retVal) { + return RETURN_ERROR; + } + } + + return RETURN_OK; +} + +static Vector * VectorFilter(const Vector * vector, fVectorElemPredicate predicate, void * args) { + Vector * filtered = (Vector *) object_create(Vector); + size_t i = 0; + char * it = NULL; + + if (!filtered) { + mcx_log(LOG_ERROR, "Vector: Filter: Not enough memory"); + return NULL; + } + + filtered->Setup(filtered, vector->elemSize_, vector->elemInitializer_, vector->elemSetter_, vector->elemDestructor_); + + for (i = 0, it = (char*)vector->elements_; i < vector->size_; ++i, it += vector->elemSize_) { + if (predicate((void *) it, args)) { + filtered->PushBack(filtered, (void *) it); + } + } + + return filtered; +} + +static Vector * VectorFilterRef(const Vector * vector, fVectorElemPredicate predicate, void * args) { + Vector * filtered = (Vector *) object_create(Vector); + size_t i = 0; + char * it = NULL; + + if (!filtered) { + mcx_log(LOG_ERROR, "Vector: FilterReferences: Not enough memory"); + return NULL; + } + + filtered->Setup(filtered, sizeof(void *), NULL, NULL, NULL); + + for (i = 0, it = (char*)vector->elements_; i < vector->size_; ++i, it += vector->elemSize_) { + if (predicate((void *) it, args)) { + filtered->PushBack(filtered, (void *) &it); + } + } + + return filtered; +} + + +static int VectorContains(Vector * vector, void * elem) { + size_t i = 0; + + for (i = 0; i < vector->size_; i++) { + if (vector->At(vector, i) == elem) { + return 1; + } + } + + return 0; +} + +static void VectorSetup( + Vector * vector, + size_t elemSize, + fVectorElemInitializer elemInitializer, + fVectorElemSetter elemSetter, + fVectorElemDestructor elemDestructor) +{ + vector->elemSize_ = elemSize; + vector->elemInitializer_ = elemInitializer; + vector->elemSetter_ = elemSetter; + vector->elemDestructor_ = elemDestructor; +} + +static void VectorDestructor(Vector * vector) { + if (vector->elements_) { + if (vector->elemDestructor_) { + size_t i = 0; + char * it = (char *)vector->elements_; + + for (i = 0; i < vector->size_; ++i) { + vector->elemDestructor_((void *) (it + i * vector->elemSize_)); + } + } + + mcx_free(vector->elements_); + } +} + +static Vector * VectorCreate(Vector * vector) { + vector->Setup = VectorSetup; + vector->Size = VectorSize; + vector->At = VectorAt; + vector->SetAt = VectorSetAt; + vector->Reserve = VectorReserve; + vector->PushBack = VectorPushBack; + vector->Append = VectorAppend; + vector->Filter = VectorFilter; + vector->FilterRef = VectorFilterRef; + vector->Find = VectorFind; + vector->FindIdx = VectorFindIdx; + vector->Contains = VectorContains; + + vector->elements_ = NULL; + + vector->elemSize_ = 0; + vector->elemDestructor_ = NULL; + vector->elemInitializer_ = NULL; + vector->elemSetter_ = NULL; + + vector->size_ = 0; + vector->capacity_ = 0; + vector->increment_ = 10; + + return vector; +} + +OBJECT_CLASS(Vector, Object); + + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ \ No newline at end of file diff --git a/src/objects/Vector.h b/src/objects/Vector.h new file mode 100644 index 0000000..5572555 --- /dev/null +++ b/src/objects/Vector.h @@ -0,0 +1,82 @@ +/******************************************************************************** + * Copyright (c) 2022 AVL List GmbH and others + * + * This program and the accompanying materials are made available under the + * terms of the Apache Software License 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef MCX_OBJECTS_VECTOR_H +#define MCX_OBJECTS_VECTOR_H + +#include "common/status.h" +#include "objects/Object.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + + +typedef struct Vector Vector; + +typedef McxStatus (*fVectorElemInitializer)(void * elem); +typedef McxStatus (*fVectorElemSetter)(void * elem, void * other); +typedef void (*fVectorElemDestructor)(void * elem); +typedef void (*fVectorSetup)(Vector * vector, size_t elemSize, fVectorElemInitializer elemInitializer, + fVectorElemSetter elemSetter, fVectorElemDestructor elemDestructor); +typedef size_t (*fVectorSize)(const Vector * vector); +typedef int (*fVectorElemPredicate)(void * elem, void * args); +typedef void * (*fVectorFind)(const Vector * vector, fVectorElemPredicate pred, void * args); +typedef size_t (*fVectorFindIdx)(const Vector * vector, fVectorElemPredicate pred, void * args); +typedef void * (*fVectorAt)(const Vector * vector, size_t idx); +typedef McxStatus (*fVectorSetAt)(Vector * vector, size_t pos, void * elem); +typedef McxStatus (*fVectorReserve)(Vector * vector, size_t newCapacity); +typedef McxStatus (*fVectorPushBack)(Vector * vector, void * elem); +typedef McxStatus (*fVectorAppend)(Vector * vector, Vector * appendee); +typedef Vector * (*fVectorFilter)(const Vector * vector, fVectorElemPredicate predicate, void * args); +typedef Vector * (*fVectorFilterRef)(const Vector * vector, fVectorElemPredicate predicate, void * args); +typedef int (*fVectorContains)(Vector * vector, void * elem); + +extern const struct ObjectClass _Vector; + + +typedef struct Vector { + Object _; + + fVectorSetup Setup; + fVectorSize Size; + fVectorAt At; + fVectorSetAt SetAt; + fVectorReserve Reserve; + fVectorPushBack PushBack; + fVectorAppend Append; + fVectorFilter Filter; + fVectorFilterRef FilterRef; + fVectorFind Find; + fVectorFindIdx FindIdx; + fVectorContains Contains; + + + void * elements_; + + size_t elemSize_; + fVectorElemInitializer elemInitializer_; + fVectorElemSetter elemSetter_; + fVectorElemDestructor elemDestructor_; + + size_t size_; + size_t capacity_; + size_t increment_; +} Vector; + + + +#ifdef __cplusplus +} /* closing brace for extern "C" */ +#endif /* __cplusplus */ + +#endif /* MCX_OBJECTS_VECTOR_H */ \ No newline at end of file diff --git a/src/reader/EnumMapping.c b/src/reader/EnumMapping.c index dc11b01..be08854 100644 --- a/src/reader/EnumMapping.c +++ b/src/reader/EnumMapping.c @@ -20,7 +20,7 @@ extern "C" { MapStringInt storeLevelMapping[] = { {"none", STORE_NONE}, - {"micro", STORE_COUPLING}, // fall back to COUPLING for now + {"micro", STORE_MICRO}, {"coupling", STORE_COUPLING}, {"synchronization", STORE_SYNCHRONIZATION}, {NULL, 0} diff --git a/src/reader/model/components/specific_data/ConstantInput.c b/src/reader/model/components/specific_data/ConstantInput.c index c14a354..a5b5559 100644 --- a/src/reader/model/components/specific_data/ConstantInput.c +++ b/src/reader/model/components/specific_data/ConstantInput.c @@ -19,7 +19,7 @@ static void ScalarConstantValueInputDestructor(ScalarConstantValueInput * input) } static ScalarConstantValueInput * ScalarConstantValueInputCreate(ScalarConstantValueInput * input) { - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; input->value.d = 0.0; return input; @@ -32,7 +32,7 @@ static void ArrayConstantValueInputDestructor(ArrayConstantValueInput * input) { } static ArrayConstantValueInput * ArrayConstantValueInputCreate(ArrayConstantValueInput * input) { - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; input->numValues = 0; input->values = NULL; diff --git a/src/reader/model/components/specific_data/ConstantInput.h b/src/reader/model/components/specific_data/ConstantInput.h index 5a38b5b..6896fbd 100644 --- a/src/reader/model/components/specific_data/ConstantInput.h +++ b/src/reader/model/components/specific_data/ConstantInput.h @@ -25,7 +25,7 @@ extern const ObjectClass _ScalarConstantValueInput; typedef struct ScalarConstantValueInput { InputElement _; - ChannelType type; + ChannelType * type; ChannelValueData value; } ScalarConstantValueInput; @@ -34,7 +34,7 @@ extern const ObjectClass _ArrayConstantValueInput; typedef struct ArrayConstantValueInput { InputElement _; - ChannelType type; + ChannelType * type; size_t numValues; void * values; diff --git a/src/reader/model/parameters/ArrayParameterInput.c b/src/reader/model/parameters/ArrayParameterInput.c index 203c426..b12419a 100644 --- a/src/reader/model/parameters/ArrayParameterInput.c +++ b/src/reader/model/parameters/ArrayParameterInput.c @@ -29,7 +29,7 @@ static void ArrayParameterInputDestructor(ArrayParameterInput * input) { } if (input->values) { - if (input->type == CHANNEL_STRING) { + if (ChannelTypeEq(input->type, &ChannelTypeString)) { size_t i = 0; for (i = 0; i < input->numValues; i++) { @@ -47,7 +47,7 @@ static ArrayParameterInput * ArrayParameterInputCreate(ArrayParameterInput * inp input->numDims = 0; input->dims = NULL; - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; input->numValues = 0; input->values = NULL; diff --git a/src/reader/model/parameters/ArrayParameterInput.h b/src/reader/model/parameters/ArrayParameterInput.h index 8c45675..cf0a0dc 100644 --- a/src/reader/model/parameters/ArrayParameterInput.h +++ b/src/reader/model/parameters/ArrayParameterInput.h @@ -29,7 +29,7 @@ typedef struct ArrayParameterInput { size_t numDims; ArrayParameterDimensionInput ** dims; - ChannelType type; + ChannelType * type; size_t numValues; void * values; diff --git a/src/reader/model/parameters/ScalarParameterInput.c b/src/reader/model/parameters/ScalarParameterInput.c index 6b217c6..1244cda 100644 --- a/src/reader/model/parameters/ScalarParameterInput.c +++ b/src/reader/model/parameters/ScalarParameterInput.c @@ -19,7 +19,7 @@ static void ScalarParameterInputDestructor(ScalarParameterInput * input) { if (input->unit) { mcx_free(input->unit); } - if (input->type == CHANNEL_STRING && input->value.defined && input->value.value.s) { + if (ChannelTypeEq(input->type, &ChannelTypeString) && input->value.defined && input->value.value.s) { mcx_free(input->value.value.s); } } @@ -27,7 +27,7 @@ static void ScalarParameterInputDestructor(ScalarParameterInput * input) { static ScalarParameterInput * ScalarParameterInputCreate(ScalarParameterInput * input) { input->name = NULL; - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; OPTIONAL_UNSET(input->value); input->unit = NULL; diff --git a/src/reader/model/parameters/ScalarParameterInput.h b/src/reader/model/parameters/ScalarParameterInput.h index b52d1ae..5be3ac0 100644 --- a/src/reader/model/parameters/ScalarParameterInput.h +++ b/src/reader/model/parameters/ScalarParameterInput.h @@ -24,7 +24,7 @@ typedef struct ScalarParameterInput { char * name; - ChannelType type; + ChannelType * type; OPTIONAL_VALUE(ChannelValueData) value; char * unit; diff --git a/src/reader/model/ports/ScalarPortInput.c b/src/reader/model/ports/ScalarPortInput.c index 50be17d..13e309b 100644 --- a/src/reader/model/ports/ScalarPortInput.c +++ b/src/reader/model/ports/ScalarPortInput.c @@ -81,37 +81,49 @@ static McxStatus CopyFrom(ScalarPortInput * self, ScalarPortInput * src) { self->min.defined = src->min.defined; if (self->min.defined) { ChannelValueDataInit(&self->min.value, self->type); - ChannelValueDataSetFromReference(&self->min.value, self->type, &src->min.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->min.value, self->type, &src->min.value)) { + return RETURN_ERROR; + } } self->max.defined = src->max.defined; if (self->max.defined) { ChannelValueDataInit(&self->max.value, self->type); - ChannelValueDataSetFromReference(&self->max.value, self->type, &src->max.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->max.value, self->type, &src->max.value)) { + return RETURN_ERROR; + } } self->scale.defined = src->scale.defined; if (self->scale.defined) { ChannelValueDataInit(&self->scale.value, self->type); - ChannelValueDataSetFromReference(&self->scale.value, self->type, &src->scale.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->scale.value, self->type, &src->scale.value)) { + return RETURN_ERROR; + } } self->offset.defined = src->offset.defined; if (self->offset.defined) { ChannelValueDataInit(&self->offset.value, self->type); - ChannelValueDataSetFromReference(&self->offset.value, self->type, &src->offset.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->offset.value, self->type, &src->offset.value)) { + return RETURN_ERROR; + } } self->default_.defined = src->default_.defined; if (self->default_.defined) { ChannelValueDataInit(&self->default_.value, self->type); - ChannelValueDataSetFromReference(&self->default_.value, self->type, &src->default_.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->default_.value, self->type, &src->default_.value)) { + return RETURN_ERROR; + } } self->initial.defined = src->initial.defined; if (self->initial.defined) { ChannelValueDataInit(&self->initial.value, self->type); - ChannelValueDataSetFromReference(&self->initial.value, self->type, &src->initial.value); + if (RETURN_OK != ChannelValueDataSetFromReference(&self->initial.value, self->type, &src->initial.value)) { + return RETURN_ERROR; + } } self->writeResults = src->writeResults; @@ -120,8 +132,8 @@ static McxStatus CopyFrom(ScalarPortInput * self, ScalarPortInput * src) { } -static void PrintOptionalChannelValueData(char * prefix, ChannelType type, OPTIONAL_VALUE(ChannelValueData) value) { - switch(type) { +static void PrintOptionalChannelValueData(char * prefix, ChannelType * type, OPTIONAL_VALUE(ChannelValueData) value) { + switch(type->con) { case CHANNEL_DOUBLE: if (value.defined) { mcx_log(LOG_DEBUG, "%s%f,", prefix, value.value.d); @@ -196,7 +208,7 @@ static ScalarPortInput * ScalarPortInputCreate(ScalarPortInput * input) { input->id = NULL; input->unit = NULL; - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; OPTIONAL_UNSET(input->min); OPTIONAL_UNSET(input->max); diff --git a/src/reader/model/ports/ScalarPortInput.h b/src/reader/model/ports/ScalarPortInput.h index 258e38e..1361328 100644 --- a/src/reader/model/ports/ScalarPortInput.h +++ b/src/reader/model/ports/ScalarPortInput.h @@ -32,7 +32,7 @@ struct ScalarPortInput { char * id; char * unit; - ChannelType type; + ChannelType * type; OPTIONAL_VALUE(ChannelValueData) min; OPTIONAL_VALUE(ChannelValueData) max; diff --git a/src/reader/model/ports/VectorPortInput.c b/src/reader/model/ports/VectorPortInput.c index bd74ebc..a5d5ab4 100644 --- a/src/reader/model/ports/VectorPortInput.c +++ b/src/reader/model/ports/VectorPortInput.c @@ -144,20 +144,12 @@ static McxStatus CopyFrom(VectorPortInput * self, VectorPortInput * src) { self->default_ = NULL; } - if (src->writeResults) { - self->writeResults = (int *) mcx_calloc(len, sizeof(int)); - if (!self->writeResults) { - return RETURN_ERROR; - } - memcpy(self->writeResults, src->writeResults, len * sizeof(int)); - } else { - self->writeResults = NULL; - } + self->writeResults = src->writeResults; return RETURN_OK; } -static void PrintVec(char * prefix, ChannelType type, size_t len, void * value) { +static void PrintVec(char * prefix, ChannelType * type, size_t len, void * value) { char buffer[4096] = { 0 }; size_t num = 0; @@ -167,7 +159,7 @@ static void PrintVec(char * prefix, ChannelType type, size_t len, void * value) if (value) { for (i = 0; i < len; i++) { - switch(type) { + switch(type->con) { case CHANNEL_DOUBLE: num += sprintf(buffer + num, " %f", ((double*)value)[i]); break; @@ -187,6 +179,14 @@ static void PrintVec(char * prefix, ChannelType type, size_t len, void * value) mcx_log(LOG_DEBUG, "%s", buffer); } +static void PrintOptionalInt(char * prefix, OPTIONAL_VALUE(int) value) { + if (value.defined) { + mcx_log(LOG_DEBUG, "%s%d,", prefix, value.value); + } else { + mcx_log(LOG_DEBUG, "%s-,", prefix); + } +} + void VectorPortInputPrint(VectorPortInput * input) { size_t len = input->endIndex - input->startIndex + 1; @@ -205,7 +205,7 @@ void VectorPortInputPrint(VectorPortInput * input) { PrintVec(" .default: ", input->type, len, input->default_); PrintVec(" .initial: ", input->type, len, input->initial); - PrintVec(" .writeResults: ", input->type, len, input->writeResults); + PrintOptionalInt(" .writeResults: ", input->writeResults); mcx_log(LOG_DEBUG, "}"); } @@ -221,7 +221,6 @@ static void VectorPortInputDestructor(VectorPortInput * input) { if (input->offset) { mcx_free(input->offset); } if (input->default_) { mcx_free(input->default_); } if (input->initial) { mcx_free(input->initial); } - if (input->writeResults) { mcx_free(input->writeResults); } } static VectorPortInput * VectorPortInputCreate(VectorPortInput * input) { @@ -236,7 +235,7 @@ static VectorPortInput * VectorPortInputCreate(VectorPortInput * input) { input->id = NULL; input->unit = NULL; - input->type = CHANNEL_UNKNOWN; + input->type = &ChannelTypeUnknown; input->min = NULL; input->max = NULL; @@ -247,7 +246,7 @@ static VectorPortInput * VectorPortInputCreate(VectorPortInput * input) { input->default_ = NULL; input->initial = NULL; - input->writeResults = NULL; + OPTIONAL_UNSET(input->writeResults); inputElement->Clone = Clone; input->CopyFrom = CopyFrom; diff --git a/src/reader/model/ports/VectorPortInput.h b/src/reader/model/ports/VectorPortInput.h index 417767b..8dacb80 100644 --- a/src/reader/model/ports/VectorPortInput.h +++ b/src/reader/model/ports/VectorPortInput.h @@ -35,7 +35,7 @@ struct VectorPortInput { char * id; char * unit; - ChannelType type; + ChannelType * type; void * min; void * max; @@ -46,7 +46,7 @@ struct VectorPortInput { void * default_; void * initial; - int * writeResults; + OPTIONAL_VALUE(int) writeResults; fVectorPortInputCopyFrom CopyFrom; }; diff --git a/src/reader/ssp/Parameters.c b/src/reader/ssp/Parameters.c index 03963d7..83b24b2 100644 --- a/src/reader/ssp/Parameters.c +++ b/src/reader/ssp/Parameters.c @@ -25,6 +25,7 @@ extern "C" { #endif /* __cplusplus */ + typedef struct SSDParameterValue SSDParameterValue; typedef McxStatus(*fSSDParameterValueSetup)(SSDParameterValue * paramValue, xmlNodePtr node, ObjectContainer * units); @@ -614,12 +615,12 @@ static McxStatus CollectParameterValues(xmlNodePtr paramBindingsNode, ObjectCont return RETURN_OK; } -static MapStringInt _typeMappingScalar[] = { - {"Real", CHANNEL_DOUBLE}, - {"Integer", CHANNEL_INTEGER}, - {"Boolean", CHANNEL_BOOL}, - {"String", CHANNEL_STRING}, - {NULL, 0}, +static MapStringChannelType _typeMappingScalar[] = { + {"Real", &ChannelTypeDouble}, + {"Integer", &ChannelTypeInteger}, + {"Boolean", &ChannelTypeBool}, + {"String", &ChannelTypeString}, + {NULL, &ChannelTypeUnknown}, }; static ScalarParameterInput * SSDReadScalarParameter(SSDParameter * parameter) { @@ -676,7 +677,7 @@ static ScalarParameterInput * SSDReadScalarParameter(SSDParameter * parameter) { } } - if (input->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(input->type)) { retVal = xml_error_unsupported_node(connectorTypeNode); goto cleanup; } @@ -705,11 +706,11 @@ static ScalarParameterInput * SSDReadScalarParameter(SSDParameter * parameter) { return input; } -static MapStringInt _typeMappingArray[] = { - {"Real", CHANNEL_DOUBLE}, - {"Integer", CHANNEL_INTEGER}, - {"Boolean", CHANNEL_BOOL}, - {NULL, 0}, +static MapStringChannelType _typeMappingArray[] = { + {"Real", &ChannelTypeDouble}, + {"Integer", &ChannelTypeInteger}, + {"Boolean", &ChannelTypeBool}, + {NULL, &ChannelTypeUnknown}, }; static ArrayParameterDimensionInput * SSDReadArrayParameterDimension(xmlNodePtr node) { @@ -746,10 +747,10 @@ static ArrayParameterDimensionInput * SSDReadArrayParameterDimension(xmlNodePtr return input; } -static McxStatus AllocateMemory(SSDParameter * parameter, ChannelType type, size_t numValues, void ** dest) { +static McxStatus AllocateMemory(SSDParameter * parameter, ChannelType * type, size_t numValues, void ** dest) { size_t size = 0; - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: size = sizeof(double); break; @@ -825,7 +826,7 @@ static McxStatus SSDReadDimensionlessArrayParameter(SSDParameter * parameter, Ar continue; } - switch (input->type) { + switch (input->type->con) { case CHANNEL_DOUBLE: retVal = xml_attr_double(paramTypeNode, "value", (double*)input->values + paramValue->idx1, SSD_MANDATORY); break; @@ -911,7 +912,7 @@ static McxStatus SSDReadDimensionArrayParameter(SSDParameter * parameter, ArrayP index = (paramValue->idx1 - input->dims[0]->start) * (input->dims[1]->end - input->dims[1]->start + 1) + paramValue->idx2 - input->dims[1]->start; } - switch (input->type) { + switch (input->type->con) { case CHANNEL_DOUBLE: retVal = xml_attr_double(paramTypeNode, "value", (double*)input->values + index, SSD_MANDATORY); break; @@ -1025,7 +1026,7 @@ static ArrayParameterInput * SSDReadArrayParameter(SSDParameter * parameter) { } } - if (input->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(input->type)) { retVal = xml_error_unsupported_node(connectorTypeNode); goto cleanup; } diff --git a/src/reader/ssp/Ports.c b/src/reader/ssp/Ports.c index 8c03a63..93c4b08 100644 --- a/src/reader/ssp/Ports.c +++ b/src/reader/ssp/Ports.c @@ -17,6 +17,7 @@ #include "reader/model/ports/ScalarPortInput.h" #include "reader/model/ports/VectorPortInput.h" +#include "core/channels/ChannelValue.h" #include "util/string.h" @@ -24,20 +25,20 @@ extern "C" { #endif /* __cplusplus */ -static MapStringInt _typeMapping[] = { - {"Real", CHANNEL_DOUBLE}, - {"Integer", CHANNEL_INTEGER}, - {"Boolean", CHANNEL_BOOL}, - {"String", CHANNEL_STRING}, - {"Binary", CHANNEL_BINARY}, - {NULL, 0}, +static MapStringChannelType _typeMapping[] = { + {"Real", &ChannelTypeDouble}, + {"Integer", &ChannelTypeInteger}, + {"Boolean", &ChannelTypeBool}, + {"String", &ChannelTypeString}, + {"Binary", &ChannelTypeBinary}, + {NULL, &ChannelTypeUnknown}, }; -static MapStringInt _vectorTypeMapping[] = { - {"RealVector", CHANNEL_DOUBLE}, - {"IntegerVector", CHANNEL_INTEGER}, - {"BooleanVector", CHANNEL_BOOL}, - {NULL, 0}, +static MapStringChannelType _vectorTypeMapping[] = { + {"RealVector", &ChannelTypeDouble}, + {"IntegerVector", &ChannelTypeInteger}, + {"BooleanVector", &ChannelTypeBool}, + {NULL, &ChannelTypeUnknown}, }; @@ -140,7 +141,7 @@ VectorPortInput * SSDReadComponentVectorPort(xmlNodePtr connectorNode, const cha break; } } - if (vectorPortInput->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(vectorPortInput->type)) { retVal = xml_error_unsupported_node(typeNode); goto cleanup; } @@ -172,7 +173,7 @@ VectorPortInput * SSDReadComponentVectorPort(xmlNodePtr connectorNode, const cha xmlNodePtr vectorNode = NULL; size_t num = 0; - switch (vectorPortInput->type) { + switch (vectorPortInput->type->con) { case CHANNEL_DOUBLE: vectorNode = xml_child(portNode, "RealVector"); break; @@ -238,18 +239,9 @@ VectorPortInput * SSDReadComponentVectorPort(xmlNodePtr connectorNode, const cha goto cleanup; } - { - size_t n = 0; - retVal = xml_attr_bool_vec(vectorNode, "writeResults", &n, &vectorPortInput->writeResults, SSD_OPTIONAL); - if (RETURN_ERROR == retVal) { - goto cleanup; - } else if (RETURN_OK == retVal) { - if (n != num) { - mcx_log(LOG_ERROR, "xml_attr_vec_len: Expected length (%d) does not match actual length (%d)", num, n); - retVal = RETURN_ERROR; - goto cleanup; - } - } + retVal = xml_opt_attr_bool(vectorNode, "writeResults", &vectorPortInput->writeResults); + if (RETURN_ERROR == retVal) { + goto cleanup; } } } @@ -354,7 +346,7 @@ ScalarPortInput * SSDReadComponentScalarPort(xmlNodePtr connectorNode, const cha break; } } - if (scalarPortInput->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(scalarPortInput->type)) { retVal = xml_error_unsupported_node(typeNode); goto cleanup; } @@ -386,7 +378,7 @@ ScalarPortInput * SSDReadComponentScalarPort(xmlNodePtr connectorNode, const cha xmlNodePtr scalarNode = NULL; size_t num = 0; - switch (scalarPortInput->type) { + switch (scalarPortInput->type->con) { case CHANNEL_DOUBLE: scalarNode = xml_child(portNode, "Real"); break; diff --git a/src/reader/ssp/SpecificData.c b/src/reader/ssp/SpecificData.c index 1af4a25..b151743 100644 --- a/src/reader/ssp/SpecificData.c +++ b/src/reader/ssp/SpecificData.c @@ -17,6 +17,7 @@ #include "reader/model/components/specific_data/VectorIntegratorInput.h" #include "reader/model/components/specific_data/ConstantInput.h" +#include "core/channels/ChannelValue.h" #ifdef __cplusplus extern "C" { @@ -150,12 +151,12 @@ McxStatus SSDReadVectorIntegratorData(xmlNodePtr componentNode, xmlNodePtr speci return RETURN_OK; } -static MapStringInt _scalarConstantTypeMapping[] = { - {"Real", CHANNEL_DOUBLE}, - {"Integer", CHANNEL_INTEGER}, - {"String", CHANNEL_STRING}, - {"Boolean", CHANNEL_BOOL}, - {NULL, CHANNEL_UNKNOWN} +static MapStringChannelType _scalarConstantTypeMapping[] = { + {"Real", &ChannelTypeDouble}, + {"Integer", &ChannelTypeInteger}, + {"String", &ChannelTypeString}, + {"Boolean", &ChannelTypeBool}, + {NULL, &ChannelTypeUnknown} }; static ScalarConstantValueInput * SSDReadScalarConstantValue(xmlNodePtr node) { @@ -181,7 +182,7 @@ static ScalarConstantValueInput * SSDReadScalarConstantValue(xmlNodePtr node) { } } - if (input->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(input->type)) { retVal = xml_error_unsupported_node(node); goto cleanup; } @@ -201,10 +202,10 @@ static ScalarConstantValueInput * SSDReadScalarConstantValue(xmlNodePtr node) { return input; } -static MapStringInt _vectorConstantTypeMapping[] = { - {"RealVector", CHANNEL_DOUBLE}, - {"IntegerVector", CHANNEL_INTEGER}, - {NULL, CHANNEL_UNKNOWN} +static MapStringChannelType _vectorConstantTypeMapping[] = { + {"RealVector", &ChannelTypeDouble}, + {"IntegerVector", &ChannelTypeInteger}, + {NULL, &ChannelTypeUnknown} }; static ArrayConstantValueInput * SSDReadArrayConstantValue(xmlNodePtr node) { @@ -230,13 +231,13 @@ static ArrayConstantValueInput * SSDReadArrayConstantValue(xmlNodePtr node) { } } - if (input->type == CHANNEL_UNKNOWN) { + if (!ChannelTypeIsValid(input->type)) { retVal = xml_error_unsupported_node(node); goto cleanup; } } - switch (input->type) { + switch (input->type->con) { case CHANNEL_DOUBLE: retVal = xml_attr_double_vec(node, "value", &input->numValues, (double**)&input->values, SSD_MANDATORY); break; diff --git a/src/reader/ssp/Util.c b/src/reader/ssp/Util.c index 2c8e76c..7b883da 100644 --- a/src/reader/ssp/Util.c +++ b/src/reader/ssp/Util.c @@ -746,8 +746,8 @@ McxStatus xml_attr_enum_weak_ptr(xmlNodePtr node, return ret_status; } -McxStatus xml_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType type, ChannelValueData * dest, SSDParamMode mode) { - switch (type) { +McxStatus xml_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType * type, ChannelValueData * dest, SSDParamMode mode) { + switch (type->con) { case CHANNEL_DOUBLE: return xml_attr_double(node, attribute_name, &dest->d, mode); case CHANNEL_INTEGER: @@ -1160,7 +1160,7 @@ McxStatus xml_opt_attr_enum(xmlNodePtr node, const char * attribute_name, MapStr return RETURN_OK; } -McxStatus xml_opt_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType type, OPTIONAL_VALUE(ChannelValueData) * dest) { +McxStatus xml_opt_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType * type, OPTIONAL_VALUE(ChannelValueData) * dest) { McxStatus ret_val = xml_attr_channel_value_data(node, attribute_name, type, &dest->value, SSD_OPTIONAL); if (ret_val == RETURN_ERROR) { @@ -1172,7 +1172,7 @@ McxStatus xml_opt_attr_channel_value_data(xmlNodePtr node, const char * attribut return RETURN_OK; } -McxStatus xml_attr_vec_len(xmlNodePtr node, const char * attribute_name, ChannelType type, size_t expectedLen, void ** dest, SSDParamMode mode) { +McxStatus xml_attr_vec_len(xmlNodePtr node, const char * attribute_name, ChannelType * type, size_t expectedLen, void ** dest, SSDParamMode mode) { McxStatus ret_status = RETURN_OK; int ret_val = 0; xmlChar * buffer = NULL; @@ -1209,7 +1209,7 @@ McxStatus xml_attr_vec_len(xmlNodePtr node, const char * attribute_name, Channel goto cleanup; } - switch (type) { + switch (type->con) { case CHANNEL_DOUBLE: ret_status = xml_attr_double_vec(node, attribute_name, &len, (double **) &values, mode); break; diff --git a/src/reader/ssp/Util.h b/src/reader/ssp/Util.h index 524fe31..8c1af9f 100644 --- a/src/reader/ssp/Util.h +++ b/src/reader/ssp/Util.h @@ -69,20 +69,20 @@ McxStatus xml_attr_string(xmlNodePtr node, const char * attribute_name, char ** McxStatus xml_attr_path(xmlNodePtr node, const char * attribute_name, char ** dest, SSDParamMode mode); McxStatus xml_attr_enum(xmlNodePtr node, const char * attribute_name, MapStringInt * mapping, int * dest, SSDParamMode mode); McxStatus xml_attr_enum_weak_ptr(xmlNodePtr node, const char * attribute_name, void * map[], size_t entry_size, void ** value, SSDParamMode mode); -McxStatus xml_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType type, ChannelValueData * dest, SSDParamMode mode); +McxStatus xml_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType * type, ChannelValueData * dest, SSDParamMode mode); McxStatus xml_opt_attr_double(xmlNodePtr node, const char * attribute_name, OPTIONAL_VALUE(double) * dest); McxStatus xml_opt_attr_int(xmlNodePtr node, const char * attribute_name, OPTIONAL_VALUE(int) * dest); McxStatus xml_opt_attr_size_t(xmlNodePtr node, const char * attribute_name, OPTIONAL_VALUE(size_t) * dest); McxStatus xml_opt_attr_bool(xmlNodePtr node, const char * attribute_name, OPTIONAL_VALUE(int) * dest); McxStatus xml_opt_attr_enum(xmlNodePtr node, const char * attribute_name, MapStringInt * mapping, OPTIONAL_VALUE(int) * dest); -McxStatus xml_opt_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType type, OPTIONAL_VALUE(ChannelValueData) * dest); +McxStatus xml_opt_attr_channel_value_data(xmlNodePtr node, const char * attribute_name, ChannelType * type, OPTIONAL_VALUE(ChannelValueData) * dest); McxStatus xml_attr_double_vec(xmlNodePtr node, const char * attribute_name, size_t * len, double ** dest, SSDParamMode mode); McxStatus xml_attr_bool_vec(xmlNodePtr node, const char * attribute_name, size_t * len, int ** dest, SSDParamMode mode); McxStatus xml_attr_int_vec(xmlNodePtr node, const char * attribute_name, size_t * len, int ** dest, SSDParamMode mode); -McxStatus xml_attr_vec_len(xmlNodePtr node, const char * attribute_name, ChannelType type, size_t expectedLen, void ** dest, SSDParamMode mode); +McxStatus xml_attr_vec_len(xmlNodePtr node, const char * attribute_name, ChannelType * type, size_t expectedLen, void ** dest, SSDParamMode mode); /*****************************************************************************/ /* Errors */ diff --git a/src/steptypes/StepType.c b/src/steptypes/StepType.c index e653d50..0a1a39d 100644 --- a/src/steptypes/StepType.c +++ b/src/steptypes/StepType.c @@ -9,6 +9,7 @@ ********************************************************************************/ #include "core/Component.h" +#include "core/Component_impl.h" #include "core/SubModel.h" #include "core/Databus.h" #include "storage/ComponentStorage.h" @@ -25,6 +26,39 @@ extern "C" { // ---------------------------------------------------------------------- // Step Type: Common +void StepTypeSynchronizationSetup(StepTypeSynchronization * stepTypes, Component * comp, double syncStepSize) { + double syncToCoupl = 0.0; + double couplToSync = 0.0; + + if (!comp->HasOwnTime(comp)) { + return; + } + + if (comp->GetTimeStep(comp) <= 0.0) { + return; + } + + // If the coupling and synchronization step sizes are multiples of one another + // it is enough to use half the size of the smaller step for absolute time comparisons. + syncToCoupl = syncStepSize / comp->GetTimeStep(comp); + couplToSync = comp->GetTimeStep(comp) / syncStepSize; + + if (double_eq(syncToCoupl, round(syncToCoupl))) { + stepTypes->stepSizesAreMultiples = TRUE; + stepTypes->eps = comp->GetTimeStep(comp) / 2.0; + } + + if (double_eq(couplToSync, round(couplToSync))) { + stepTypes->stepSizesAreMultiples = TRUE; + stepTypes->eps = syncStepSize / 2.0; + } +} + +void StepTypeSynchronizationInit(StepTypeSynchronization * stepTypes) { + stepTypes->stepSizesAreMultiples = FALSE; + stepTypes->eps = -1.0; +} + McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeParams * params) { McxStatus retVal = RETURN_OK; double time = params->time; @@ -48,7 +82,9 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP while ( comp->GetFinishState(comp) != COMP_IS_FINISHED && - double_lt(comp->GetTime(comp), stepEndTime) + comp->syncHints.stepSizesAreMultiples ? + double_cmp_eps_abs(comp->GetTime(comp), stepEndTime, comp->syncHints.eps) == CMP_LT : + double_lt(comp->GetTime(comp), stepEndTime) ) { if (comp->HasOwnTime(comp)) { interval.startTime = comp->GetTime(comp); @@ -60,12 +96,13 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP } } + TimeSnapshotStart(&comp->data->rtData.funcTimings.rtTriggerIn); // TODO: Rename this to UpdateInChannels if (TRUE == ComponentGetUseInputsAtCouplingStepEndTime(comp)) { tmpTime = interval.startTime; interval.startTime = interval.endTime; - retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &interval); + retVal = DatabusTriggerConnectedInConnections(comp->GetDatabus(comp), &interval); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "%s: Update inports failed", comp->GetName(comp)); return RETURN_ERROR; @@ -73,12 +110,13 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP interval.startTime = tmpTime; } else { - retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &interval); + retVal = DatabusTriggerConnectedInConnections(comp->GetDatabus(comp), &interval); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "%s: Update inports failed", comp->GetName(comp)); return RETURN_ERROR; } } + TimeSnapshotEnd(&comp->data->rtData.funcTimings.rtTriggerIn); #ifdef MCX_DEBUG if (time < MCX_DEBUG_LOG_TIME) { @@ -86,6 +124,7 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP } #endif // MCX_DEBUG + TimeSnapshotStart((TimeSnapshot *) &comp->data->rtData.funcTimings.rtStoreIn); if (TRUE == ComponentGetStoreInputsAtCouplingStepEndTime(comp)) { retVal = comp->Store(comp, CHANNEL_STORE_IN, interval.endTime, level); } else if (FALSE == ComponentGetStoreInputsAtCouplingStepEndTime(comp)) { @@ -98,6 +137,7 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP mcx_log(LOG_ERROR, "%s: Storing inport failed", comp->GetName(comp)); return RETURN_ERROR; } + TimeSnapshotEnd((TimeSnapshot *) &comp->data->rtData.funcTimings.rtStoreIn); #ifdef MCX_DEBUG if (time < MCX_DEBUG_LOG_TIME) { @@ -121,6 +161,14 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP return RETURN_ERROR; } + if (comp->PostDoStep) { + retVal = comp->PostDoStep(comp); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "%s: PostDoStep failed", comp->GetName(comp)); + return RETURN_ERROR; + } + } + /* the last coupling step is the new synchronization step */ if (double_geq(comp->GetTime(comp), stepEndTime)) { level = STORE_SYNCHRONIZATION; @@ -134,6 +182,7 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP } #endif // MCX_DEBUG + TimeSnapshotStart((TimeSnapshot *) &comp->data->rtData.funcTimings.rtStore); retVal = comp->Store(comp, CHANNEL_STORE_OUT, comp->GetTime(comp), level); if (RETURN_ERROR == retVal) { mcx_log(LOG_ERROR, "%s: Storing outport failed", comp->GetName(comp)); @@ -149,6 +198,7 @@ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeP mcx_log(LOG_ERROR, "%s: Storing real time factors failed", comp->GetName(comp)); return RETURN_ERROR; } + TimeSnapshotEnd((TimeSnapshot *) &comp->data->rtData.funcTimings.rtStore); } if (comp->GetFinishState(comp) == COMP_IS_FINISHED) { @@ -184,7 +234,7 @@ static McxStatus CompTriggerInputs(CompAndGroup * compGroup, void * param) { return RETURN_ERROR; } - retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &interval); + retVal = DatabusTriggerConnectedInConnections(comp->GetDatabus(comp), &interval); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "%s: Updating inports failed", comp->GetName(comp)); return RETURN_ERROR; @@ -236,6 +286,18 @@ McxStatus CompEnterCouplingStepMode(Component * comp, void * param) { return RETURN_OK; } +McxStatus CompCollectModeSwitchData(Component * comp, void * param) { + McxStatus retVal = RETURN_OK; + + retVal = DatabusCollectModeSwitchData(comp->GetDatabus(comp)); + if (RETURN_OK != retVal) { + mcx_log(LOG_ERROR, "%s: Collecting mode switch data failed", comp->GetName(comp)); + return RETURN_ERROR; + } + + return RETURN_OK; +} + McxStatus CompEnterCommunicationPoint(CompAndGroup * compGroup, void * param) { const StepTypeParams * params = (const StepTypeParams *) param; @@ -249,6 +311,11 @@ McxStatus CompEnterCommunicationPoint(CompAndGroup * compGroup, void * param) { // ---------------------------------------------------------------------- // Step Type +int IsStepTypeMultiThreading(StepTypeType type) { + return (type == STEP_TYPE_PARALLEL_MT + ); +} + static McxStatus StepTypeConfigure(StepType * stepType, StepTypeParams * params, SubModel * subModel) { return RETURN_OK; } diff --git a/src/steptypes/StepType.h b/src/steptypes/StepType.h index f555b11..b0676d0 100644 --- a/src/steptypes/StepType.h +++ b/src/steptypes/StepType.h @@ -24,6 +24,18 @@ typedef struct SubModel SubModel; typedef struct CompAndGroup CompAndGroup; +typedef struct StepTypeSynchronization { + // flag whether the coupling and synchronization step size are multiples of one another + int stepSizesAreMultiples; + + // epsilon used for time comparisons + double eps; +} StepTypeSynchronization; + +void StepTypeSynchronizationSetup(StepTypeSynchronization * stepTypes, Component * comp, double syncStepSize); +void StepTypeSynchronizationInit(StepTypeSynchronization * stepTypes); + + typedef enum StepTypeType { STEP_TYPE_UNDEFINED = -1, /* "parallel_singlethreaded" */ STEP_TYPE_SEQUENTIAL = 1, /* "sequential" */ @@ -32,6 +44,9 @@ typedef enum StepTypeType { } StepTypeType; +int IsStepTypeMultiThreading(StepTypeType type); + + typedef McxStatus (* fStepTypeDoStep)(StepType * stepType, StepTypeParams * params, SubModel * subModel); typedef McxStatus (* fStepTypeFinish)(StepType * stepType, StepTypeParams * params, SubModel * subModel, FinishState * finishState); typedef McxStatus (* fStepTypeConfigure)(StepType * stepType, StepTypeParams * params, SubModel * subModel); @@ -56,6 +71,7 @@ struct StepTypeParams { /* shared functionality between step types */ McxStatus ComponentDoCommunicationStep(Component * comp, size_t group, StepTypeParams * params); McxStatus CompEnterCouplingStepMode(Component * comp, void * param); +McxStatus CompCollectModeSwitchData(Component * comp, void * param); McxStatus CompEnterCommunicationPoint(CompAndGroup * compGroup, void * param); McxStatus CompDoStep(CompAndGroup * compGroup, void * param); diff --git a/src/steptypes/StepTypeParallelMT.c b/src/steptypes/StepTypeParallelMT.c index 23e5bdd..ee43557 100644 --- a/src/steptypes/StepTypeParallelMT.c +++ b/src/steptypes/StepTypeParallelMT.c @@ -79,6 +79,8 @@ static void DoStepThreadArgSetup(DoStepThreadArg * arg, Component * comp, size_t arg->comp = comp; arg->group = group; arg->params = params; + + StepTypeSynchronizationSetup(&comp->syncHints, comp, params->timeStepSize); } static void DoStepThreadArgSetCounter(DoStepThreadArg * arg, DoStepThreadCounter * counter) { @@ -103,11 +105,13 @@ static DoStepThreadArg * DoStepThreadArgCreate(DoStepThreadArg * arg) { arg->SetCounter = DoStepThreadArgSetCounter; arg->StartThread = DoStepThreadArgStartThread; + arg->reachedSyncTime = 0.0; arg->comp = NULL; arg->group = 0; arg->params = NULL; arg->status = RETURN_OK; arg->finished = FALSE; + status = mcx_event_create(&arg->startDoStepEvent); if (status) { mcx_log(LOG_ERROR, "Simulation: Failed to create DoStep start event"); diff --git a/src/steptypes/StepTypeParallelMT.h b/src/steptypes/StepTypeParallelMT.h index deb3906..625f834 100644 --- a/src/steptypes/StepTypeParallelMT.h +++ b/src/steptypes/StepTypeParallelMT.h @@ -71,6 +71,9 @@ typedef struct DoStepThreadArg { // last status value McxStatus status; + // last reached synchronization point + double reachedSyncTime; + // flag if thread should stop int finished; diff --git a/src/steptypes/StepTypeSequential.c b/src/steptypes/StepTypeSequential.c index bbd6cc9..3e26842 100644 --- a/src/steptypes/StepTypeSequential.c +++ b/src/steptypes/StepTypeSequential.c @@ -61,7 +61,7 @@ McxStatus CompPreDoUpdateState(Component * comp, void * param) { } } - retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &interval); + retVal = DatabusTriggerConnectedInConnections(comp->GetDatabus(comp), &interval); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Simulation: Update inports for element PreDoUpdateState failed"); return RETURN_ERROR; @@ -96,7 +96,7 @@ McxStatus CompPostDoUpdateState(Component * comp, void * param) { } } - retVal = DatabusTriggerInConnections(comp->GetDatabus(comp), &interval); + retVal = DatabusTriggerConnectedInConnections(comp->GetDatabus(comp), &interval); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Simulation: Update inports for element PostDoUpdateState failed"); return RETURN_ERROR; diff --git a/src/storage/ChannelStorage.c b/src/storage/ChannelStorage.c index 4aa3807..65ca204 100644 --- a/src/storage/ChannelStorage.c +++ b/src/storage/ChannelStorage.c @@ -36,16 +36,16 @@ static McxStatus ChannelStorageRegisterChannelInternal(ChannelStorage * channelS /* if values have already been written, do not allow registering additional channels */ if (channelStore->values) { - info = channel->GetInfo(channel); - mcx_log(LOG_ERROR, "Results: Register port %s: Cannot register ports to storage after values have been stored", info->GetLogName(info)); + info = &channel->info; + mcx_log(LOG_ERROR, "Results: Register port %s: Cannot register ports to storage after values have been stored", ChannelInfoGetLogName(info)); return RETURN_ERROR; } /* add channel */ retVal = channels->PushBack(channels, (Object *)object_strong_reference(channel)); if (RETURN_OK != retVal) { - info = channel->GetInfo(channel); - mcx_log(LOG_DEBUG, "Results: Register port %s: Pushback of port failed", info->GetLogName(info)); + info = &channel->info; + mcx_log(LOG_DEBUG, "Results: Register port %s: Pushback of port failed", ChannelInfoGetLogName(info)); return RETURN_ERROR; } @@ -56,8 +56,8 @@ static McxStatus ChannelStorageRegisterChannel(ChannelStorage * channelStore, Ch ObjectContainer * channels = channelStore->channels; if (0 == channels->Size(channels)) { - ChannelInfo *info = channel->GetInfo(channel); - mcx_log(LOG_ERROR, "Results: Register port %s: Port storage not yet setup", info->GetLogName(info)); + ChannelInfo *info = &channel->info; + mcx_log(LOG_ERROR, "Results: Register port %s: Port storage not yet setup", ChannelInfoGetLogName(info)); return RETURN_ERROR; } @@ -65,7 +65,7 @@ static McxStatus ChannelStorageRegisterChannel(ChannelStorage * channelStore, Ch } static McxStatus ChannelStorageSetup(ChannelStorage * channelStore, int fullStorage) { - ChannelInfo * timeInfo = NULL; + ChannelInfo timeInfo = { 0 }; Channel * timeChannel = NULL; McxStatus retVal = RETURN_OK; @@ -77,38 +77,35 @@ static McxStatus ChannelStorageSetup(ChannelStorage * channelStore, int fullStor } /* add time channel */ - timeInfo = (ChannelInfo *) object_create(ChannelInfo); - if (!timeInfo) { /* this can only fail because of no memory */ - mcx_log(LOG_DEBUG, "Results: Setup port storage: No memory for time port data"); - return RETURN_ERROR; + retVal = ChannelInfoInit(&timeInfo); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Results: Setup port storage: Initialization of time port data failed"); + goto cleanup; } - retVal = timeInfo->Init( - timeInfo, - "Time", /* name */ - "", /* description */ - GetTimeUnitString(), /* unit */ - CHANNEL_DOUBLE, /* type */ - "" /* id*/ ); - if (RETURN_OK != retVal) { - mcx_log(LOG_ERROR, "Results: Setup port storage: Could not setup time port data"); - return RETURN_ERROR; + retVal = ChannelInfoSetup(&timeInfo, "Time", "Time", "", GetTimeUnitString(), &ChannelTypeDouble, ""); + if (RETURN_ERROR == retVal) { + mcx_log(LOG_ERROR, "Results: Setup port storage: Could not set up time port data"); + goto cleanup; } timeChannel = (Channel *) object_create(Channel); if (!timeChannel) { /* this can only fail because of no memory */ mcx_log(LOG_DEBUG, "Results: Setup port storage: No memory for time port"); - return RETURN_ERROR; + retVal = RETURN_ERROR; + goto cleanup; } - retVal = timeChannel->Setup(timeChannel, timeInfo); + retVal = timeChannel->Setup(timeChannel, &timeInfo); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Results: Setup port storage: Could not setup time port"); - return RETURN_ERROR; + goto cleanup; } retVal = ChannelStorageRegisterChannelInternal(channelStore, timeChannel); +cleanup: + ChannelInfoDestroy(&timeInfo); object_destroy(timeChannel); return retVal; @@ -155,11 +152,13 @@ static McxStatus ChannelStorageSetValueFromReferenceAt(ChannelStorage * channelS } if (row >= channelStore->numValues) { - ChannelInfo * info = channel->GetInfo(channel); - ChannelValueInit(&channelStore->values[row * colNum + col], info->GetType(info)); + ChannelInfo * info = &channel->info; + ChannelValueInit(&channelStore->values[row * colNum + col], ChannelTypeClone(info->type)); } - ChannelValueSetFromReference(&channelStore->values[row * colNum + col], reference); + if (RETURN_OK != ChannelValueSetFromReference(&channelStore->values[row * colNum + col], reference)) { + return RETURN_ERROR; + } return RETURN_OK; } @@ -207,8 +206,8 @@ static McxStatus ChannelStorageStoreFull(ChannelStorage * channelStore, double t retVal = ChannelStorageSetValueFromReferenceAt(channelStore, channelStore->numValues, i, channel->GetValueReference(channel)); if (RETURN_OK != retVal) { /* error msg in ChannelStorageSetValueFromReferenceAt */ - ChannelInfo *info = channel->GetInfo(channel); - mcx_log(LOG_DEBUG, "Results: Error in store port %s", info->GetLogName(info)); + ChannelInfo *info = &channel->info; + mcx_log(LOG_DEBUG, "Results: Error in store port %s", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } @@ -249,8 +248,8 @@ static McxStatus ChannelStorageStoreNonFull(ChannelStorage * channelStore, doubl Channel * channel = (Channel *) channels->At(channels, i); retVal = ChannelStorageSetValueFromReferenceAt(channelStore, 0, i, channel->GetValueReference(channel)); if (RETURN_OK != retVal) { /* error msg in ChannelStorageSetValueFromReferenceAt */ - ChannelInfo *info = channel->GetInfo(channel); - mcx_log(LOG_DEBUG, "Results: Error in store port %s", info->GetLogName(info)); + ChannelInfo *info = &channel->info; + mcx_log(LOG_DEBUG, "Results: Error in store port %s", ChannelInfoGetLogName(info)); return RETURN_ERROR; } } @@ -267,6 +266,11 @@ static ChannelValue ChannelStorageGetValueAt(ChannelStorage * channelStore, size return channelStore->values[row * colNum + col]; } +static ChannelValue * ChannelStorageGetValuesAtRow(ChannelStorage * channelStore, size_t row) { + size_t colNum = channelStore->channels->Size(channelStore->channels); + return channelStore->values + row * colNum; +} + static size_t ChannelStorageLength(ChannelStorage * channelStore) { return channelStore->numValues; @@ -277,7 +281,7 @@ static ChannelInfo * ChannelStorageGetChannelInfo(ChannelStorage * channelStore, Channel * channel = (Channel *) channels->At(channels, idx); if (channel) { - return channel->GetInfo(channel); + return &channel->info; } else { return NULL; } @@ -302,15 +306,12 @@ static void ChannelStorageDestructor(ChannelStorage * channelStore) { if (channels) { size_t i = 0; - if (channels->Size(channels) > 0) { - Channel * channel = (Channel *) channels->At(channels, 0); - ChannelInfo * timeInfo = channel->GetInfo(channel); - object_destroy(timeInfo); - } + for (i = 0; i < channels->Size(channels); i++) { Channel * channel = (Channel *) channels->At(channels, i); object_destroy(channel); } + object_destroy(channels); } } @@ -324,6 +325,7 @@ static ChannelStorage * ChannelStorageCreate(ChannelStorage * channelStore) { channelStore->GetChannelNum = ChannelStorageGetChannelNum; channelStore->GetValueAt = ChannelStorageGetValueAt; + channelStore->GetValuesAtRow = ChannelStorageGetValuesAtRow; channelStore->Length = ChannelStorageLength; channelStore->GetChannelInfo = ChannelStorageGetChannelInfo; @@ -346,6 +348,32 @@ static ChannelStorage * ChannelStorageCreate(ChannelStorage * channelStore) { return channelStore; } +char ** ExpandedChannelNames(const char * name, size_t start, size_t end) { + char ** names = NULL; + size_t i = 0; + + names = (char **) mcx_malloc(sizeof(char *) * (end - start + 1 + 1)); + if (!names) { + return NULL; + } + + for (i = start; i <= end; i++) { + names[i-start] = CreateIndexedName(name, i); + } + names[i-start] = NULL; + + return names; +} + +void FreeExpandedChannelNames(char ** names) { + size_t i = 0; + while (names[i]) { + mcx_free(names[i]); + ++i; + } + mcx_free(names); +} + OBJECT_CLASS(ChannelStorage, Object); #ifdef __cplusplus diff --git a/src/storage/ChannelStorage.h b/src/storage/ChannelStorage.h index 0702875..3ed9e08 100644 --- a/src/storage/ChannelStorage.h +++ b/src/storage/ChannelStorage.h @@ -26,6 +26,7 @@ typedef McxStatus (* fChannelStorageRegisterChannel)(ChannelStorage * channelSto typedef McxStatus (* fChannelStorageStore)(ChannelStorage * channelStore, double time); typedef size_t (* fChannelStorageGetChannelNum)(ChannelStorage * channelStore); typedef ChannelValue (* fChannelStorageGetValueAt)(ChannelStorage * channelStore, size_t row, size_t col); +typedef ChannelValue * (* fChannelStorageGetValuesAtRow)(ChannelStorage * channelStore, size_t row); typedef size_t (* fChannelStorageLength)(ChannelStorage * channelStore); typedef struct ChannelInfo * (* fChannelStorageGetChannelInfo)(ChannelStorage * channelStore, size_t idx); @@ -40,6 +41,7 @@ typedef struct ChannelStorage { fChannelStorageGetChannelNum GetChannelNum; fChannelStorageGetValueAt GetValueAt; + fChannelStorageGetValuesAtRow GetValuesAtRow; fChannelStorageLength Length; @@ -59,6 +61,9 @@ typedef struct ChannelStorage { size_t storeCallNum; } ChannelStorage; +char ** ExpandedChannelNames(const char * name, size_t start, size_t end); +void FreeExpandedChannelNames(char ** names); + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ diff --git a/src/storage/ComponentStorage.c b/src/storage/ComponentStorage.c index f9b8008..a6ce392 100644 --- a/src/storage/ComponentStorage.c +++ b/src/storage/ComponentStorage.c @@ -50,9 +50,8 @@ static McxStatus ComponentStorageRegisterChannel(ComponentStorage * compStore, C ChannelStorage * channels = compStore->channels[chType]; if (compStore->storeLevel > STORE_NONE) { - ChannelInfo * info = channel->GetInfo(channel); - if (compStore->storage->channelStoreEnabled[chType] - && info->GetWriteResultFlag(info)) { + ChannelInfo * info = &channel->info; + if (compStore->storage->channelStoreEnabled[chType] && info->writeResult) { return channels->RegisterChannel(channels, channel); } } diff --git a/src/storage/ResultsStorage.c b/src/storage/ResultsStorage.c index 41146ba..2af07bd 100644 --- a/src/storage/ResultsStorage.c +++ b/src/storage/ResultsStorage.c @@ -38,6 +38,7 @@ static StorageBackend * StorageBackendCreate(StorageBackend * backend) { backend->Configure = NULL; backend->Setup = NULL; backend->Store = NULL; + backend->StoreChannelValues = NULL; backend->Finished = NULL; backend->id = 0; @@ -160,6 +161,25 @@ static McxStatus StorageStoreModelLocal(ResultsStorage * storage, SubModel * sub return RETURN_OK; } +static McxStatus StorageStoreModelRTFactor(ResultsStorage * storage, SubModel * subModel, double time, StoreLevel level) { + size_t i = 0; + + McxStatus retVal = RETURN_OK; + + // Get values from Components + for (i = 0; i < storage->numComponents; i++) { + ComponentStorage * compStore = storage->componentStorage[i]; + if (subModel->IsElement(subModel, compStore->comp)) { + retVal = compStore->StoreChannels(compStore, CHANNEL_STORE_RTFACTOR, time, level); + if (RETURN_OK != retVal) { + return RETURN_ERROR; + } + } + } + + return RETURN_OK; +} + static McxStatus StorageFinishModel(ResultsStorage * storage, SubModel * subModel) { size_t i = 0; @@ -168,7 +188,7 @@ static McxStatus StorageFinishModel(ResultsStorage * storage, SubModel * subMode // Get values from Components for (i = 0; i < storage->numComponents; i++) { ComponentStorage * compStore = storage->componentStorage[i]; - if (subModel->IsElement(subModel, compStore->comp)) { + if (subModel->ContainsOrIsElement(subModel, compStore->comp)) { compStore->Finished(compStore); } } @@ -241,9 +261,13 @@ static McxStatus StorageAddBackend(ResultsStorage * storage, BackendType type, i StorageBackend * storeBackend = NULL; switch (type) { case BACKEND_CSV: - storeBackend = (StorageBackend *)object_create(StorageBackendCsv); + { + { + storeBackend = (StorageBackend *)object_create(StorageBackendCsv); + } break; } + } if (NULL == storeBackend) { mcx_log(LOG_ERROR, "The %s result storage backend could not be created", GetBackendTypeString(type)); return RETURN_ERROR; @@ -396,7 +420,7 @@ static McxStatus ResultsStorageSetChannelStoreEnabled(ResultsStorage * storage, return RETURN_OK; } -static McxStatus StorageRead(ResultsStorage * storage, ResultsInput * resultsInput, const Config * config) { +static McxStatus StorageRead(ResultsStorage * storage, ResultsInput * resultsInput, const Config * config, int multiThreaded) { BackendsInput * backendsInput = resultsInput->backends; size_t i = 0; McxStatus retVal = RETURN_OK; @@ -520,6 +544,7 @@ static ResultsStorage * ResultsStorageCreate(ResultsStorage * storage) { storage->StoreModel = StorageStoreModel; storage->StoreModelOut = StorageStoreModelOut; storage->StoreModelLocal = StorageStoreModelLocal; + storage->StoreModelRTFactor = StorageStoreModelRTFactor; storage->FinishModel = StorageFinishModel; storage->Finished = StorageFinished; diff --git a/src/storage/ResultsStorage.h b/src/storage/ResultsStorage.h index 2a0e78e..4665128 100644 --- a/src/storage/ResultsStorage.h +++ b/src/storage/ResultsStorage.h @@ -35,6 +35,7 @@ typedef struct StorageBackend StorageBackend; typedef McxStatus (* fStorageBackendConfigure)(StorageBackend * backend, ResultsStorage * storage, const char * path, int flushEveryStore, int storeAtRuntime); typedef McxStatus (* fStorageBackendSetup)(StorageBackend * backend); typedef McxStatus (* fStorageBackendStore)(StorageBackend * backend, ChannelStoreType chType, size_t comp, size_t row); +typedef McxStatus (* fStorageBackendStoreChannelValues)(StorageBackend * backend, ChannelStoreType chType, size_t comp, ChannelValue * channels, size_t num); typedef McxStatus (* fStorageBackendFinished)(StorageBackend * backend); extern const struct ObjectClass _StorageBackend; @@ -42,10 +43,11 @@ extern const struct ObjectClass _StorageBackend; struct StorageBackend { Object _; // super class first - fStorageBackendConfigure Configure; - fStorageBackendSetup Setup; - fStorageBackendStore Store; - fStorageBackendFinished Finished; + fStorageBackendConfigure Configure; + fStorageBackendSetup Setup; + fStorageBackendStore Store; + fStorageBackendStoreChannelValues StoreChannelValues; + fStorageBackendFinished Finished; int id; @@ -56,7 +58,7 @@ struct StorageBackend { struct ResultsStorage * storage; }; -typedef McxStatus (* fResultsStorageRead)(ResultsStorage * storage, ResultsInput * resultsInput, const Config * config); +typedef McxStatus (* fResultsStorageRead)(ResultsStorage * storage, ResultsInput * resultsInput, const Config * config, int multiThreaded); typedef McxStatus (* fResultsStorageSetup)(ResultsStorage * storage, double startTime); typedef McxStatus (* fResultsStorageFinished)(ResultsStorage * storage); @@ -91,6 +93,7 @@ struct ResultsStorage { fResultsStorageStoreModel StoreModel; fResultsStorageStoreModel StoreModelOut; fResultsStorageStoreModel StoreModelLocal; + fResultsStorageStoreModel StoreModelRTFactor; fResultsStorageFinishModel FinishModel; fResultsStorageRegisterComponent RegisterComponent; diff --git a/src/storage/StorageBackendCsv.c b/src/storage/StorageBackendCsv.c index e467a7c..67e216b 100644 --- a/src/storage/StorageBackendCsv.c +++ b/src/storage/StorageBackendCsv.c @@ -16,6 +16,8 @@ #include "storage/StorageBackendCsv.h" #include "storage/StorageBackendText_impl.h" #include "storage/PPD.h" +#include "storage/ChannelStorage.h" +#include "core/connections/ConnectionInfoFactory.h" #include "util/string.h" #include "util/os.h" @@ -185,19 +187,21 @@ static char * QuoteString(const char * _str) { static McxStatus SetupComponentFilesCsv(StorageBackend * backend) { StorageBackendText * textBackend = (StorageBackendText *) backend; ResultsStorage * storage = backend->storage; - char * buffer = NULL; size_t compIdx = 0; + size_t numCompsOld = textBackend->numComponents; - if (textBackend->numComponents > 0) { - mcx_log(LOG_ERROR, "Results: Re-setting up backend"); + MCX_DEBUG_LOG("Setting up component CSV files (%zu -> %zu)", numCompsOld, storage->numComponents); + textBackend->numComponents = storage->numComponents; + textBackend->comps = (TextComponent *) mcx_realloc(textBackend->comps, textBackend->numComponents * sizeof(TextComponent)); + if (textBackend->numComponents && !textBackend->comps) { + mcx_log(LOG_ERROR, "SetupComponentFilesCsv: TextComponents: Not enough memory"); return RETURN_ERROR; } - /* calloc is used for implicit initialization of textBackend->comps */ - textBackend->numComponents = storage->numComponents; - textBackend->comps = (TextComponent *) mcx_calloc(textBackend->numComponents, sizeof(TextComponent)); + // initialize new TextComponents to 0 + memset(textBackend->comps + numCompsOld, 0, (textBackend->numComponents - numCompsOld) * sizeof(TextComponent)); - for (compIdx = 0; compIdx < textBackend->numComponents; compIdx++) { + for (compIdx = numCompsOld; compIdx < textBackend->numComponents; compIdx++) { ComponentStorage * compStore = storage->componentStorage[compIdx]; Component * comp = (Component *) compStore->comp; TextComponent * textComponent = &(textBackend->comps[compIdx]); @@ -216,6 +220,7 @@ static McxStatus SetupComponentFilesCsv(StorageBackend * backend) { ChannelStorage * chStore = compStore->channels[j]; size_t chNum = chStore->GetChannelNum(chStore); size_t chIdx = 0; + char * buffer = NULL; const size_t nameLen = strlen(localName) + strlen(ChannelStoreSuffix[j]) + 6; /* do not create a file if channel store is not enabled */ @@ -251,36 +256,84 @@ static McxStatus SetupComponentFilesCsv(StorageBackend * backend) { for (chIdx = 0; chIdx < chNum; chIdx++) { ChannelInfo * info = chStore->GetChannelInfo(chStore, chIdx); - const char * channelName = info->GetName(info); - char * quotedChannelName = QuoteString(channelName); - const char * sep = textBackend->separator; - - if (chIdx == 0) { - sep = ""; - } - if(quotedChannelName){ - mcx_os_fprintf(textFile->fp, "%s\"%s\"", sep, quotedChannelName); - mcx_free(quotedChannelName); + const char * channelName = ChannelInfoGetName(info); + ChannelType * type = info->type; + + if (ChannelTypeIsArray(type)) { + if (type->ty.a.numDims > 1) { + // multi-dim not yet supported + continue; + } + ChannelDimension * dimension = info->dimension; + size_t array_start = dimension->startIdxs[0]; + size_t array_end = dimension->endIdxs[0]; + + size_t array_idx = 0; + + char ** names = ExpandedChannelNames(channelName, array_start, array_end); + const char * sep = textBackend->separator; + while (names[array_idx]) { + char * quotedChannelName = QuoteString(names[array_idx]); + + if(quotedChannelName){ + mcx_os_fprintf(textFile->fp, "%s\"%s\"", sep, quotedChannelName); + mcx_free(quotedChannelName); + } else { + mcx_os_fprintf(textFile->fp, "%s", sep); + } + ++array_idx; + } + FreeExpandedChannelNames(names); } else { - mcx_os_fprintf(textFile->fp, "%s", sep); + char * quotedChannelName = QuoteString(channelName); + const char * sep = textBackend->separator; + + if (chIdx == 0) { + sep = ""; + } + if(quotedChannelName){ + mcx_os_fprintf(textFile->fp, "%s\"%s\"", sep, quotedChannelName); + mcx_free(quotedChannelName); + } else { + mcx_os_fprintf(textFile->fp, "%s", sep); + } } - } mcx_os_fprintf(textFile->fp, "\n"); for (chIdx = 0; chIdx < chNum; chIdx++) { ChannelInfo * info = chStore->GetChannelInfo(chStore, chIdx); - const char * channelUnit = info->GetUnit(info); - const char * sep = textBackend->separator; - if (chIdx == 0) { - sep = ""; + ChannelType * type = info->type; + const char * channelUnit = info->unitString; + + if (ChannelTypeIsArray(type)) { + if (type->ty.a.numDims > 1) { + // multi-dim not yet supported + continue; + } + ChannelDimension * dimension = info->dimension; + size_t array_start = dimension->startIdxs[0]; + size_t array_end = dimension->endIdxs[0]; + + size_t array_idx = 0; + + const char * sep = textBackend->separator; + for (array_idx = array_start; array_idx <= array_end; array_idx++) { + mcx_os_fprintf(textFile->fp, "%s%s", sep, channelUnit); + } + } else { + const char * sep = textBackend->separator; + if (chIdx == 0) { + sep = ""; + } + mcx_os_fprintf(textFile->fp, "%s%s", sep, channelUnit); } - mcx_os_fprintf(textFile->fp, "%s%s", sep, channelUnit); } mcx_os_fprintf(textFile->fp, "\n"); } mcx_free(localName); } + return RETURN_OK; } diff --git a/src/storage/StorageBackendText.c b/src/storage/StorageBackendText.c index a951aad..b14f4c6 100644 --- a/src/storage/StorageBackendText.c +++ b/src/storage/StorageBackendText.c @@ -25,6 +25,7 @@ extern "C" { //declare storage functions +static McxStatus StoreChannelValues(StorageBackend * backend, ChannelStoreType chType, size_t comp, ChannelValue * values, size_t num); static McxStatus Store(StorageBackend * backend, ChannelStoreType chType, size_t comp, size_t row); static McxStatus Finished(StorageBackend * backend); static McxStatus StoreFull(StorageBackend * backend, ChannelStoreType chType, size_t comp, size_t row); @@ -91,6 +92,7 @@ static McxStatus Configure(StorageBackend * backend, ResultsStorage * storage, c } else { backend->needsFullStorage = 0; backend->Store = Store; + backend->StoreChannelValues = StoreChannelValues; backend->Finished = Finished; } @@ -196,9 +198,8 @@ static char * QuoteString(const char * _str) { return newStr; } -static McxStatus WriteRow(FILE * file, ChannelStorage * chStore, size_t row, const char * separator) { +static McxStatus WriteRow(FILE * file, ChannelValue * values, size_t numChannels, const char * separator) { size_t channel = 0; - const size_t numChannels = chStore->GetChannelNum(chStore); char staticBuffer[32]; int storedLen = 0; @@ -209,12 +210,15 @@ static McxStatus WriteRow(FILE * file, ChannelStorage * chStore, size_t row, con for (channel = 0; channel < numChannels; channel++) { McxStatus retVal = RETURN_OK; - ChannelValue val = chStore->GetValueAt(chStore, row, channel); + ChannelValue val = values[channel]; const char * sep = separator; if (channel == 0) { // leave out separator at the beginning sep = ""; } - switch (ChannelValueType(&val)) { + + // TODO: This should not mention CHANNEL_* anymore + + switch (ChannelValueType(&val)->con) { case CHANNEL_DOUBLE: case CHANNEL_INTEGER: case CHANNEL_BOOL: @@ -244,6 +248,12 @@ static McxStatus WriteRow(FILE * file, ChannelStorage * chStore, size_t row, con } break; } + case CHANNEL_ARRAY: { + char * str = ChannelValueToString(&val); + mcx_os_fprintf(file, "%s%s", sep, str); + mcx_free(str); + break; + } default: mcx_os_fprintf(file, "%s\"\"", sep); break; @@ -259,8 +269,7 @@ static McxStatus WriteRow(FILE * file, ChannelStorage * chStore, size_t row, con return RETURN_OK; } - -static McxStatus Store(StorageBackend * backend, ChannelStoreType chType, size_t comp, size_t row) { +static McxStatus StoreChannelValues(StorageBackend * backend, ChannelStoreType chType, size_t comp, ChannelValue * values, size_t num) { StorageBackendText * textBackend = (StorageBackendText *) backend; ResultsStorage * storage = backend->storage; ComponentStorage * compStore = storage->componentStorage[comp]; @@ -271,10 +280,10 @@ static McxStatus Store(StorageBackend * backend, ChannelStoreType chType, size_t mcx_log(LOG_ERROR, "Results: No result file for element %d", comp); return RETURN_ERROR; } + textFile = &(textBackend->comps[comp].files[chType]); - MCX_DEBUG_LOG("STORE WRITE (%d) chtype %d row %d", comp, chType, row); - retVal = WriteRow(textFile->fp, compStore->channels[chType], row, textBackend->separator); + retVal = WriteRow(textFile->fp, values, num, textBackend->separator); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Results: Could not write result row for \"%s\"", textFile->name); return RETURN_ERROR; @@ -285,6 +294,16 @@ static McxStatus Store(StorageBackend * backend, ChannelStoreType chType, size_t } } return RETURN_OK; + +} + + +static McxStatus Store(StorageBackend * backend, ChannelStoreType chType, size_t comp, size_t row) { + ResultsStorage * storage = backend->storage; + ComponentStorage * compStore = storage->componentStorage[comp]; + ChannelStorage * chStore = compStore->channels[chType]; + + return backend->StoreChannelValues(backend, chType, comp, chStore->GetValuesAtRow(chStore, row), chStore->GetChannelNum(chStore)); } @@ -336,7 +355,7 @@ static McxStatus FinishedFull(StorageBackend * backend) { if (storage->channelStoreEnabled[chType] && textFile) { for (chIdx = 0; chIdx < chStore->Length(chStore); chIdx++) { - McxStatus retVal = WriteRow(textFile->fp, chStore, chIdx, textBackend->separator); + McxStatus retVal = WriteRow(textFile->fp, chStore->GetValuesAtRow(chStore, chIdx), chStore->GetChannelNum(chStore), textBackend->separator); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Results: Could not write result row for %s", textFile->name); finishedStatus = RETURN_ERROR; diff --git a/src/util/common/compare.c b/src/util/common/compare.c index ebc5a50..ea21285 100644 --- a/src/util/common/compare.c +++ b/src/util/common/compare.c @@ -60,6 +60,12 @@ int double_almost_equal(double a, double b, double eps) { } } +static int double_almost_equal_abs(double a, double b, double eps) { + double diff = (a - b); + diff = (diff < 0) ? -diff : diff; + return diff < eps; +} + cmp double_cmp_eps(double a, double b, double eps) { if (double_almost_equal(a, b, eps)) { return CMP_EQ; @@ -73,6 +79,19 @@ cmp double_cmp_eps(double a, double b, double eps) { } } +cmp double_cmp_eps_abs(double a, double b, double eps) { + if (double_almost_equal_abs(a, b, eps)) { + return CMP_EQ; + } else if (a < b) { + return CMP_LT; + } else if (a > b) { + return CMP_GT; + } else { + // error + return CMP_IN; + } +} + int double_eq(double a, double b) { return (double_cmp(a,b) == CMP_EQ); } @@ -95,6 +114,10 @@ int double_geq(double a, double b) { || double_cmp(a,b) == CMP_GT); } +int double_leq_eps_abs(double a, double b, double eps) { + return (double_cmp_eps_abs(a, b, eps) == CMP_EQ || double_cmp_eps_abs(a, b, eps) == CMP_LT); +} + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/util/common/stdlib.c b/src/util/common/stdlib.c index cfa25b8..3109219 100644 --- a/src/util/common/stdlib.c +++ b/src/util/common/stdlib.c @@ -20,6 +20,17 @@ extern "C" { #endif /* __cplusplus */ +void * mcx_copy(void * object, size_t size) { + void * copy = mcx_malloc(size); + if (!copy) { + return NULL; + } + + memcpy(copy, object, size); + + return copy; +} + size_t mcx_filter(void * dst, void * base, size_t nmemb, size_t size, int (*pred)(const void *, void *), void * arg) { size_t i; size_t j = 0; diff --git a/src/util/common/time.c b/src/util/common/time.c index 3cff9f2..c2951c3 100644 --- a/src/util/common/time.c +++ b/src/util/common/time.c @@ -20,6 +20,13 @@ void mcx_time_init(McxTime * time) { mcx_time_diff(&now, &now, time); } +double mcx_time_to_milli_s(McxTime * time) { + return mcx_time_to_micro_s(time) / 1000.0; +} +double mcx_time_to_seconds(McxTime * time) { + return mcx_time_to_micro_s(time) / 1000000.0; +} + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/util/compare.h b/src/util/compare.h index 1a81b67..ae3e084 100644 --- a/src/util/compare.h +++ b/src/util/compare.h @@ -46,6 +46,14 @@ cmp double_cmp(double a, double b); */ cmp double_cmp_eps(double a, double b, double eps); +/** + * Returns CMP_LT, CMP_EQ or CMP_GT if a < b, a == b, a > b within eps + * and CMP_IN if a and b are not comparable. + * + * The comparison is done in an absolute manner. + */ +cmp double_cmp_eps_abs(double a, double b, double eps); + /** * Returns if a == b within an epsilon */ @@ -71,6 +79,11 @@ int double_leq(double a, double b); */ int double_geq(double a, double b); +/** + * Returns if a <= b modulo eps + */ +int double_leq_eps_abs(double a, double b, double eps); + #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/util/linux/signals.c b/src/util/linux/signals.c index aecd9de..101e510 100644 --- a/src/util/linux/signals.c +++ b/src/util/linux/signals.c @@ -18,6 +18,11 @@ /* Thread local variable to store the name of the element which is * running inside the signal-handled block. */ static __thread const char * _signalThreadName = NULL; +static __thread const char * _signalFunctionName = NULL; +static __thread const char * _signalFunctionNameStack1 = NULL; +static __thread const char * _signalFunctionNameStack2 = NULL; +static __thread const char * _signalFunctionNameStack3 = NULL; +static __thread const char * _signalFunctionNameStack4 = NULL; #ifdef __cplusplus extern "C" { @@ -25,7 +30,11 @@ extern "C" { static void sigHandlerParam(int param) { if (_signalThreadName) { - mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error. Shutting down.", _signalThreadName); + if (_signalFunctionName) { + mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error in %s. Shutting down.", _signalThreadName, _signalFunctionName); + } else { + mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error. Shutting down.", _signalThreadName); + } } else { mcx_log(LOG_ERROR, "An element caused an unrecoverable error. Shutting down."); } @@ -48,6 +57,33 @@ void mcx_signal_handler_unset_name(void) { _signalThreadName = NULL; } +void mcx_signal_handler_set_function(const char * functionName) { +#if defined(MCX_DEBUG) + if (_signalFunctionNameStack4 != NULL) { + mcx_log(LOG_ERROR, "Signal handler function callstack overflow!"); + exit(1); // I guess there is a better way to handle this + } +#endif + _signalFunctionNameStack4 = _signalFunctionNameStack3; + _signalFunctionNameStack3 = _signalFunctionNameStack2; + _signalFunctionNameStack2 = _signalFunctionNameStack1; + _signalFunctionNameStack1 = _signalFunctionName; + _signalFunctionName = functionName; +} + +void mcx_signal_handler_unset_function(void) { +#if defined(MCX_DEBUG) + if (_signalFunctionName == NULL) { + mcx_log(LOG_WARNING, "Signal handler function callstack empty. Cannot pop non-existing element."); + } +#endif + _signalFunctionName = _signalFunctionNameStack1; + _signalFunctionNameStack1 = _signalFunctionNameStack2; + _signalFunctionNameStack2 = _signalFunctionNameStack3; + _signalFunctionNameStack3 = _signalFunctionNameStack4; + _signalFunctionNameStack4 = NULL; +} + void mcx_signal_handler_enable(void) { static struct sigaction sigHandlerSEGV; @@ -71,6 +107,10 @@ void mcx_signal_handler_disable(void) { _signalThreadName = NULL; } +const char * mcx_signal_handler_get_function_name(void) { + return _signalFunctionName; +} + #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/util/linux/time.c b/src/util/linux/time.c index 082200b..cc86196 100644 --- a/src/util/linux/time.c +++ b/src/util/linux/time.c @@ -66,8 +66,8 @@ void mcx_time_diff(McxTime * start, McxTime * end, McxTime * result) { timersub(end, start, result); } -double mcx_time_to_seconds(McxTime * time) { - return time->tv_sec + time->tv_usec / 1000000.0; +double mcx_time_to_micro_s(McxTime * time) { + return time->tv_sec*1000000.0 + time->tv_usec; } McxTime mcx_seconds_to_time(int seconds) { diff --git a/src/util/signals.h b/src/util/signals.h index f468ca7..b1a3ee0 100644 --- a/src/util/signals.h +++ b/src/util/signals.h @@ -23,6 +23,15 @@ void mcx_signal_handler_enable(void); void mcx_signal_handler_set_name(const char * threadName); void mcx_signal_handler_unset_name(void); +/** + * Sets and unsets the current functions name for usage in signal handler messages + * + * Note: __func__ is part of C99 standard (ISO/IEC 9899:1999), section 6.4.2.2 + */ +#define mcx_signal_handler_set_this_function() mcx_signal_handler_set_function(__func__) +void mcx_signal_handler_set_function(const char * functionName); +void mcx_signal_handler_unset_function(void); + /** * Deletes the handler for SIGSEGV */ @@ -38,6 +47,7 @@ void mcx_signal_handler_sigint(int param); */ int mcx_signal_handler_is_interrupted(void); +const char * mcx_signal_handler_get_function_name(void); #ifdef __cplusplus } /* closing brace for extern "C" */ diff --git a/src/util/stdlib.h b/src/util/stdlib.h index 52332c2..2dd3470 100644 --- a/src/util/stdlib.h +++ b/src/util/stdlib.h @@ -18,6 +18,8 @@ extern "C" { #endif /* __cplusplus */ +void * mcx_copy(void * object, size_t size); + /** * Sorts the given array in-place using quicksort. * diff --git a/src/util/time.h b/src/util/time.h index a8dfecd..c6a88f0 100644 --- a/src/util/time.h +++ b/src/util/time.h @@ -32,6 +32,8 @@ void mcx_cpu_time_get(McxTime * time); void mcx_time_add(McxTime * a, McxTime * b, McxTime * result); void mcx_time_diff(McxTime * start, McxTime * end, McxTime * result); double mcx_time_to_seconds(McxTime * time); +double mcx_time_to_micro_s(McxTime * time); +double mcx_time_to_milli_s(McxTime * time); McxTime mcx_seconds_to_time(int seconds); long mcx_time_get_clock(); diff --git a/src/util/win/signals.c b/src/util/win/signals.c index e584175..156b3b5 100644 --- a/src/util/win/signals.c +++ b/src/util/win/signals.c @@ -21,6 +21,11 @@ /* Thread local variable to store the name of the element which is * running inside the signal-handled block. */ __declspec( thread ) static const char * _signalThreadName = NULL; +__declspec( thread ) static const char * _signalFunctionName = NULL; +__declspec( thread ) static const char * _signalFunctionNameStack1 = NULL; +__declspec( thread ) static const char * _signalFunctionNameStack2 = NULL; +__declspec( thread ) static const char * _signalFunctionNameStack3 = NULL; +__declspec( thread ) static const char * _signalFunctionNameStack4 = NULL; #ifdef __cplusplus extern "C" { @@ -28,7 +33,11 @@ extern "C" { static LONG WINAPI HandleException(PEXCEPTION_POINTERS exception) { if (_signalThreadName) { - mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error.", _signalThreadName); + if (_signalFunctionName) { + mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error in %s.", _signalThreadName, _signalFunctionName); + } else { + mcx_log(LOG_ERROR, "The element %s caused an unrecoverable error.", _signalThreadName); + } } else { mcx_log(LOG_ERROR, "An element caused an unrecoverable error."); } @@ -112,6 +121,33 @@ void mcx_signal_handler_unset_name(void) { _signalThreadName = NULL; } +void mcx_signal_handler_set_function(const char * functionName) { +#if defined(MCX_DEBUG) + if (_signalFunctionNameStack4 != NULL) { + mcx_log(LOG_ERROR, "Signal handler function callstack overflow!"); + exit(1); // I guess there is a better way to handle this + } +#endif + _signalFunctionNameStack4 = _signalFunctionNameStack3; + _signalFunctionNameStack3 = _signalFunctionNameStack2; + _signalFunctionNameStack2 = _signalFunctionNameStack1; + _signalFunctionNameStack1 = _signalFunctionName; + _signalFunctionName = functionName; +} + +void mcx_signal_handler_unset_function(void) { +#if defined(MCX_DEBUG) + if (_signalFunctionName == NULL) { + mcx_log(LOG_WARNING, "Signal handler function callstack in element %s empty. Cannot pop non-existing element.", _signalThreadName); + } +#endif + _signalFunctionName = _signalFunctionNameStack1; + _signalFunctionNameStack1 = _signalFunctionNameStack2; + _signalFunctionNameStack2 = _signalFunctionNameStack3; + _signalFunctionNameStack3 = _signalFunctionNameStack4; + _signalFunctionNameStack4 = NULL; +} + void mcx_signal_handler_enable(void) { _signalThreadName = NULL; SetUnhandledExceptionFilter(HandleException); @@ -124,6 +160,10 @@ void mcx_signal_handler_disable(void) { _signalThreadName = NULL; } +const char * mcx_signal_handler_get_function_name(void) { + return _signalFunctionName; +} + #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */ \ No newline at end of file diff --git a/src/util/win/time.c b/src/util/win/time.c index 3a9a191..990c9af 100644 --- a/src/util/win/time.c +++ b/src/util/win/time.c @@ -50,7 +50,7 @@ void mcx_time_diff(McxTime * start, McxTime * end, McxTime * result) { result->QuadPart = end->QuadPart - start->QuadPart; } -double mcx_time_to_seconds(McxTime * time) { +double mcx_time_to_micro_s(McxTime * time) { McxTime freq; McxTime micro_secs; @@ -58,7 +58,7 @@ double mcx_time_to_seconds(McxTime * time) { micro_secs.QuadPart = time->QuadPart * 1000000; micro_secs.QuadPart /= freq.QuadPart; - return micro_secs.QuadPart / 1000000.0; + return micro_secs.QuadPart; } McxTime mcx_seconds_to_time(int seconds) {