diff --git a/Version_Max_07_05_2018_CMake/src/AbstractionModule.cpp b/Version_Max_07_05_2018_CMake/src/AbstractionModule.cpp new file mode 100755 index 0000000..0699f08 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/AbstractionModule.cpp @@ -0,0 +1,198 @@ +#include "AbstractionModule.h" +#include "abstraction_interface.h" + +#include + + +void AbstractionModule :: initialize_abstraction(Lookuptable* lut, unsigned int abstraction_method) { + this->abstraction_method = abstraction_method; + + num_of_lookuptables = 0; + + for(unsigned int lut_ix=0; lut_ixabstraction_method = abstraction_strategy; + return true; + } + return false; +} + +unsigned int AbstractionModule :: get_abstraction_method() { + return abstraction_method; +} + +bool AbstractionModule :: add_lookuptable(Lookuptable* lut) { + if(num_of_lookuptables < MAX_NUM_OF_LOOKUPTABLES && lut != NULL) { + flag_lookuptable_exist[num_of_lookuptables] = true; + num_of_lookuptables++; + return true; + } + return false; +} + +bool AbstractionModule :: get_flag_lookuptable_exist(unsigned int position) { + if(position < num_of_lookuptables) { + return flag_lookuptable_exist[position]; + } + return false; +} + +Lookuptable* AbstractionModule :: get_lookuptable(unsigned int position) { + if(position < num_of_lookuptables) { + return list_lookuptables[position]; + } + return NULL; +} + +/* +bool Abstraction :: connect_with_lookuptable(unsigned int position, Lookuptable* lut) { + if(position < num_of_sensors) { + list_lookuptables_float[position] = lut; + return true; + } + return false; +} + +void Abstraction :: set_num_of_slaveagents(unsigned int num_of_slaveagents) { + this->num_of_slaveagents = num_of_slaveagents; +} + +unsigned int Abstraction :: get_num_of_slaveagents() { + return num_of_slaveagents; +} + +void Abstraction :: set_num_of_sensors(unsigned int num_of_sensors) { + this->num_of_sensors = num_of_sensors; +} + +unsigned int Abstraction :: get_num_of_sensors() { + return num_of_sensors; +} + +bool Abstraction :: set_input_parameter(unsigned int position, int input_parameter) { + if(position < MAX_NUM_OF_INPUT_VALUES) { + flag_input_data_int_is_in_use[position] = true; + input_data_int[position] = input_parameter; + return true; + } + return false; +} + +bool Abstraction :: set_input_parameter(unsigned int position, float input_parameter) { + if(position < MAX_NUM_OF_INPUT_VALUES) { + flag_input_data_float_is_in_use[position] = true; + input_data_float[position] = input_parameter; + return true; + } + return false; +} + +bool Abstraction :: get_input_parameter(unsigned int position, int* input_parameter) { + if(position < MAX_NUM_OF_INPUT_VALUES) { + if(flag_input_data_int_is_in_use[position]) { + *input_parameter = input_data_int[position]; + return true; + } + } + return false; +} +bool Abstraction :: get_input_parameter(unsigned int position, float* input_parameter) { + if(position < MAX_NUM_OF_INPUT_VALUES) { + if(flag_input_data_float_is_in_use[position]) { + *input_parameter = input_data_float[position]; + return true; + } + } + return false; +}*/ + +bool AbstractionModule :: abstract(float input, int* output) { + + switch(abstraction_method) { + + case ABSTRACTION_METHOD_NOT_SPECIFIED: return false; + case ABSTRACTION_LOOKUPTABLE: return abstract_via_lookuptable(input, output); break; + + default:return false; break;//TODO: interface + + //default: return abstract_interface(abstraction_method, num_of_slaveagents, flag_input_data_int_is_in_use, input_data_int, num_of_sensors, flag_input_data_float_is_in_use, input_data_float); break; + } + + /* + if(abstraction_method == ABSTRACTION_METHOD_NOT_SPECIFIED) + return false; + + return abstract_data(abstraction_method, num_of_mounted_slaveagents, flag_input_data_int_is_in_use, input_data_int, num_of_mounted_sensors, flag_input_data_float_is_in_use, input_data_float); + */ + + +} + +bool AbstractionModule :: abstract_via_lookuptable(float input, int* output) { + + if(list_lookuptables[lookuptable_to_use]->get_lookuptable_is_correct_and_active()) { + *output = list_lookuptables[lookuptable_to_use]->get_score(input); + return true; + } + + return false; //dummy +} + + + +/* +bool Abstraction :: add_score_to_input_data_lookuptable(unsigned int position, float lower_boundary, float upper_boundary, int score, bool flag_lower_boundary_exist, bool flag_upper_boundary_exist, bool flag_lower_boundary_included, bool flag_upper_boundary_included) { + + if(flag_input_data_range_is_activated[position] == false) { + + bool flag_found_empty_position = false; + + for(unsigned int pos=0; pos + +//TODO: Move this include to ControlModule +#include "instruction_set_architecture.h" + +/* +#include "Evaluation.h" +#include "instruction_set_architecture.h" +*/ + +#define PRINT_READING + +void Agent :: init_agent() { + sensorHandlerOfAgent = NULL; + slaveAgentHandlerOfAgent = NULL; + masterAgentHandlerOfAgent = NULL; + stateHandler = NULL; + + workingCycleCounter = 0; +} + +Agent :: Agent() { + set_name(NO_NAME); + init_agent(); +} + +Agent :: Agent(char* name) { + set_name(name); + init_agent(); + +} + +bool Agent :: set_sensorHandlerOfAgent() { + sensorHandlerOfAgent = new SensorHandlerOfAgent(); + + if(sensorHandlerOfAgent == NULL) { + printError("Couldn't create Sensor Handler!"); + return false; + } + return true; +} + +bool Agent :: del_sensorHandlerOfAgent() { + if(sensorHandlerOfAgent != NULL) { + //TODO: Unmount/delete all sensorSlots with everything inside (history module, confidence module, ...) + delete sensorHandlerOfAgent; + return true; + } + return false; +} + +SensorHandlerOfAgent* Agent :: get_sensorHandlerOfAgent() { + if(sensorHandlerOfAgent == NULL) { + set_sensorHandlerOfAgent(); + } + return sensorHandlerOfAgent; +} + +bool Agent :: set_slaveAgentHandlerOfAgent() { + slaveAgentHandlerOfAgent = new SlaveAgentHandlerOfAgent(); + + if(slaveAgentHandlerOfAgent == NULL) { + printError("Couldn't create Slave Agent Handler!"); + return false; + } + return true; +} + +bool Agent :: del_slaveAgentHandlerOfAgent() { + if(slaveAgentHandlerOfAgent != NULL) { + //TODO: Unmount/delete all SlaveAgentSlots with everything inside (history module, confidence module, ...) + delete slaveAgentHandlerOfAgent; + return true; + } + return false; +} + +SlaveAgentHandlerOfAgent* Agent :: get_slaveAgentHandlerOfAgent() { + if(slaveAgentHandlerOfAgent == NULL) { + set_slaveAgentHandlerOfAgent(); + } + return slaveAgentHandlerOfAgent; +} + +bool Agent :: set_masterAgentHandlerOfAgent() { + masterAgentHandlerOfAgent = new MasterAgentHandlerOfAgent(); + + if(masterAgentHandlerOfAgent == NULL) { + printError("Couldn't create Master Agent Handler!"); + return false; + } + return true; +} + +bool Agent :: del_masterAgentHandlerOfAgent() { + if(masterAgentHandlerOfAgent != NULL) { + //TODO: Unmount/delete (all) MasterAgentSlot(s) with everything inside + delete masterAgentHandlerOfAgent; + return true; + } + return false; +} + +MasterAgentHandlerOfAgent* Agent :: get_masterAgentHandlerOfAgent() { + if(masterAgentHandlerOfAgent == NULL) { + set_masterAgentHandlerOfAgent(); + } + return masterAgentHandlerOfAgent; +} + +bool Agent :: set_stateHandler() { + stateHandler = new StateHandler(); + + if(stateHandler == NULL) { + printError("Couldn't create Master Agent Handler!"); + return false; + } + return true; +} + +bool Agent :: set_stateHandler(StateHandler* stateHandler) { + if(stateHandler == NULL) { + this->stateHandler = stateHandler; + return true; + } + return false; +} + + +bool Agent :: del_stateHandler() { + if(stateHandler != NULL) { + //TODO: Unmount/delete (all) MasterAgentSlot(s) with everything inside + delete stateHandler; + return true; + } + return false; +} + +StateHandler* Agent :: get_stateHandler() { + + if(stateHandler == NULL) { + set_stateHandler(); + } + + return stateHandler; +} + + +StateHandler* Agent::get_stateHandler2() { + + return stateHandler; +} + +Agent::~Agent() +{ + del_masterAgentHandlerOfAgent(); + del_slaveAgentHandlerOfAgent(); + del_sensorHandlerOfAgent(); + del_stateHandler(); +} + + +void Agent :: trigger(unsigned int cycle) { + + if (workingCycleCounter < get_workingCycle()) + workingCycleCounter++; + else + workingCycleCounter = 1; + + if (workingCycleCounter == 1) { + + //TODO: make control_module to set the method of operating for each agent individual + + //Job: Read all sensory data + if(sensorHandlerOfAgent != NULL) { + //printf("%s->sensorHandler: ", name); + sensorHandlerOfAgent->read_allSensorValues(); + } + + //Job: Read all slave agent data + if(slaveAgentHandlerOfAgent != NULL) { + //TODO: do this in HistoryModule //TODO: this for all slots (not only for slaveagents) + slaveAgentHandlerOfAgent->saveAllValuesInHistory(); + //getchar(); + + slaveAgentHandlerOfAgent->read_allSlaveAgentValues(); + } + + //Job: Just pass the Sensory Data (without abstraction) to master + if(masterAgentHandlerOfAgent != NULL) { + if(sensorHandlerOfAgent != NULL) { + vector* vSensoryData = sensorHandlerOfAgent->get_vMountedSensors(); + for(auto &sensorSlot : *vSensoryData) { + //TODO: also for int + float sensorValue; + if(sensorSlot->get_sensorValue(&sensorValue)) { + masterAgentHandlerOfAgent->pass_msgToSendBuffer(ISA_SensoryData); + masterAgentHandlerOfAgent->pass_msgToSendBuffer(sensorValue); + } + } + } + masterAgentHandlerOfAgent->send_msgs(); + } + + + if (stateHandler != NULL) { + stateHandler->trigger(cycle); + } + + + } + + /* + read_all_mountedSensors(); + + validate_confidence_of_all_mountedSensors(); + + //TODO: save only when confident or save everytime? ...maybe safe confidence as meta data. + save_all_mountedSensor_histories(); + + read_all_slaveAgents(); + */ + + + + + + + + + + + + + + + + + + + + + + + + /* OLD + //has to be done in an extra loop because every slave agent values are needed + for(unsigned int sa_ix = 0; sa_ixcross_validate(num_of_mounted_slaveagents, slaveagent_value, &flag_slaveagent_value_confident[0]); + } + } + + + //bunch //TODO: auch f�r integer (slaveagents) + if(flag_bunch_module_exist) { + bunch_score_confidency = bunch_module->bunch(num_of_mounted_slaveagents, &slaveagent_value[0], &flag_slaveagent_value_confident[0], &bunched_score); + //printf("flag_bunched_score_exist setzten - "); + if(bunch_score_confidency > 0) { + flag_bunched_score_exist = true; + //printf("true\n"); + } + else { + flag_bunched_score_exist = false; + //printf("false\n"); + } + } + + + + + + + //abstract data //TODO: auch f�r integer (slaveagents) + for(unsigned int s_ix = 0; s_ixabstract(sensor_value[s_ix], &abstracted_sensor_score[s_ix])) { + flag_abstracted_sensor_score_exist[s_ix] = true; + } + else { + flag_abstracted_sensor_score_exist[s_ix] = false; + } + } + } + } + + //sending data / do specific task + if(flag_masteragent_outputport_is_active) { + for(unsigned int s_ix = 0; s_ixset_msg((int)ISA_SCORE_VALID); + } + else { + mounted_masteragent_outputport->set_msg((int)ISA_SCORE_INVALID); + } + } + else { + mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID); + } + + + + //if(flag_sensor_value_confident || flag_confidence_validator_exist == false) { + // mounted_masteragent_outputport->set_msg((int)IS_SCORE_VALID); + //} + //else { + // mounted_masteragent_outputport->set_msg((int)IS_SCORE_INVALID); + //} + + mounted_masteragent_outputport->set_msg(abstracted_sensor_score[s_ix]); + } + } + } + */ +} + + + +/* +void Agent :: initialize_master_slot() { + //TODO: also mast_is_active needed? + flag_masteragent_is_mounted = UNMOUNTED; + flag_masteragent_inputport_is_active = INACTIVE; + flag_masteragent_outputport_is_active = INACTIVE; +} + +void Agent :: initialize_slaveagent_slots() { + num_of_mounted_slaveagents = 0; + //number_of_active_mounted_subagents = 0; //TODO: do i need it?? + for(unsigned int sa_ix=0; sa_ixworking_frequency = working_frequency; + return true; + } + this->working_frequency = 0; + return false; +} + + +bool Agent :: read_mountedSensor(unsigned int s_ix) { + + bool flag_got_new_sensor_value; + float temp_sensor_value; + + flag_got_new_sensor_value = mounted_sensor_inputport[s_ix]->get_msg_float(&temp_sensor_value); + + if(flag_got_new_sensor_value) { + + if(!flag_sensor_value_set[s_ix]) { + flag_sensor_value_set[s_ix] = true; + flag_sensor_value_changed[s_ix] = true; + sensor_value[s_ix] = temp_sensor_value; + } + else { + if(sensor_value[s_ix] == temp_sensor_value) { + flag_sensor_value_changed[s_ix] = false; + } + else { + flag_sensor_value_changed[s_ix] = true; + sensor_value[s_ix] = temp_sensor_value; + } + } + } + else { + flag_sensor_value_changed[s_ix] = false; + } + + return flag_got_new_sensor_value; +} + + +void Agent :: read_all_mountedSensors() { + + for(unsigned int s_ix = 0; s_ixdrop_data(sensor_value[s_ix]); + } + + return flag_data_saved; +} + +void Agent :: save_all_mountedSensor_histories() { + + for(unsigned int s_ix = 0; s_ixget_latest_value(&temp_value)) + printf("History %s got value: %f\n", name, temp_value); + else + printf("History %s got no value.\n", name); + } + else { + printf("History doesn't exist.\n"); + } + } +} + +//TODO: this function is untested - test it! +bool Agent :: validate_confidence_of_mountedSensor(unsigned int s_ix) { + + if(flag_sensor_value_set[s_ix]) { + + if(flag_confidence_validator_exist[s_ix]) { + //TODO: modify validate_confidence function in a way that there is parameter that says if actual sensor_value[s_ix] is already in history or not! + flag_sensor_value_confident[s_ix] = list_of_confidence_validators[s_ix]->validate_confidence(sensor_value[s_ix], sensor_history[s_ix]); + } + else { + //I have to believe it if I don't know + flag_sensor_value_confident[s_ix] = true; + } + } + + return flag_sensor_value_confident[s_ix]; +} + +void Agent :: validate_confidence_of_all_mountedSensors() { + for(unsigned int s_ix = 0; s_ixis_there_a_msg_for_me_int()) { + + instruction = mounted_slaveagent_inputport[sa_ix]->get_msg_int(); //TODO: hier (vllt) auch die m�glichkeit float (score) einzulesen!! + + if(instruction == ISA_SCORE_VALID || instruction == ISA_SCORE_INVALID) { + + bool got_msg = mounted_slaveagent_inputport[sa_ix]->is_there_a_msg_for_me_int(); + + if(got_msg) { + data = mounted_slaveagent_inputport[sa_ix]->get_msg_int(); + + if(slaveagent_value[sa_ix] != data) { + flag_slaveagent_value_changed[sa_ix] = true; + } + slaveagent_value[sa_ix] = data; + flag_slaveagent_value_set[sa_ix] = true; + + if(instruction == ISA_SCORE_VALID) { + //if(id == 0) + // printf("setze valid\n"); + flag_slaveagent_value_confident[sa_ix] = true; + } + else { + //if(id == 0) + // printf("setze invalid\n"); + flag_slaveagent_value_confident[sa_ix] = false; + } + } + else { + flag_slaveagent_value_set[sa_ix] = false; + } + } else { + flag_slaveagent_value_set[sa_ix] = false; + } + } + + //TODO: do i need a return value? + return false; +} + +void Agent :: read_all_slaveAgents() { + for(unsigned int sa_ix = 0; sa_ixcross_validate(num_of_mounted_slaveagents, slaveagent_value, &flag_slaveagent_value_confident[0]); + } + } + + + //bunch //TODO: auch f�r integer (slaveagents) + if(flag_bunch_module_exist) { + bunch_score_confidency = bunch_module->bunch(num_of_mounted_slaveagents, &slaveagent_value[0], &flag_slaveagent_value_confident[0], &bunched_score); + //printf("flag_bunched_score_exist setzten - "); + if(bunch_score_confidency > 0) { + flag_bunched_score_exist = true; + //printf("true\n"); + } + else { + flag_bunched_score_exist = false; + //printf("false\n"); + } + } + + + + + + + //abstract data //TODO: auch f�r integer (slaveagents) + for(unsigned int s_ix = 0; s_ixabstract(sensor_value[s_ix], &abstracted_sensor_score[s_ix])) { + flag_abstracted_sensor_score_exist[s_ix] = true; + } + else { + flag_abstracted_sensor_score_exist[s_ix] = false; + } + } + } + } + + //sending data / do specific task + if(flag_masteragent_outputport_is_active) { + for(unsigned int s_ix = 0; s_ixset_msg((int)ISA_SCORE_VALID); + } + else { + mounted_masteragent_outputport->set_msg((int)ISA_SCORE_INVALID); + } + } + else { + mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID); + } + + + + //if(flag_sensor_value_confident || flag_confidence_validator_exist == false) { + // mounted_masteragent_outputport->set_msg((int)IS_SCORE_VALID); + //} + //else { + // mounted_masteragent_outputport->set_msg((int)IS_SCORE_INVALID); + //} + + mounted_masteragent_outputport->set_msg(abstracted_sensor_score[s_ix]); + } + } + } + */ +/*} + + +//TODO: prevent possibility to mount yourself as subagent! +//TODO: prevent possibility to mount sensor as subagent! +bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport) { + if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS && (inputport != NULL || outputport != NULL)) { + for(unsigned int sa_ix=0; sa_ixset_proband(sa_ix); + + num_of_mounted_slaveagents++; + return true; + } + } + } + return false; +} + + + +//TODO: prevent possibility to mount yourself as subagent! +//TODO: prevent possibility to mount subagent as sensor! +bool Agent :: mount_masteragent(Channel* inputport, Channel* outputport) { + if(inputport != NULL || outputport != NULL) { + + if(inputport != NULL) { + mounted_masteragent_inputport = inputport; + flag_masteragent_inputport_is_active = ACTIVE; + } + else { + flag_masteragent_inputport_is_active = INACTIVE; + } + + if(outputport != NULL) { + mounted_masteragent_outputport = outputport; + flag_masteragent_outputport_is_active = ACTIVE; + } + else { + flag_masteragent_outputport_is_active = INACTIVE; + } + + return true; + } + return false; +} + + +bool Agent :: mount_sensor(Channel* inputport, unsigned int position) { + if(position < MAX_NUM_OF_MOUNTED_SENSORS) { + if(flag_sensor_has_dedicated_position[position] == NO && inputport != NULL) { + if(flag_sensor_is_mounted[position] == MOUNTED) { + if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS) { + for(unsigned int s_ix=0; s_ixbunch_module = bunch_module; + this->flag_bunch_module_exist = true; + return true; + } + return false; +} + + +bool Agent :: get_flag_abstracted_sensor_score_exist(unsigned int position) { + return flag_abstracted_sensor_score_exist[position]; +} + +//TODO: r�ckgabewert, wenn kein vern�nftiger wert +int Agent :: get_abstracted_sensor_score(unsigned int position) { + if(position < num_of_mounted_sensors && flag_abstracted_sensor_score_exist[position]) { + return abstracted_sensor_score[position]; + } + return -1; +} + +bool Agent :: get_flag_bunched_score_exist() { + return flag_bunched_score_exist; +} + +int Agent :: get_bunched_score() { + if(flag_bunched_score_exist) { + return bunched_score; + } + return -1; +} + +unsigned int Agent :: get_bunch_score_confidency() { + return bunch_score_confidency; +} + + + + + + +void Agent :: test_print_all_slaveagents() { + + for(int i=0; iname, mounted_slaveagent_inputport[i]->get_name(), i); + } + if(flag_slaveagent_outputport_is_active[i]) { + printf("%s has mounted %s on position %i\n", this->name, mounted_slaveagent_outputport[i]->get_name(), i); + } + } + else { + printf("%s has nothing mounted on position %i\n", this->name, i); + } + } + getchar(); +} + +void Agent :: test_print_all_sensors() { + + for(int i=0; iname, mounted_sensor_inputport[i]->get_name(), i); + } + } + else { + printf("%s has nothing mounted on position %i\n", this->name, i); + } + } + getchar(); +} +*/ diff --git a/Version_Max_07_05_2018_CMake/src/Agent.h b/Version_Max_07_05_2018_CMake/src/Agent.h new file mode 100755 index 0000000..dd0b42d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Agent.h @@ -0,0 +1,208 @@ +#ifndef AGENT_HEADERFILE +#define AGENT_HEADERFILE + +#include "MasterAgentHandlerOfAgent.h" +#include "Node.h" +#include "SensorHandlerOfAgent.h" +#include "SlaveAgentHandlerOfAgent.h" +#include "StateHandler.h" +#include + + +class Agent : public Node { + + private : + SensorHandlerOfAgent* sensorHandlerOfAgent; + SlaveAgentHandlerOfAgent* slaveAgentHandlerOfAgent; + MasterAgentHandlerOfAgent* masterAgentHandlerOfAgent; + + /// Pointer to the stateHandler + StateHandler* stateHandler; + + unsigned int workingCycleCounter; + + void init_agent(); + + public: + Agent(); + Agent(char* name); + + bool set_sensorHandlerOfAgent(); + bool del_sensorHandlerOfAgent(); + SensorHandlerOfAgent* get_sensorHandlerOfAgent(); + + bool set_slaveAgentHandlerOfAgent(); + bool del_slaveAgentHandlerOfAgent(); + SlaveAgentHandlerOfAgent* get_slaveAgentHandlerOfAgent(); + + bool set_masterAgentHandlerOfAgent(); + bool del_masterAgentHandlerOfAgent(); + MasterAgentHandlerOfAgent* get_masterAgentHandlerOfAgent(); + + bool set_stateHandler(); + bool set_stateHandler(StateHandler* stateHandler); + bool del_stateHandler(); + StateHandler* get_stateHandler(); + StateHandler* get_stateHandler2(); + + void trigger(unsigned int cycle); + + bool operator !=(const Agent& a) { + return strcmp(this->name, a.name); + } + + ~Agent(); + /* + private: + + unsigned int working_frequency; + + //master agent + bool flag_masteragent_is_mounted; + Channel* mounted_masteragent_inputport; + Channel* mounted_masteragent_outputport; + bool flag_masteragent_inputport_is_active; + bool flag_masteragent_outputport_is_active; + + + //slave agents + unsigned int num_of_mounted_slaveagents; + bool flag_slaveagent_is_mounted[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + bool flag_slaveagent_has_dedicated_position[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + Channel* mounted_slaveagent_inputport[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + Channel* mounted_slaveagent_outputport[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + bool flag_slaveagent_inputport_is_active[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + bool flag_slaveagent_outputport_is_active[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + + //slaveagent values + int slaveagent_value[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_slaveagent_value_set[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_slaveagent_value_changed[MAX_NUM_OF_MOUNTED_SENSORS]; + + //sensors + unsigned int num_of_mounted_sensors; + bool flag_sensor_is_mounted[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_has_dedicated_position[MAX_NUM_OF_MOUNTED_SENSORS]; + Channel* mounted_sensor_inputport[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_inputport_is_active[MAX_NUM_OF_MOUNTED_SENSORS]; + + //sensor values + float sensor_value[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_value_set[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_value_changed[MAX_NUM_OF_MOUNTED_SENSORS]; + + //sensor history + HistoryModule* sensor_history[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_history_exist[MAX_NUM_OF_MOUNTED_SENSORS]; + + //confidence + bool flag_confidence_validator_exist[MAX_NUM_OF_MOUNTED_SENSORS]; + ConfidenceModule* list_of_confidence_validators[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_sensor_value_confident[MAX_NUM_OF_MOUNTED_SENSORS]; + + bool flag_slaveagent_value_confident[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + + + //abstraction modules + bool flag_abstraction_exist[MAX_NUM_OF_MOUNTED_SENSORS]; + AbstractionModule* list_of_abstractions[MAX_NUM_OF_MOUNTED_SENSORS]; + int abstracted_sensor_score[MAX_NUM_OF_MOUNTED_SENSORS]; + bool flag_abstracted_sensor_score_exist[MAX_NUM_OF_MOUNTED_SENSORS]; + + //bunch module + bool flag_bunch_module_exist; + Bunch_Module* bunch_module; + int bunched_score; + bool flag_bunched_score_exist; + unsigned int bunch_score_confidency; + + //private functions + void initialize_master_slot(); + void initialize_slaveagent_slots(); + void initialize_sensor_slots(); + void initialize_bunch_module(); + void initialize_working_frequency(int* success_indicator); + + //cross confidence + Cross_Confidence_Validator* list_of_ccv_modules[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + bool flag_ccv_module_exist[MAX_NUM_OF_MOUNTED_SLAVEAGENTS]; + + bool read_mountedSensor(unsigned int s_ix); + void read_all_mountedSensors(); + bool save_mountedSensor_history(unsigned int s_ix); + void save_all_mountedSensor_histories(); + bool validate_confidence_of_mountedSensor(unsigned int s_ix); + void validate_confidence_of_all_mountedSensors(); + bool read_slaveAgent(unsigned int sa_ix); + void read_all_slaveAgents(); + + public: + // ----- Standard Attributes ----- + Agent(); + Agent(char* name); + Agent(unsigned int working_frequency, int* success_indicator); + Agent(char* name, unsigned int working_frequency, int* success_indicator); + + bool set_working_frequency(unsigned int working_frequency); + + // ----- Runtime Functions ----- + void trigger(); + + // ----- Setup Subagents ----- + bool mount_slaveagent(Channel* inputport, Channel* outputport); + bool mount_slaveagent(Channel* inputport, Channel* outputport, unsigned int position); + bool mount_slaveagent(Channel* inputport, Channel* outputport, Cross_Confidence_Validator* ccv); + + bool mount_masteragent(Channel* inputport, Channel* outputport); + + + // ----- Setup Mounted Sensors ----- + bool mount_sensor(Channel* inputport); + bool mount_sensor(Channel* inputport, unsigned int position); + bool mount_sensor(Channel* inputport, Abstraction* abstraction); + bool mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator); + bool mount_sensor(Channel* inputport, HistoryModule* historyModule); + bool mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator, Abstraction* abstraction); + + // ----- Bunch Module ----- + bool mount_bunch_module(Bunch_Module* bunch_module); + + + // ----- Setup Abstraction Method ----- + + //bool set_abstraction_method(unsigned int abstraction_method); + //unsigned int get_abstraction_method(); + + + + //void set_agent_id(unsigned int id); + //unsigned int get_agent_id(); + + // ----- Setup Agent ----- + //TODO: DEACTIVATE, ACTIVATE (muss auch in miunt funktion an den Subagent weitergegeben werden) + + void set_active_state_flag(bool flag); + bool get_active_state_flag(); + + void set_master_agent(Agent* agent); + void Agent :: register_as_master_agent(Agent* agent); + void Agent :: deregister_as_master_agent(); + Agent* get_master_agent(); + + bool get_flag_abstracted_sensor_score_exist(unsigned int position); + int get_abstracted_sensor_score(unsigned int position); + + bool get_flag_bunched_score_exist(); + int get_bunched_score(); + + unsigned int get_bunch_score_confidency(); + + + + //test functions + void test_print_all_slaveagents(); + void test_print_all_sensors(); + */ +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.cpp b/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.cpp new file mode 100755 index 0000000..cab1129 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.cpp @@ -0,0 +1,37 @@ +#include "AgentSlotOfTestbench.h" + +#include + +void AgentSlotOfTestbench :: init_agentSlotOfTestbench() { + agent = NULL; +} + +AgentSlotOfTestbench :: AgentSlotOfTestbench() { + init_agentSlotOfTestbench(); +} + + +bool AgentSlotOfTestbench :: set_agent(Agent* agent) { + if(agent != NULL) { + this->agent = agent; + return true; + } + return false; +} + +bool AgentSlotOfTestbench :: del_agent() { + if(agent != NULL) { + agent = NULL; + return true; + } + return false; +} + + +Agent* AgentSlotOfTestbench :: get_agent() { + return agent; +} + +AgentSlotOfTestbench :: ~AgentSlotOfTestbench(){ + del_agent(); +} diff --git a/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.h b/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.h new file mode 100755 index 0000000..d155548 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/AgentSlotOfTestbench.h @@ -0,0 +1,23 @@ +#ifndef AGENTSLOTOFTESTBENCH_HEADERFILE +#define AGENTSLOTOFTESTBENCH_HEADERFILE + +#include "Agent.h" + +class AgentSlotOfTestbench { + + protected: + Agent* agent; + + void init_agentSlotOfTestbench(); + + public: + AgentSlotOfTestbench(); + + bool set_agent(Agent* agent); + bool del_agent(); + Agent* get_agent(); + + ~AgentSlotOfTestbench(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/AverageValue.cpp b/Version_Max_07_05_2018_CMake/src/AverageValue.cpp new file mode 100755 index 0000000..8162c9b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/AverageValue.cpp @@ -0,0 +1,39 @@ +#include "AverageValue.h" + +#include + +AverageValue :: AverageValue() { + resetAverageValue(); +} + +void AverageValue :: resetAverageValue() { + avgValue = 0; + injectedValuesCounter = 0; +} + +void AverageValue ::injectAndCalculateAverageValue(float value) { + if(injectedValuesCounter > 0) { + avgValue = (avgValue*injectedValuesCounter + value) / (injectedValuesCounter + 1); + } + else { + avgValue = value; + } + injectedValuesCounter++; +} + +float AverageValue ::getAverageValue() { + return avgValue; +} + +unsigned int AverageValue :: getInjectedValuesCounter() { + return injectedValuesCounter; +} + +bool AverageValue::averageValueIsValid() { + printf(" ------------------- hier\n"); + if (injectedValuesCounter > 0) { + printf(" --- injVal %u\n", injectedValuesCounter); + return true; + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/AverageValue.h b/Version_Max_07_05_2018_CMake/src/AverageValue.h new file mode 100755 index 0000000..c9935e5 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/AverageValue.h @@ -0,0 +1,23 @@ +#ifndef AVERAGEVALUE_HEADERFILE +#define AVERAGEVALUE_HEADERFILE + +class AverageValue { + +private: + float avgValue; + unsigned int injectedValuesCounter; + +public: + AverageValue(); + + void resetAverageValue(); + + void injectAndCalculateAverageValue(float value); + float getAverageValue(); + + unsigned int getInjectedValuesCounter(); + bool averageValueIsValid(); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Bunch_Module.cpp b/Version_Max_07_05_2018_CMake/src/Bunch_Module.cpp new file mode 100755 index 0000000..a110332 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Bunch_Module.cpp @@ -0,0 +1,66 @@ +#include "Bunch_Module.h" + +#include + +void Bunch_Module :: initialize_bunch_module(unsigned int bunch_method) { + this->bunch_method = bunch_method; +} + +Bunch_Module :: Bunch_Module(unsigned int bunch_method) { + set_name(NO_NAME); + + initialize_bunch_module(bunch_method); +} + +Bunch_Module :: Bunch_Module(char* name, unsigned int bunch_method) { + set_name(name); + + initialize_bunch_module(bunch_method); +} + +//TODO: retrun value bool -> confidecy value => pointer +unsigned int Bunch_Module :: bunch(unsigned int num_of_input, int* input, bool* input_is_valid, int* output) { + + switch(bunch_method) { + + case BUNCH_METHOD_NOT_SPECIFIED: return false; break; + case BUNCH_SIMPLY_ADD: return bunch_simply_add(num_of_input, input, input_is_valid, output); break; + + default: return false; //dummy ... ändern zu bunch interface + } + +} + +unsigned int Bunch_Module :: bunch(unsigned int num_of_input, float* input, bool* input_is_valid, float* output) { + + return false; //dummy +} + +unsigned int Bunch_Module :: bunch_simply_add(unsigned int num_of_input, int* input, bool* input_is_valid, int* output) { + + + //bool data_confident = false; + unsigned int data_confidence_counter = 0; + int result = 0; + + for(unsigned int in_ix=0; in_ixbunch_method = bunch_method; +} + +unsigned int Bunch_Module :: get_bunch_method() { + return bunch_method; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Bunch_Module.h b/Version_Max_07_05_2018_CMake/src/Bunch_Module.h new file mode 100755 index 0000000..fcbd93a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Bunch_Module.h @@ -0,0 +1,34 @@ +#ifndef BUNCH_HEADERFILE +#define BUNCH_HEADERFILE + +#include "Module.h" + +#define BUNCH_METHOD_NOT_SPECIFIED 0 +#define BUNCH_SIMPLY_ADD 1 + +class Bunch_Module : public Module { + + private: + unsigned int bunch_method; + + //private functions + void initialize_bunch_module(unsigned int bunch_method); + //void Bunch_Module :: initialize_bunch_module(unsigned int bunch_method); + + //bunch functions + unsigned int bunch_simply_add(unsigned int num_of_input, int* input, bool* input_is_valid, int* output); + + public: + Bunch_Module(); + Bunch_Module(unsigned int bunch_method); + Bunch_Module(char* name, unsigned int bunch_method); + + unsigned int bunch(unsigned int num_of_input, int* input, bool* input_is_valid, int* output); + unsigned int bunch(unsigned int num_of_input, float* input, bool* input_is_valid, float* output); + + void set_bunch_method(unsigned int bunch_method); + unsigned int get_bunch_method(); +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/CMakeLists.txt b/Version_Max_07_05_2018_CMake/src/CMakeLists.txt new file mode 100755 index 0000000..cc6f9f3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/CMakeLists.txt @@ -0,0 +1,50 @@ +cmake_minimum_required (VERSION 2.6 FATAL_ERROR) +project("CAH-Project") + +if( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR + "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + set(warnings "-Wall -Wextra -Werror") +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + set(warnings "/W4 /WX /EHsc") +endif() + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +set(CMAKE_BUILD_TYPE Debug) + +add_executable(CAH main.cpp +abstraction_functions.cpp MasterAgentSlotOfAgent.cpp +abstraction_interface.cpp MaximumValue.cpp +AbstractionModule.cpp Message.cpp +Agent.cpp minmaxzeug.cpp +AgentSlotOfTestbench.cpp MinumumValue.cpp +attach_modules.cpp Module.cpp +attach_modulesToTestbench.cpp mount_nodes.cpp +AverageValue.cpp Node.cpp +boundary_check.cpp printError.cpp +Bunch_Module.cpp Range.cpp +Channel.cpp register_in_testbench.cpp +ChannelSlotOfTestbench.cpp relationChecker.cpp +clock.cpp Sensor.cpp +ConfidenceModule.cpp SensorHandlerOfAgent.cpp +Continuous_Average.cpp SensorSlotOfAgent.cpp +create_unit.cpp SensorSlotOfTestbench.cpp +Cross_Confidence_Validator.cpp setup_agent.cpp +CSVreaderModule.cpp setup_lookuptable.cpp +CSV_Writer.cpp setupNode.cpp +Discrete_Average.cpp SlaveAgentHandlerOfAgent.cpp +Domain.cpp SlaveAgentSlotOfAgent.cpp +Evaluation.cpp Slot.cpp +extremaValues.cpp SlotOfAgent.cpp +ExtremeValue.cpp State.cpp +HandlerOfAgent.cpp StateHandler.cpp +HistoryEntry.cpp StateModule.cpp +HistoryModule.cpp StateVariable.cpp +inAgentsRegistrations.cpp StatisticValue.cpp +LinearFunctionBlock.cpp SubState.cpp +LinearFunction.cpp Testbench.cpp +Lookuptable.cpp Unit.cpp +user_method_abstraction.cpp Testbench_Config.cpp +MasterAgentHandlerOfAgent.cpp) + + diff --git a/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp b/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp new file mode 100755 index 0000000..c9e4cd2 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp @@ -0,0 +1,100 @@ +#include "CSV_Writer.h" +//#include +//#include + +#define STRINGLENGTH 5000 + +void CSV_Writer :: initialize_csv_writer(const char* filepath_write) { + if(!this->valid_fp) { + fpointer_write = fopen(filepath_write, "w"); + //fopen_s(&fpointer_write, filepath_write, "w"); + + }else { + close_file(); + fpointer_write = fopen(filepath_write, "w"); + } + this->valid_fp = true; +} + +CSV_Writer :: CSV_Writer(char* filepath_write) { + CSV_Writer(NO_NAME, filepath_write); +} + +CSV_Writer :: CSV_Writer(char* name, char* filepath_write) { + this->valid_fp = false; + set_name(name); + initialize_csv_writer(filepath_write); +} + + + +bool CSV_Writer :: write_field(int dataset) { + if(fpointer_write) { + fprintf(fpointer_write, "%i", dataset); + return true; + } + return false; +} + +bool CSV_Writer :: write_field(float dataset) { + if(fpointer_write) { + fprintf(fpointer_write, "%f", dataset); + return true; + } + return false; +} + +bool CSV_Writer :: write_field(char* dataset) { + if(fpointer_write) { + fprintf(fpointer_write, "%s", dataset); + return true; + } + return false; +} + +bool CSV_Writer :: make_new_field() { + if(fpointer_write) { + fprintf(fpointer_write, ","); + return true; + } + return false; +} + +bool CSV_Writer :: make_new_line() { + if(fpointer_write) { + fprintf(fpointer_write, "\n"); + return true; + } + return false; +} + + +bool CSV_Writer :: write_row_data(unsigned int num_of_datasets, float* datasets) { + + if(fpointer_write) { + for(unsigned int d_ix=0; d_ixvalid_fp = false; + } +} + +CSV_Writer :: ~CSV_Writer() +{ + +} diff --git a/Version_Max_07_05_2018_CMake/src/CSV_Writer.h b/Version_Max_07_05_2018_CMake/src/CSV_Writer.h new file mode 100755 index 0000000..03f0d2f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/CSV_Writer.h @@ -0,0 +1,40 @@ +#ifndef CSV_WRITER_HEADERFILE +#define CSV_WRITER_HEADERFILE + +#include "Module.h" +#include +#include + +#define MAX_LENGTH_OF_NAMES_TO_WRITE 50 + +class CSV_Writer : public Module { + + private: + FILE *fpointer_write; + unsigned int num_of_datasets; + float datasets[MAX_NUM_OF_DATA_SETS]; + bool valid_fp; + + void initialize_csv_writer(const char* filepath_write); + + public: + + CSV_Writer(char* filepath_write); + CSV_Writer(char* name, char* filepath_write); + + bool write_field(int dataset); + bool write_field(float dataset); + bool write_field(char* dataset); + bool make_new_field(); + bool make_new_line(); + + bool write_row_data(unsigned int num_of_datasets, float* datasets); + + void reset_fpointer(std::string filepath_write); + + void close_file(); + + ~CSV_Writer(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp new file mode 100755 index 0000000..6705ac2 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp @@ -0,0 +1,217 @@ +#include "CSVreaderModule.h" +#include +#include +#include + +#define STRINGLENGTH 5000 + +/* +void CSV_Reader :: initialize_csvreader(char* filepath_read, unsigned int num_of_datasets, unsigned int* list_of_datasets, unsigned int start_row) { + //fpointer_read = fopen(filepath_read, "r"); + fopen_s(&fpointer_read, filepath_read, "r"); + + this->num_of_datasets = num_of_datasets; + //TODO: sort.. falls es nicht in aufsteigender folge kommt + for(unsigned int d_ix=0; d_ixlist_of_datasets[d_ix] = list_of_datasets[d_ix]; + } + + row = 1; + this->start_row = start_row; +} +*/ + + void CSVreaderModule :: initialize_csvreader(FILE* fpointer, unsigned int column, unsigned int start_row) { + //fpointer_read = fopen(filepath_read, "r"); + + //TODO: file ponter schon aus CSV-Reader Creator Funktion �bergeben.. dann kann man n�mlich ausgeben, wenn da was nicht erstellt werden kann + //bool file_opened = fopen_s(&fpointer_read, filepath_read, "r"); + //TODO: etwas mit flag + + this->fpointer = fpointer; + this->row = 1; + this->column = column; + this->start_row = start_row; + + flag_csv_reader_configured = true; +} + + +/* +CSV_Reader :: CSV_Reader(char* filepath_read, unsigned int num_of_data_sets, unsigned int* list_of_datasets, unsigned int start_row) { + set_name(NO_NAME); + initialize_csvreader(filepath_read, num_of_data_sets, list_of_datasets, start_row); +} + +CSV_Reader :: CSV_Reader(char* name, char* filepath_read, unsigned int num_of_data_sets, unsigned int* list_of_datasets, unsigned int start_row) { + set_name(name); + initialize_csvreader(filepath_read, num_of_data_sets, list_of_datasets, start_row); +} +*/ + +CSVreaderModule :: CSVreaderModule() { + set_name(NO_NAME); + flag_csv_reader_configured = false; +} + +CSVreaderModule :: CSVreaderModule(char* name) { + set_name(name); + flag_csv_reader_configured = false; +} + +CSVreaderModule :: CSVreaderModule(FILE* fpointer, unsigned int column, unsigned int start_row) { + set_name(NO_NAME); + + if(fpointer) { + initialize_csvreader(fpointer, column, start_row); + } + else { + flag_csv_reader_configured = false; + } +} + +CSVreaderModule :: CSVreaderModule(char* name, FILE* fpointer, unsigned int column, unsigned int start_row) { + set_name(name); + + if(fpointer) { + initialize_csvreader(fpointer, column, start_row); + } + else { + flag_csv_reader_configured = false; + } +} +/* +CSV_Reader :: CSV_Reader(char* name, char* filepath_read, int column, int start_row) { + +} +*/ + + + +//XXX: Wird nicht mehr benutzt +//TODO: �berarbeiten nach folgendem Beispiel https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx +bool CSVreaderModule :: read_one_row() { + if(fpointer) + { + char readrow[STRINGLENGTH] = "", electedfield[STRINGLENGTH] = ""; + + //TODO: move following for-loop to "initialize_csvreader(...) + for(;rowrow = row; +} + +void CSVreaderModule:: set_position_fpointer_to_start() +{ + long int cur_pos; + if(this->fpointer) { + cur_pos = ftell(this->fpointer); + rewind(this->fpointer); + } +} + + +//TODO: flag_csv_reader_configured abfragen +void CSVreaderModule :: close_file() { + fclose(fpointer); +} + +CSVreaderModule :: ~CSVreaderModule(){ + if(fpointer) { + close_file(); + } +} diff --git a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h new file mode 100755 index 0000000..2b1ba30 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h @@ -0,0 +1,52 @@ +#ifndef CSV_READER_HEADERFILE +#define CSV_READER_HEADERFILE + +#include "Module.h" +#include + +class CSVreaderModule : public Module { + + private: + FILE *fpointer; + unsigned int num_of_datasets; + unsigned int list_of_datasets[MAX_NUM_OF_DATA_SETS]; + float data_read[MAX_NUM_OF_DATA_SETS]; + unsigned int row, start_row, column; + float input_data; + bool flag_csv_reader_configured; + unsigned int dataset_counter; + + //private fuctions + //void initialize_csvreader(char* filepath_read, unsigned int num_of_datasets, unsigned int* list_of_datasets, unsigned int start_row); + void initialize_csvreader(FILE* fpointer, unsigned int column, unsigned int start_row); + + public: + CSVreaderModule(); + CSVreaderModule(char* name); + CSVreaderModule(FILE* fpointer, unsigned int column, unsigned int start_row); + CSVreaderModule(char* name, FILE* fpointer, unsigned int column, unsigned int start_row); + /* + CSV_Reader(char* filepath_read, unsigned int column, unsigned int start_row); + CSV_Reader(char* name, char* filepath_read, unsigned int column, unsigned int start_row); + */ + + bool read_one_row(); + + + bool read_field(); + float get_value_of_field(unsigned int field); + + + //new functions + bool get_next_value(float* value); + + void reset_row(const int row); + + void set_position_fpointer_to_start(); + + void close_file(); + + ~CSVreaderModule(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Channel.cpp b/Version_Max_07_05_2018_CMake/src/Channel.cpp new file mode 100755 index 0000000..2da808a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Channel.cpp @@ -0,0 +1,346 @@ +#include "Channel.h" +#include + +#define MAX_BUFFER_LENGTH 100 + +void Channel :: init_channel() { + maxBufferLength = MAX_BUFFER_LENGTH; + transferRate = MAX_BUFFER_LENGTH; +} + +Channel :: Channel() { + init_channel(); +} + +Channel :: Channel(char* name) { + set_name(name); + init_channel(); +} + +bool Channel :: set_maxBufferLength(unsigned int maxBufferLength) { + if(maxBufferLength <= MAX_BUFFER_LENGTH) { + this->maxBufferLength = maxBufferLength; + return true; + } + return false; +} + +unsigned int Channel :: get_maxBufferLength() { + return maxBufferLength; +} + +unsigned int Channel :: get_avlInputBufferUp() { + return maxBufferLength-lInputMsgBufferUp.size(); +} + +unsigned int Channel :: get_avlOutputBufferUp() { + return maxBufferLength-lOutputMsgBufferUp.size(); +} + +unsigned int Channel :: get_avlInputBufferDown() { + return maxBufferLength-lInputMsgBufferDown.size(); +} + +unsigned int Channel :: get_avlOutputBufferDown() { + return maxBufferLength-lOutputMsgBufferDown.size(); +} + +bool Channel :: set_transferRate(unsigned int transferRate) { + if(transferRate <= MAX_BUFFER_LENGTH) { + this->transferRate = transferRate; + return true; + } + return false; +} + +unsigned int Channel :: get_transferRate() { + return transferRate; +} + + + +bool Channel :: add_msgAtBegin (list* buffer, Message* message) { + try { + buffer->push_front(message); + } + catch(bad_alloc& error) { + delete message; + return false; + } + return true; +} + +bool Channel :: del_msgAtBegin (list* buffer) { + try { + /* + printf("a\n"); + getchar(); + delete buffer->back(); + printf("b\n"); + getchar(); + */ + Message* first_Message = buffer->front(); + delete first_Message; + buffer->pop_front(); + /* + printf("c\n"); + getchar(); + */ + } + catch(bad_alloc& error) { + return false; + } + return true; +} + +bool Channel :: add_msgAtEnd (list* buffer, Message* message) { + try { + buffer->push_back(message); + } + catch(bad_alloc& error) { + cerr << "bad_alloc caught: " << error.what() << endl; + delete message; + return false; + } + return true; +} + +bool del_msgAtEnd (list* buffer) { + try { + Message* last_Message = buffer->back(); + delete last_Message; + buffer->pop_back(); + } + catch(bad_alloc& error) { + return false; + } + return true; +} + +bool Channel :: send_MsgUp(Message* message) { + if(message != NULL) { + if(transferRate == 0) { + //TODO: at the moment only one packet (in the front) gets deleted if buffer is full. However, the whole message (instruction+value) should be deleted in case of a full buffer + if(lOutputMsgBufferUp.size() == maxBufferLength) { + del_msgAtBegin(&lOutputMsgBufferUp); + } + return add_msgAtEnd(&lOutputMsgBufferUp, message); + } + else { + if(lInputMsgBufferUp.size() == maxBufferLength) { + //TODO: at the moment only one packet (in the front) gets deleted if buffer is full. However, the whole message (instruction+value) should be deleted in case of a full buffer + del_msgAtBegin(&lInputMsgBufferUp); + } + return add_msgAtEnd(&lInputMsgBufferUp, message); + } + } +} + +bool Channel :: send_MsgUp(float msg) { + Message* message = new Message(msg); + return send_MsgUp(message); +} + +bool Channel :: send_MsgUp(int msg) { + Message* message = new Message(msg); + return send_MsgUp(message); +} + +bool Channel :: get_MsgUp(float* msg) { + if(isThereFloatMsgUp()) { + float tempMsg; + if(lOutputMsgBufferUp.front()->getMsg(&tempMsg)) { + *msg = tempMsg; + del_msgAtBegin(&lOutputMsgBufferUp); + return true; + } + } + return false; +} + +bool Channel :: get_MsgUp(int* msg) { + if(isThereIntMsgUp()) { + int tempMsg; + if(lOutputMsgBufferUp.front()->getMsg(&tempMsg)) { + *msg = tempMsg; + del_msgAtBegin(&lOutputMsgBufferUp); + return true; + } + } + return false; +} + +bool Channel :: isThereFloatMsgUp() { + if(lOutputMsgBufferUp.size() > 0 ) { + if(lOutputMsgBufferUp.front() != NULL) { + return lOutputMsgBufferUp.front()->isMsgFloat(); + } + } + return false; +} + +bool Channel :: isThereIntMsgUp() { + if(lOutputMsgBufferUp.size() > 0 ) { + if(lOutputMsgBufferUp.front() != NULL) { + return lOutputMsgBufferUp.front()->isMsgInt(); + } + } + return false; +} + +bool Channel :: send_MsgDown(Message* message) { + if(message != NULL) { + if(transferRate == 0) { + if(lOutputMsgBufferDown.size() == maxBufferLength) { + del_msgAtBegin(&lOutputMsgBufferDown); + } + return add_msgAtEnd(&lOutputMsgBufferDown, message); + } + else { + if(lInputMsgBufferDown.size() == maxBufferLength) { + del_msgAtBegin(&lInputMsgBufferDown); + } + return add_msgAtEnd(&lInputMsgBufferDown, message); + } + } +} + +bool Channel :: send_MsgDown(float msg) { + Message* message = new Message(msg); + return send_MsgDown(message); +} + +bool Channel :: send_MsgDown(int msg) { + Message* message = new Message(msg); + return send_MsgDown(message); +} + +bool Channel :: get_MsgDown(float* msg) { + if(isThereFloatMsgDown()) { + float tempMsg; + if(lOutputMsgBufferDown.front()->getMsg(&tempMsg)) { + *msg = tempMsg; + del_msgAtBegin(&lOutputMsgBufferDown); + return true; + } + } + return false; +} + +bool Channel :: get_MsgDown(int* msg) { + if(isThereIntMsgDown()) { + int tempMsg; + if(lOutputMsgBufferDown.front()->getMsg(&tempMsg)) { + *msg = tempMsg; + del_msgAtBegin(&lOutputMsgBufferDown); + return true; + } + } + return false; +} + +bool Channel :: isThereFloatMsgDown() { + if(lOutputMsgBufferDown.size() > 0 ) { + if(lOutputMsgBufferDown.front() != NULL) { + return lOutputMsgBufferDown.front()->isMsgFloat(); + } + } + return false; +} + +bool Channel :: isThereIntMsgDown() { + if(lOutputMsgBufferDown.size() > 0 ) { + if(lOutputMsgBufferDown.front() != NULL) { + return lOutputMsgBufferDown.front()->isMsgInt(); + } + } + return false; +} + +bool Channel :: transferMsgs(list* dest_buffer, list* src_buffer) { + unsigned int NumOfMsgsToMove; + + if(transferRate <= src_buffer->size()) { + NumOfMsgsToMove = transferRate; + } + else { + NumOfMsgsToMove = src_buffer->size(); + } + + if(NumOfMsgsToMove <= maxBufferLength-dest_buffer->size()) { + for(unsigned int i=0; ifront())) { + if(!del_msgAtBegin(src_buffer)) { + return false; + } + } + else { + return false; + } + } + return true; + } + return false; +} + +bool Channel :: trigger() { + bool flag_worked = transferMsgs(&lOutputMsgBufferUp, &lInputMsgBufferUp) && transferMsgs(&lOutputMsgBufferUp, &lInputMsgBufferUp); + //printf("Channel %s: in_up %u, out_up %u, in_dn %u, out_dn %u,\n", name, lInputMsgBufferUp.size(), lOutputMsgBufferUp.size(), lInputMsgBufferDown.size(), lOutputMsgBufferDown.size()); + return flag_worked; + +} + +bool Channel :: delete_all_InputMsgBufferUp() +{ + Message* cur_Message; + unsigned int cur_index_Message = 0; + unsigned int size_li_Inp_MsgBufUp = lInputMsgBufferUp.size(); + for(cur_index_Message = 0; cur_index_Message < size_li_Inp_MsgBufUp; cur_index_Message){ + cur_Message = lInputMsgBufferUp.front(); + delete cur_Message; + lInputMsgBufferUp.pop_front(); + } + +} + +bool Channel :: delete_all_OuputMsgBufferUp() +{ + Message* cur_Message; + unsigned int cur_index_Message = 0; + unsigned int size_li_Out_MsgBufUp = lOutputMsgBufferUp.size(); + for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufUp; cur_index_Message){ + cur_Message = lOutputMsgBufferUp.front(); + delete cur_Message; + lOutputMsgBufferUp.pop_front(); + } +} +bool Channel :: delete_all_InputMsgBufferDown() +{ + Message* cur_Message; + unsigned int cur_index_Message = 0; + unsigned int size_li_Out_MsgBufDown = lInputMsgBufferDown.size(); + for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message){ + cur_Message = lInputMsgBufferDown.front(); + delete cur_Message; + lInputMsgBufferDown.pop_front(); + } +} +bool Channel :: delete_all_OutputMsgBufferDown() +{ + Message* cur_Message; + unsigned int cur_index_Message = 0; + unsigned int size_li_Out_MsgBufDown = lOutputMsgBufferDown.size(); + for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message){ + cur_Message = lOutputMsgBufferDown.front(); + delete cur_Message; + lOutputMsgBufferDown.pop_front(); + } +} + +Channel :: ~Channel() +{ + delete_all_InputMsgBufferUp(); + delete_all_OuputMsgBufferUp(); + delete_all_InputMsgBufferDown(); + delete_all_OutputMsgBufferDown(); +} diff --git a/Version_Max_07_05_2018_CMake/src/Channel.h b/Version_Max_07_05_2018_CMake/src/Channel.h new file mode 100755 index 0000000..9139038 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Channel.h @@ -0,0 +1,81 @@ +#ifndef CHANNEL_HEADERFILE +#define CHANNEL_HEADERFILE + +#include +#include +#include +#include "Message.h" +#include "Module.h" + + +#define MAX_BUFFER_LENGTH 100 +#define OPEN NULL + +using namespace std; + +class Channel : public Module { + + private: + + list lInputMsgBufferUp; + list lOutputMsgBufferUp; + + list lInputMsgBufferDown; + list lOutputMsgBufferDown; + + unsigned int maxBufferLength; + unsigned int transferRate; + + void init_channel(); + + bool add_msgAtBegin (list* buffer, Message* message); + bool del_msgAtBegin (list* buffer); + + bool add_msgAtEnd (list* buffer, Message* message); + bool del_msgAtEnd (list* buffer); + + bool delete_all_InputMsgBufferUp(); + bool delete_all_OuputMsgBufferUp(); + bool delete_all_InputMsgBufferDown(); + bool delete_all_OutputMsgBufferDown(); + + public: + Channel(); + Channel(char* name); + + bool set_maxBufferLength(unsigned int maxBufferLength); + unsigned int get_maxBufferLength(); + + unsigned int get_avlInputBufferUp(); + unsigned int get_avlOutputBufferUp(); + unsigned int get_avlInputBufferDown(); + unsigned int get_avlOutputBufferDown(); + + bool set_transferRate(unsigned int transferRate); + unsigned int get_transferRate(); + + bool send_MsgUp(Message* message); + bool send_MsgUp(float msg); + bool send_MsgUp(int msg); + bool get_MsgUp(float* msg); + bool get_MsgUp(int* msg); + bool isThereFloatMsgUp(); + bool isThereIntMsgUp(); + + bool send_MsgDown(Message* message); + bool send_MsgDown(float msg); + bool send_MsgDown(int msg); + bool get_MsgDown(float* msg); + bool get_MsgDown(int* msg); + bool isThereFloatMsgDown(); + bool isThereIntMsgDown(); + + bool trigger(); + bool transferMsgs(list* dest_buffer, list* src_buffer); + + ~Channel(); + +}; + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.cpp b/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.cpp new file mode 100755 index 0000000..7a7340a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.cpp @@ -0,0 +1,35 @@ +#include "ChannelSlotOfTestbench.h" + +#include + +void ChannelSlotOfTestbench :: init_channelSlotOfTestbench() { + channel = NULL; +} + +ChannelSlotOfTestbench :: ChannelSlotOfTestbench() { + init_channelSlotOfTestbench(); +} + +bool ChannelSlotOfTestbench :: set_channel(Channel* channel) { + if(channel != NULL) { + this->channel = channel; + return true; + } + return false; +} + +bool ChannelSlotOfTestbench :: del_channel() { + if(channel != NULL) { + channel = NULL; + return true; + } + return false; +} + +Channel* ChannelSlotOfTestbench :: get_channel() { + return channel; +} + +ChannelSlotOfTestbench :: ~ChannelSlotOfTestbench() { + del_channel(); +} diff --git a/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.h b/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.h new file mode 100755 index 0000000..4c14297 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ChannelSlotOfTestbench.h @@ -0,0 +1,23 @@ +#ifndef CHANNELSLOTOFTESTBENCH_HEADERFILE +#define CHANNELSLOTOFTESTBENCH_HEADERFILE + +#include "Channel.h" + +class ChannelSlotOfTestbench { + + protected: + Channel* channel; + + void init_channelSlotOfTestbench(); + + public: + ChannelSlotOfTestbench(); + + bool set_channel(Channel* channel); + bool del_channel(); + Channel* get_channel(); + + ~ChannelSlotOfTestbench(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp new file mode 100755 index 0000000..5d9548a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp @@ -0,0 +1,167 @@ +#include "ConfidenceModule.h" +#include "HistoryModule.h" + +#include + +//TODO: at the moment are only positive rates_of_changes allowed!! +void ConfidenceModule :: initialize_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) { + //plausibility + if(lower_bound <= upper_bound) { + this->lower_bound = lower_bound; + this->upper_bound = upper_bound; + this->flag_lower_bound_exist = flag_lower_bound_exist; + this->flag_upper_bound_exist = flag_upper_bound_exist; + } + else { + this->lower_bound = upper_bound; + this->upper_bound = lower_bound; + this->flag_lower_bound_exist = flag_upper_bound_exist; + this->flag_upper_bound_exist = flag_lower_bound_exist; + } + + //consistency + this->rates_of_change = rates_of_change; + this->flag_rates_of_change_exist = flag_rates_of_change_exist; + flag_value_got_inconsistence = false; + + //TODO: Changes of Other Sensors (e.g. Environment Temperature Sensor) +} + +ConfidenceModule :: ConfidenceModule(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) { + set_name(NO_NAME); + initialize_confidence_validator(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist); +} + + +ConfidenceModule :: ConfidenceModule(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) { + set_name(name); + initialize_confidence_validator(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist); +} + +bool ConfidenceModule :: validate_confidence(float input, HistoryModule* historyModule) { + + bool flag_confidence = true; + + + + //bounds + if(flag_lower_bound_exist && input < lower_bound) { + flag_confidence = false; + //printf("lb\ninput = %f\n", input); + } + + if(flag_upper_bound_exist && input > upper_bound) { + flag_confidence = false; + //printf("ub\n"); + } + + //rates_of_change + float trend_abs; + //TODO: time_unites and time_base should be configurable and saved for the object + unsigned int time_units = 2; + bool got_trend = false; //XXX historyModule->get_history_trend_absolutely(&trend_abs, time_units, TB_SECONDS); + + if(got_trend) { + if(trend_abs > rates_of_change) { + flag_confidence = false; + //printf("trend\n"); + + //VERSUCH + if(flag_value_got_inconsistence == false) { + //printf("setze flag\n"); + flag_value_got_inconsistence = true; + value_before_value_got_inconsistence = 0; //XXX historyModule->get_value_ago(time_units); + } + } + } + else { + //printf("no trend\n"); + } + + if(flag_value_got_inconsistence) { + + //TODO: nicht hardcoded + float seconds = 20; + + //printf("tradition\n"); + + if(input == value_before_value_got_inconsistence) { + flag_value_got_inconsistence = false; + } + else if(input < value_before_value_got_inconsistence) { + if(input >= value_before_value_got_inconsistence-rates_of_change*seconds) { + flag_value_got_inconsistence = false; + } + else { + flag_confidence = false; + } + } + else if(input > value_before_value_got_inconsistence) { + if(input <= value_before_value_got_inconsistence+rates_of_change*seconds) { + flag_value_got_inconsistence = false; + } + else { + flag_confidence = false; + } + } + else { + flag_confidence = false; + } + } + + + confidence = flag_confidence; + return confidence; +} + +bool ConfidenceModule :: get_confidence() { + return confidence; +} + +void ConfidenceModule :: set_lower_bound(float lower_bound) { + this->lower_bound = lower_bound; +} + +float ConfidenceModule :: get_lower_bound() { + return lower_bound; +} + +void ConfidenceModule :: set_flag_lower_bound_exist(bool flag) { + this->flag_lower_bound_exist = flag; +} + +bool ConfidenceModule :: get_flag_lower_bound_exist() { + return flag_lower_bound_exist; +} + +void ConfidenceModule :: set_upper_bound(float upper_bound) { + this->upper_bound = upper_bound; +} + +float ConfidenceModule :: get_upper_bound() { + return upper_bound; +} + +void ConfidenceModule :: set_flag_upper_bound_exist(bool flag) { + this->flag_upper_bound_exist = flag; +} + +bool ConfidenceModule :: get_flag_upper_bound_exist() { + return flag_upper_bound_exist; +} + +void ConfidenceModule :: set_rates_of_change(float rates) { + this->rates_of_change = rates; +} + +float ConfidenceModule :: get_rates_of_change() { + return rates_of_change; +} + +void ConfidenceModule :: set_flag_rates_of_change_exist(bool flag) { + this->flag_rates_of_change_exist = flag; +} + +bool ConfidenceModule :: get_flag_rates_of_change_exist() { + return flag_rates_of_change_exist; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/ConfidenceModule.h b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.h new file mode 100755 index 0000000..2fe4d33 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.h @@ -0,0 +1,56 @@ +#ifndef PLAUSIBILITY_HEADERFILE +#define PLAUSIBILITY_HEADERFILE + +#include "Module.h" +#include "HistoryModule.h" + +class ConfidenceModule : public Module { + + private: + bool confidence; + + //plausibility + float lower_bound, upper_bound; + bool flag_lower_bound_exist, flag_upper_bound_exist; + + //consistency + float rates_of_change; + bool flag_rates_of_change_exist; + float value_before_value_got_inconsistence; + bool flag_value_got_inconsistence; + + + //TODO: Changes of Other Sensors (e.g. Environment Temperature Sensor) + + //private functions + void initialize_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist); + + public: + ConfidenceModule(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist); + ConfidenceModule(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist); + + bool validate_confidence(float input, HistoryModule* historyModule); + bool get_confidence(); + + void set_lower_bound(float lower_bound); + float get_lower_bound(); + + void set_flag_lower_bound_exist(bool flag); + bool get_flag_lower_bound_exist(); + + void set_upper_bound(float upper_bound); + float get_upper_bound(); + + void set_flag_upper_bound_exist(bool flag); + bool get_flag_upper_bound_exist(); + + void set_rates_of_change(float rates); + float get_rates_of_change(); + + void set_flag_rates_of_change_exist(bool flag); + bool get_flag_rates_of_change_exist(); + + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Continuous_Average.cpp b/Version_Max_07_05_2018_CMake/src/Continuous_Average.cpp new file mode 100755 index 0000000..0bf2bf8 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Continuous_Average.cpp @@ -0,0 +1,36 @@ +#include "Continuous_Average.h" + +void Continuous_Average :: init_avg() { + sample_counter = 0; + average = 0.0; +} + +Continuous_Average :: Continuous_Average() { + //set_name(NO_NAME); + init_avg(); +} + +/* +Continuous_Average :: Continuous_Average(char* name) { + set_name(name); + init_avg(); +} +*/ + +void Continuous_Average :: reset() { + init_avg(); +} + +float Continuous_Average :: calc_avg(float sample_value) { + average = (average*sample_counter + sample_value) / (sample_counter + 1); + sample_counter++; + + return average; +} + +float Continuous_Average :: calc_avg(int sample_value) { + average = (average*sample_counter + (float)sample_value) / (sample_counter + 1); + sample_counter++; + + return average; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Continuous_Average.h b/Version_Max_07_05_2018_CMake/src/Continuous_Average.h new file mode 100755 index 0000000..02d7518 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Continuous_Average.h @@ -0,0 +1,26 @@ +#ifndef CON_AVG_HEADERFILE +#define CON_AVG_HEADERFILE + +#include "Unit.h" + +class Continuous_Average : public Unit { + + private: + unsigned int sample_counter; + float average; + + //private functions + void init_avg(); + + public: + Continuous_Average(); + //Continuous_Average(char* name); + + void reset(); + + float calc_avg(float sample_value); + float calc_avg(int sample_value); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.cpp b/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.cpp new file mode 100755 index 0000000..cef87f1 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.cpp @@ -0,0 +1,80 @@ +#include "Cross_Confidence_Validator.h" + +#include + +//TODO: bproband = 0 ??? +void Cross_Confidence_Validator :: initialize_cross_confidence_validator(float percentage_of_inputs_must_be_bad) { + this->percentage_of_inputs_must_be_bad = percentage_of_inputs_must_be_bad; + this->proband = 0; +} + +Cross_Confidence_Validator :: Cross_Confidence_Validator(float percentage_of_inputs_must_be_bad) { + set_name(NO_NAME); + initialize_cross_confidence_validator(percentage_of_inputs_must_be_bad); +} + +Cross_Confidence_Validator :: Cross_Confidence_Validator(char* name, float percentage_of_inputs_must_be_bad) { + set_name(name); + initialize_cross_confidence_validator(percentage_of_inputs_must_be_bad); +} + +//TODO: FEhlerbehandlung nötig? +bool Cross_Confidence_Validator :: set_proband(unsigned int proband) { + this->proband = proband; + + return true; //dummy +} + +//TODO: Fehlerbehandlung, wenn proband > num_of_input +//TODO: dies sollte eine von mehreren möglichkeiten sein +bool Cross_Confidence_Validator :: cross_validate(unsigned int num_of_input, int* input, bool* input_is_valid) { + /* + printf("DRINNEN\n"); + printf("input[proband] = %i, input_is_valid[proband] = %i\n", input[proband], *(input_is_valid+proband)); + */ + + if(input_is_valid[proband] == false) { + //printf("HIER?\n"); + return false; + } + + + + //TODO: kein hardcoded 0 ... könnte ja auch einen schlechten score bedeuten + if(input[proband] != 0) { + unsigned int num_of_valid = 0; + unsigned int num_of_not_perfect = 0; + for(unsigned int in_ix=0; in_ix= percentage_of_inputs_must_be_bad) { + return true; + } else { + return false; + } + } else { + //printf("gib true zurück\n"); + return true; + } + +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.h b/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.h new file mode 100755 index 0000000..c9216dd --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Cross_Confidence_Validator.h @@ -0,0 +1,24 @@ +#ifndef CROSS_CONFIDENCE_VALIDATOR_HEADERFILE +#define CROSS_CONFIDENCE_VALIDATOR_HEADERFILE + +#include "Module.h" + +class Cross_Confidence_Validator : public Module { + + private: + float percentage_of_inputs_must_be_bad; + unsigned int proband; + + //private functions + void initialize_cross_confidence_validator(float percentage_of_inputs_must_be_bad); + + public: + Cross_Confidence_Validator(float percentage_of_inputs_must_be_bad); + Cross_Confidence_Validator(char* name, float percentage_of_inputs_must_be_bad); + + bool set_proband(unsigned int proband); + + bool cross_validate(unsigned int num_of_input, int* input, bool* input_is_valid); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Discrete_Average.cpp b/Version_Max_07_05_2018_CMake/src/Discrete_Average.cpp new file mode 100755 index 0000000..e69de29 diff --git a/Version_Max_07_05_2018_CMake/src/Discrete_Average.h b/Version_Max_07_05_2018_CMake/src/Discrete_Average.h new file mode 100755 index 0000000..256ccf6 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Discrete_Average.h @@ -0,0 +1,26 @@ +#ifndef DIS_AVG_HEADERFILE +#define DIS_AVG_HEADERFILE + +#include "Unit.h" + +class Discrete_Average : public Unit { + + private: + unsigned int sample_counter; + float average; + + //private functions + void init_avg(); + + public: + Discrete_Average(); + + /* + void reset(); + + float calc_avg(float sample_value); + float calc_avg(int sample_value); + */ +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Domain.cpp b/Version_Max_07_05_2018_CMake/src/Domain.cpp new file mode 100755 index 0000000..82b66d0 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Domain.cpp @@ -0,0 +1,60 @@ +#include "Domain.h" + +Domain::Domain() { + this->flagLowerBoundaryExist = false; + this->lowerBoundary = 0; + this->flagUpperBoundaryExist = false; + this->upperBoundary = 0; +} + +void Domain::setLowerBoundary(float lowerBoundary) { + flagLowerBoundaryExist = true; + this->lowerBoundary = lowerBoundary; +} + +void Domain::setUpperBoundary(float upperBoundary) { + flagUpperBoundaryExist = true; + this->upperBoundary = upperBoundary; +} + +void Domain::setBoundaries(float lowerBoundary, float upperBoundary) { + setLowerBoundary(lowerBoundary); + setUpperBoundary(upperBoundary); +} + +void Domain::unsetBoundaries() { + this->flagLowerBoundaryExist = false; + this->flagUpperBoundaryExist = false; +} + +bool Domain::lowerBoundaryExist() { + return flagLowerBoundaryExist; +} + +float Domain::getLowerBoundary() { + return lowerBoundary; +} + +bool Domain::getLowerBoundary(float *lowerBoundary) { + if (flagLowerBoundaryExist) { + *lowerBoundary = this->lowerBoundary; + return true; + } + return false; +} + +bool Domain::upperBoundaryExist() { + return flagUpperBoundaryExist; +} + +float Domain::getUpperBoundary() { + return upperBoundary; +} + +bool Domain::getUpperBoundary(float *upperBoundary) { + if (flagUpperBoundaryExist) { + *upperBoundary = this->upperBoundary; + return true; + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Domain.h b/Version_Max_07_05_2018_CMake/src/Domain.h new file mode 100755 index 0000000..48d3cfd --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Domain.h @@ -0,0 +1,26 @@ +#ifndef DOMAIN_HEADERFILE +#define DOMAIN_HEADERFILE + +class Domain { + +private: + bool flagLowerBoundaryExist, flagUpperBoundaryExist; + float lowerBoundary, upperBoundary; + +public: + Domain(); + + void setLowerBoundary(float lowerBoundary); + void setUpperBoundary(float upperBoundary); + void setBoundaries(float lowerBoundary, float upperBoundary); + void unsetBoundaries(); + bool lowerBoundaryExist(); + float getLowerBoundary(); + bool getLowerBoundary(float *lowerBoundary); + bool upperBoundaryExist(); + float getUpperBoundary(); + bool getUpperBoundary(float *upperBoundary); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Evaluation.cpp b/Version_Max_07_05_2018_CMake/src/Evaluation.cpp new file mode 100755 index 0000000..db0a16e --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Evaluation.cpp @@ -0,0 +1,163 @@ +#include "Evaluation.h" +#include +#include "boundary_check.h" + +Evaluation :: Evaluation() { + +} +Evaluation :: Evaluation(Agent a) { + agent = a; +} + +void Evaluation :: set_agent(Agent a) { + agent = a; +} +Agent Evaluation :: get_agent(){ + return agent; +} + + +//TODO: Timeslot observation +void Evaluation :: evaluate_scores_of_mounted_sensor() { + /* + for(unsigned int s_ix=0; s_ixget_number_of_scores(); + if(sensor->get_flag_use_learned_data()) { + if(is_it_lower_than_boundary(sensor, 0, LOWER_BOUNDARY)) { + for(unsigned int score=1; scoreset_score(score); + break; + } + else { + sensor->set_score(score+1); + } + } + } + else if(is_it_higher_than_boundary(sensor, 0, UPPER_BOUNDARY)) { + for(unsigned int score=1; scoreset_score(score); + break; + } + else { + sensor->set_score(score+1); + } + } + } + else { + sensor->set_score(0); + } + } + else { + if(is_it_lower_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) { + for(unsigned int score=1; scoreset_score(score); + break; + } + else { + sensor->set_score(score+1); + } + } + } + else if(is_it_higher_than_hardcoded_boundary(sensor, 0, UPPER_BOUNDARY)) { + for(unsigned int score=1; scoreset_score(score); + break; + } + else { + sensor->set_score(score+1); + } + } + } + else { + sensor->set_score(0); + } + } + + printf("Sensor %s (mounted on Agent %s) has the value %f, which leads to the Sensor Score %u\n", sensor->get_name(), agent.get_name(), sensor->get_sensor_value(), sensor->get_score()); + } + } + */ +} + + + +//TODO: Timeslot observation +int Evaluation :: evaluate_score_of_Agent() { + /* + float score = 0; + + if(agent.get_score_calculation_way() == ARITHMETIC_MEAN) { + + for(unsigned int s_ix=0; s_ixget_score(); + } + } + for(unsigned int sa_ix=0; sa_ixget_score()); + score += agent.get_mounted_subagent(sa_ix)->get_score(); + } + } + + printf(" < score: %f\n", score); + + score = score / (agent.get_number_of_active_mounted_sensors() + agent.get_number_of_active_mounted_subagents()); + } + + /* + else if(agent->get_score_calculation_way() == GEOMETRIC_MEAN) { + for(unsigned int sensor=0; sensorget_sensor_state(sensor)) { + score *= (agent->get_sensor_scores(sensor)+1); //TODO: is das +1 wirklich ok? + number_of_active_sensors++; + } + } + score = pow(score, 1/number_of_active_sensors) - 1; //und hier das -1...? + } + else if(agent->get_score_calculation_way() == HARMONIC_MEAN) { + for(unsigned int sensor=0; sensorget_sensor_state(sensor)) { + score *= (1 / (agent->get_sensor_scores(sensor)+1)); //TODO: is das +1 wirklich ok? + number_of_active_sensors++; + } + } + score = (number_of_active_sensors / score) - 1; //und hier das -1...? + } + else if(agent->get_score_calculation_way() == WEIGHTED_ARITHMETIC_MEAN) { + for(unsigned int sensor=0; sensorget_sensor_state(sensor) && agent->get_sensor_priority(sensor) > 0.0) { + score += ((agent->get_sensor_scores(sensor) + 1) * agent->get_sensor_priority(sensor)); //TODO: is das +1 wirklich ok? + number_of_active_sensors++; + } + } + score = (score / number_of_active_sensors) - 1; //und hier das -1...? + } + else if(agent->get_score_calculation_way() == WEIGHTED_GEOMETRIC_MEAN) { + + } + else if(agent->get_score_calculation_way() == WEIGHTED_HARMONIC_MEAN) { + + } + + agent->set_agent_score((int)(score+0.5)); + + if(agent->get_agent_score() > agent->get_number_of_agent_scores()) { + agent->set_agent_score(agent->get_number_of_agent_scores()); + } + + printf("Total score of this Agent is: %i\n\n", agent->get_agent_score()); + + + */ + + + //return (int)(score+0.5); + return 1; //dummy zeile +} diff --git a/Version_Max_07_05_2018_CMake/src/Evaluation.h b/Version_Max_07_05_2018_CMake/src/Evaluation.h new file mode 100755 index 0000000..da30547 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Evaluation.h @@ -0,0 +1,22 @@ +#ifndef EVALUATION_HEADERFILE +#define EVALUATION_HEADERFILE + +#include "Agent.h" + +class Evaluation { + + private: + Agent agent; + public: + Evaluation(); + Evaluation(Agent a); + + void set_agent(Agent a); + Agent get_agent(); + + void evaluate_scores_of_mounted_sensor(); + int evaluate_score_of_Agent(); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/ExtremeValue.cpp b/Version_Max_07_05_2018_CMake/src/ExtremeValue.cpp new file mode 100755 index 0000000..fbdb9bc --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ExtremeValue.cpp @@ -0,0 +1,15 @@ +#include "ExtremeValue.h" + +ExtremeValue :: ExtremeValue() { + +} + +void ExtremeValue :: resetExtremeValue() { + resetMinimumValue(); + resetMaximumValue(); +} + +void ExtremeValue :: injectAndCalculateExtremeValue(float value) { + injectAndCalculateMinimumValue(value); + injectAndCalculateMaximumValue(value); +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/ExtremeValue.h b/Version_Max_07_05_2018_CMake/src/ExtremeValue.h new file mode 100755 index 0000000..be7c6c4 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/ExtremeValue.h @@ -0,0 +1,18 @@ +#ifndef EXTREMEVALUE_HEADERFILE +#define EXTREMEVALUE_HEADERFILE + +#include "MinumumValue.h" +#include "MaximumValue.h" + +class ExtremeValue : public MinimumValue, public MaximumValue { + +public: + ExtremeValue(); + + void resetExtremeValue(); + + void injectAndCalculateExtremeValue(float value); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/HandlerOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/HandlerOfAgent.cpp new file mode 100755 index 0000000..e69de29 diff --git a/Version_Max_07_05_2018_CMake/src/HandlerOfAgent.h b/Version_Max_07_05_2018_CMake/src/HandlerOfAgent.h new file mode 100755 index 0000000..d82411f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/HandlerOfAgent.h @@ -0,0 +1,36 @@ +#ifndef HANDLEROFAGENT_HEADERFILE +#define HANDLEROFAGENT_HEADERFILE + +#include " +#include "Unit.h" + +class HandlerOfAgent : public Unit { + + private: + /* + //TODO: set- and get function for maxNumOf_mountedSensors; + vector vMountedSlaveAgents; + unsigned int maxNumOfMountedSlaveAgents; + + void initSlaveAgentHandler(); + */ + + public: + HandlerOfAgent(); + /* + bool attach_historyModule(Channel* inputPort, HistoryModule* historyModule); + bool detach_historyModule(SensorSlotOfAgent* sensorSlotOfAgent); + bool detach_historyModule(Channel* inputPort); + bool detach_historyModule(HistoryModule* historyModule); + HistoryModule* get_historyModuleOfSensorSlot(Channel* inputPort); + + bool attach_confidenceModule(Channel* inputPort, ConfidenceModule* confidenceModule); + bool detach_confidenceModule(SensorSlotOfAgent* sensorSlotOfAgent); + bool detach_confidenceModule(Channel* inputPort); + bool detach_confidenceModule(ConfidenceModule* confidenceModule); + ConfidenceModule* get_confidenceModuleOfSensorSlot(Channel* inputPort); + */ +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Header.h b/Version_Max_07_05_2018_CMake/src/Header.h new file mode 100755 index 0000000..50e9667 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Header.h @@ -0,0 +1 @@ +#pragma once diff --git a/Version_Max_07_05_2018_CMake/src/HistoryEntry.cpp b/Version_Max_07_05_2018_CMake/src/HistoryEntry.cpp new file mode 100755 index 0000000..a1ee383 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/HistoryEntry.cpp @@ -0,0 +1,13 @@ +#include "HistoryEntry.h" + +HistoryEntry :: HistoryEntry() { + +} + +void HistoryEntry :: set_entryValue(float entryValue) { + this->entryValue = entryValue; +} + +float HistoryEntry :: get_entryValue() { + return entryValue; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/HistoryEntry.h b/Version_Max_07_05_2018_CMake/src/HistoryEntry.h new file mode 100755 index 0000000..6e9af53 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/HistoryEntry.h @@ -0,0 +1,19 @@ +#ifndef HISTORYENTRY_HEADERFILE +#define HISTORYENTRY_HEADERFILE + +//TODO: save also time stamp or something similar +class HistoryEntry { + + private: + float entryValue; + + public: + HistoryEntry(); + + void set_entryValue(float entryValue); + float get_entryValue(); + +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp b/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp new file mode 100755 index 0000000..e73291b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp @@ -0,0 +1,442 @@ +#include "HistoryModule.h" +#include "printError.h" +#include + +#define MAX_HIST_LENGTH 1000 + +//using namespace std; + +void HistoryModule :: initHistoryModule() { + if(MAX_HIST_LENGTH <= vHistory.max_size()) { + historyLength = MAX_HIST_LENGTH; + } + else { + historyLength = vHistory.max_size(); + } + + delimitationMode = DELIMITATE_MODE_SRWF; +} + +HistoryModule :: HistoryModule() { + set_name(NO_NAME); + initHistoryModule(); +} + +HistoryModule :: HistoryModule(char* name) { + initHistoryModule(); + set_name(name); +} + +bool HistoryModule :: set_maxHistoryLength(unsigned int length) { + if(length <= MAX_HIST_LENGTH && length <= vHistory.max_size()) { + this->historyLength = historyLength; + return true; + } + return false; +} + +unsigned int HistoryModule :: get_maxHistoryLength() { + return historyLength; +} + +bool HistoryModule :: set_delimitationMode(int delimitationMode) { + if(delimitationMode > DELIMITATE_MODE_LBOUND && delimitationMode < DELIMITATE_MODE_UBOUND) { + this->delimitationMode = delimitationMode; + return true; + } + return false; +} + +int HistoryModule :: get_delimitationMode() { + return delimitationMode; +} + +/* +bool HistoryModule :: add_entry(float entryValue) +{ + if(vHistory.size() <= historyLength) { + HistoryEntry* historyEntry = new HistoryEntry(); + if(historyEntry != NULL) { + historyEntry->set_entryValue(entryValue); + try { + vHistory.push_back(historyEntry); + return true; + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + } + } + else { + printError("Couldn't create HistoryEntry!"); + } + } + else { + switch(delimitationMode) { + case DELIMITATE_MODE_SRWF: + printError("History is already full!"); + break; + default : + printError("History is already full! DelimitationMode isn't set!"); + break; + } + } + return false; +} +*/ + +unsigned int HistoryModule :: get_numberOfEntries() { + return vHistory.size(); +} + + + +/* +void HistoryModule :: initialize_history(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) { + history_occupied = 0; + history_pointer = 0; + + clk_counter = 1; + + if(!set_history_length(history_length)) { + *success_indicator = 1; + } + else if(!set_recording_frequency(recording_frequency)) { + *success_indicator = 2; + } + else if(!set_delimitation_mode(delimitation_mode)) { + *success_indicator = 3; + } + else { + *success_indicator = 0; + } +} + +HistoryModule :: HistoryModule(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) { + set_name(NO_NAME); + initialize_history(history_length, recording_frequency, delimitation_mode, success_indicator); +} + +HistoryModule :: HistoryModule(char* name, unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) { + + set_name(name); + initialize_history(history_length, recording_frequency, delimitation_mode, success_indicator); +} + +bool HistoryModule :: set_history_length(unsigned int history_length) { + if(history_length > 0 && history_length <= MAX_HIST_LENGTH) { + this->history_length = history_length; + return true; + } + this->history_length = 0; + return false; +} + +bool HistoryModule :: set_recording_frequency(unsigned int recording_frequency) { + if(recording_frequency <= MAX_REC_FREQU) { + this->recording_frequency = recording_frequency; + return true; + } + this->recording_frequency = 0; + return false; +} + +bool HistoryModule :: set_delimitation_mode(unsigned int delimitation_mode) { + if(delimitation_mode > DELIMITATE_MODE_LBOUND && delimitation_mode < DELIMITATE_MODE_UBOUND) { + this->delimitation_mode = delimitation_mode; + return true; + } + this->delimitation_mode = HIST_DELIMITATE_MODE_SRWF; + return false; +} + + +void HistoryModule :: carry_on_history_pointer() { + if(history_pointer >= history_length-1) { + history_pointer = 0; + } + else { + history_pointer++; + } +} + +//TODO: namen überarbeiten +bool HistoryModule :: drop_data(float data) { + + if(clk_counter == recording_frequency) { + clk_counter = 1; + return rec_data(data); + } + else { + clk_counter++; + return true; + } + + return false; +} + +bool HistoryModule :: rec_data(float data) { + + if(history_occupied < history_length-1) { + + history[history_pointer] = data; + + carry_on_history_pointer(); + history_occupied++; + + return true; + } + else { + + if(delimitation_mode == HIST_DELIMITATE_MODE_SRWF) { + return false; + } + else if(delimitation_mode == HIST_DELIMITATE_MODE_FIFO) { + history[history_pointer] = data; + carry_on_history_pointer(); + return true; + } + else if(delimitation_mode == HIST_DELIMITATE_MODE_LIFO) { + //TODO: implement! + } + else { + return false; + } + } + + return false; +} + + +bool HistoryModule :: get_latest_value(float* value) { + if(history_occupied > 0) { + if(history_pointer > 0) { + *value = history[history_pointer-1]; + } + else { + *value = history[history_length-1]; + } + return true; + } + + return false; +} + + + + + + + + + + + + + + + + +bool HistoryModule :: smooth_history() { + if(history_occupied > 1) { + + unsigned int calculation_point; + + //TODO: kann man anders verschachteln .. in ein if mit || oder && + if(history_occupied < MAX_HIST_LENGTH-1) { + calculation_point = 0; + } + else { + if(history_pointer < MAX_HIST_LENGTH-1) { + calculation_point = history_pointer; + } + else { + calculation_point = 0; + } + } + + //printf("calculation_point = %u\n", calculation_point); + + for(unsigned int t_ix=0; t_ix<=history_occupied-1; t_ix++) { + + float value, divider; + + if(calculation_point == 0) { + //printf("hier?\n"); + if(history_occupied == MAX_HIST_LENGTH-1) { + //printf("ja!\n"); + value = history[MAX_HIST_LENGTH-1]; + divider = 1; + } + else { + value = 0; + divider = 0; + } + + value = value + 2*history[calculation_point]; + divider = divider + 2; + + //printf("value = %f\ndivider = %f\n", value, divider); + + + //printf("is er da drinnen?\n"); + if(t_ix < history_occupied-1) { + //printf("ja\n"); + value = value + history[calculation_point+1]; + divider = divider + 1; + } + } + + else if(calculation_point == MAX_HIST_LENGTH-1) { + value = history[calculation_point-1] + 2*history[calculation_point]; + divider = 3; + + if(t_ix < history_occupied-1) { + value = value + history[0]; + divider = divider + 1; + } + } + + else { + value = history[calculation_point-1] + 2*history[calculation_point]; + divider = 3; + + //printf("da hoffentlich auch nicht\n"); + if(t_ix < history_occupied-1) { + //printf("doch\n"); + value = value + history[calculation_point+1]; + divider = divider + 1; + } + } + + //printf("value = %f\ndivider = %f\ncalculation_point = %u\n", value, divider, calculation_point); + history_smoothed[t_ix] = value/divider; + + //printf("history_smoothed[%u] = %f\n", t_ix, history_smoothed[t_ix]); + + + if(calculation_point < MAX_HIST_LENGTH-1) { + calculation_point++; + } + else { + calculation_point = 0; + } + } + return true; + } + return false; +} + +//TODO: TO CHECK: small bug when overflow of history array ??? +bool HistoryModule :: get_history_trend(float* trend, unsigned int time_unites, unsigned int time_base) { + /* + float trend_temp, divider; + + bool got_smoothed = smooth_history(); + + if(got_smoothed) { + if(time_unites <= MAX_HIST_LENGTH) { + //TODO: fall wenn andere time base + if(this->time_base == time_base) { + + if(time_unites < history_occupied) { //XXX <= oder < ??? + //printf("a\n"); + trend_temp = history_smoothed[history_occupied-1] - history_smoothed[history_occupied-time_unites]; //xxx -1-time_unites oder nur -time_unites ??? + divider = (float)time_unites; + } + else { + //printf("b\nhistory_smoothed[history_occupied-1] = %f mit history_occupied = %u\nhistory_smoothed[0] = %f\n", history_smoothed[history_occupied-1], history_occupied, history_smoothed[0]); + trend_temp = history_smoothed[history_occupied-1] - history_smoothed[0]; + divider = (float)history_occupied; + //printf("divider = %f\n", divider); + } + + *trend = trend_temp/divider; + //printf("trend = %f\n", *trend); + } + return true; + } + } + */ +/* return false; +} + +bool HistoryModule :: get_history_trend_absolutely(float* trend, unsigned int time_unites, unsigned int time_base) { + float trend_temp; + bool got_trend = get_history_trend(&trend_temp, time_unites, time_base); + + if(got_trend) { + if(trend_temp < 0) { + trend_temp = trend_temp * -1; + } + *trend = trend_temp; + + return true; + } + + return false; +} + +unsigned int HistoryModule :: get_history_occupied() { + return history_occupied; +} + +//TODO: Fehlerbehandlung! +float HistoryModule :: get_value_ago(unsigned int ago) { + + if(history_occupied >= ago) { + if(history_pointer < ago) { + return history[MAX_HIST_LENGTH-(ago-history_pointer)]; //TO CHECK .. auch ein -1 dazu?? + } + else { + return history[history_pointer-ago]; + } + + } else if (history_occupied > 0) { + return history[0]; + } + else { + printf("\n\n\n\n\n\n\nBOESE"); + return 0; + } +} + + + + + + +/* +void History :: set_history(unsigned int point, float value) { + + if(point + +/* +#define MAX_HIST_LENGTH 1000 +#define MAX_REC_FREQU 4294967295 +*/ + +#define DELIMITATE_MODE_LBOUND 0 +#define DELIMITATE_MODE_SRWF 1 //Stop Recording When Full +#define DELIMITATE_MODE_FIFO 2 //First In First Out +#define DELIMITATE_MODE_LIFO 3 //Last In First Out +#define DELIMITATE_MODE_UBOUND 4 + + +using namespace std; + +class HistoryModule : public Module { + + private: + vector vHistory; + unsigned int historyLength; + int delimitationMode; + + void initHistoryModule(); + + public: + HistoryModule(); + HistoryModule(char* name); + + bool set_maxHistoryLength(unsigned int length); + unsigned int get_maxHistoryLength(); + + bool set_delimitationMode(int delimitationMode); + int get_delimitationMode(); + + //bool add_entry(); + + unsigned int get_numberOfEntries(); + + + + + /* + float history[MAX_HIST_LENGTH]; + unsigned int history_length; + unsigned int recording_frequency; + unsigned int delimitation_mode; + + unsigned int history_occupied; + unsigned int history_pointer; + + unsigned int clk_counter; + + + //unsigned int time_base; + + float history_smoothed[MAX_HIST_LENGTH]; + + //private functions + void initialize_history(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator); + void carry_on_history_pointer(); + bool smooth_history(); + + public: + HistoryModule(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator); + HistoryModule(char* name, unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator); + + bool set_history_length(unsigned int history_length); + bool set_recording_frequency(unsigned int recording_frequency); + bool set_delimitation_mode(unsigned int delimitation_mode); + + bool drop_data(float data); + bool rec_data(float data); + + bool get_latest_value(float* value); + + bool get_history_trend(float* trend, unsigned int time_unites, unsigned int time_base); + bool get_history_trend_absolutely(float* trend, unsigned int time_unites, unsigned int time_base); + unsigned int get_history_occupied(); + + float get_value_ago(unsigned int ago); + */ +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunction.cpp b/Version_Max_07_05_2018_CMake/src/LinearFunction.cpp new file mode 100755 index 0000000..5ab91b9 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/LinearFunction.cpp @@ -0,0 +1,99 @@ +#include "LinearFunction.h" + + +LinearFunction::LinearFunction() { + //printf(" > Linear Function created\n"); + LinearFunction("no_name"); +} + +LinearFunction::LinearFunction(const std::string& name) +{ + this->name = name; +} + +//bounded both-sided +Domain* LinearFunction::setDomain(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary) { + if (flagLowerBoundaryExist && flagUpperBoundaryExist && upperBoundary >= lowerBoundary) { + domain.setBoundaries(lowerBoundary, upperBoundary); + //printf("%f - %f\n", domain.getLowerBoundary(), domain.getUpperBoundary()); + return &domain; + } + return NULL; +} + +//bounded below +Domain* LinearFunction::setDomain(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist) { + if (flagLowerBoundaryExist && !flagUpperBoundaryExist) { + domain.setLowerBoundary(lowerBoundary); + //printf("%f - oo\n", domain.getLowerBoundary()); + return &domain; + } + return NULL; +} + +//bounded above +Domain* LinearFunction::setDomain(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary) { + if (!flagLowerBoundaryExist && flagUpperBoundaryExist) { + domain.setUpperBoundary(upperBoundary); + //printf("oo - %f\n", domain.getUpperBoundary()); + return &domain; + } + return NULL; +} + +Domain* LinearFunction::setDomain(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist) { + if (!flagLowerBoundaryExist && !flagUpperBoundaryExist) { + domain.unsetBoundaries(); + return &domain; + } + return NULL; +} + +Domain* LinearFunction::getDomain() { + return &domain; +} + +std::string LinearFunction::getName() +{ + return this->name; +} + +bool LinearFunction::setKandD(float k, float d) { + this->k = k; + this->d = d; + + return true; +} + +bool LinearFunction::setKandD(float x1, float y1, float x2, float y2) { + if (x1 < x2) { + k = (y2 - y1) / (x2 - x1); + } + else if (x2 < x1) { + k = (y1 - y2) / (x1 - x2); + } + else { + k = 1; + d = 0; + return false; + } + + d = y1 - k*x1; + + return true; +} + +float LinearFunction::getK() { + return k; +} + +float LinearFunction::getD() { + return d; +} + +float LinearFunction::getY(float x) { + float y; + y = k*x + d; + + return y; +} diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunction.h b/Version_Max_07_05_2018_CMake/src/LinearFunction.h new file mode 100755 index 0000000..6b8a883 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/LinearFunction.h @@ -0,0 +1,39 @@ +#ifndef LINEARFUNCTION_HEADERFILE +#define LINEARFUNCTION_HEADERFILE + +#include +#include +#include "Domain.h" + +class LinearFunction { + + private: + Domain domain; + float k, d; + std::string name; + + public: + LinearFunction(); + LinearFunction(const std::string& name); + + Domain* setDomain(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist, float upperBoundary); //bounded both-sided + Domain* setDomain(bool flagLowerBoundaryExist, float lowerBoundary, bool flagUpperBoundaryExist); //bounded below + Domain* setDomain(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist, float upperBoundary); //bounded above + Domain* setDomain(bool flagLowerBoundaryExist, bool flagUpperBoundaryExist); + + Domain* getDomain(); + + std::string getName(); + + bool setKandD(float k, float d); + bool setKandD(float x1, float y1, float x2, float y2); + float getK(); + float getD(); + + float getY(float x); +}; + + + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp new file mode 100755 index 0000000..cd8ca6c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp @@ -0,0 +1,96 @@ +#include "LinearFunctionBlock.h" + +LinearFunctionBlock::LinearFunctionBlock() { + printf(" > Linear Function Block created\n"); +} + +LinearFunctionBlock::LinearFunctionBlock(char* name) : Module(name) { + printf(" > %s (id:%u) created\n", name, id); +} + +LinearFunctionBlock::~LinearFunctionBlock() { + LinearFunction* cur_Linear_Function; + unsigned int index_cur_Linear_Function; + unsigned int size_vec_Linear_Functions = vLinearFunctions.size(); + for(index_cur_Linear_Function = 0; index_cur_Linear_Function < size_vec_Linear_Functions; index_cur_Linear_Function++){ + cur_Linear_Function = vLinearFunctions[index_cur_Linear_Function]; + delete cur_Linear_Function; + } + vLinearFunctions.clear(); +} + +//NOTE: for this time being, linear functions have to be filled beginning from lowest x value +bool LinearFunctionBlock::addLinearFunction(LinearFunction *linearFunction) { + if (vLinearFunctions.empty()) { + //printf("empty\n"); + if (!(linearFunction->getDomain()->lowerBoundaryExist())) { + vLinearFunctions.push_back(linearFunction); + printf(" - added function\n"); + return true; + } + } + else + { + //printf("nicht empty\n"); + if (vLinearFunctions.back()->getDomain()->upperBoundaryExist() && linearFunction->getDomain()->lowerBoundaryExist()) { + //printf("last function ub = %f, new function lb = %f\n", lLinearFunctions.back()->getDomain()->getUpperBoundary(), linearFunction->getDomain()->getLowerBoundary()); + if (vLinearFunctions.back()->getDomain()->getUpperBoundary() == linearFunction->getDomain()->getLowerBoundary()) { + vLinearFunctions.push_back(linearFunction); + printf(" - added function\n"); + return true; + } + } + } + + printf(" - couldn't add function\n"); + return false; +} + +//NOTE: Specific Function for CAH Project (DATE18) +void LinearFunctionBlock::changeFunctionBlockIncr(float newBoundary) { + vLinearFunctions[1]->setDomain(true, (float)0, true, newBoundary); + vLinearFunctions[1]->setKandD((float)0, (float)0, newBoundary, (float)1); + vLinearFunctions[2]->setDomain(true, newBoundary, false); +} + +void LinearFunctionBlock::changeFunctionBlockDecr(float newBoundary) { + vLinearFunctions[1]->setDomain(true, (float)0, true, newBoundary); + vLinearFunctions[1]->setKandD((float)0, (float)1, newBoundary, (float)0); + vLinearFunctions[2]->setDomain(true, newBoundary, false); +} + + + +//TODO: jump discontinuity -> user must have the probability to set the value there +float LinearFunctionBlock::getY(float x) { + for (auto &linearFunction : vLinearFunctions) { + if (linearFunction->getDomain()->lowerBoundaryExist() && linearFunction->getDomain()->upperBoundaryExist()) { + if (x >= linearFunction->getDomain()->getLowerBoundary() && x <= linearFunction->getDomain()->getUpperBoundary()) { + return linearFunction->getY(x); + } + } + else if (linearFunction->getDomain()->lowerBoundaryExist()) { + if (x >= linearFunction->getDomain()->getLowerBoundary()) { + return linearFunction->getY(x); + } + } + else if (linearFunction->getDomain()->upperBoundaryExist()) { + if (x <= linearFunction->getDomain()->getUpperBoundary()) { + return linearFunction->getY(x); + } + } + else { + return linearFunction->getY(x); + } + } + + printf("DEFAULT!!!!!!!!!!!\n"); + getchar(); + //TODO: default return value is maybe not the best + return 0; +} + +vector& LinearFunctionBlock::get_all_LinearFunctions() +{ + return vLinearFunctions; +} diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h new file mode 100755 index 0000000..d85d07a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h @@ -0,0 +1,35 @@ +#ifndef LINEARFUNCTIONBLOCK_HEADERFILE +#define LINEARFUNCTIONBLOCK_HEADERFILE + +#include +#include + +#include "LinearFunction.h" +#include "Module.h" +#include "stdio.h" + +using namespace std; + +class LinearFunctionBlock : public Module{ + +private: + //CHECK: list, vector or other container? + vector vLinearFunctions; + +public: + LinearFunctionBlock(); + LinearFunctionBlock(char* name); + ~LinearFunctionBlock(); + + bool addLinearFunction(LinearFunction *linearFunction); + + //NOTE: Specific Function for CAH Project (DATE18) + void changeFunctionBlockIncr(float newBoundary); + void changeFunctionBlockDecr(float newBoundary); + + vector& get_all_LinearFunctions(); + + float getY(float x); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Lookuptable.cpp b/Version_Max_07_05_2018_CMake/src/Lookuptable.cpp new file mode 100755 index 0000000..b65c5a2 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Lookuptable.cpp @@ -0,0 +1,82 @@ +#include "Lookuptable.h" +#include + +Lookuptable :: Lookuptable() { + set_name(NO_NAME); + num_of_ranges = 0; +} + +Lookuptable :: Lookuptable(char* name) { + set_name(name); + num_of_ranges = 0; +} + +bool Lookuptable :: add_range_to_lookuptable(int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included) { + //TODO: possibility of lower_boundary = upper_boundary is maybe needed in one case + if(num_of_ranges < MAX_NUM_OF_RANGES && lower_boundary < upper_boundary) { + + Range range(score, lower_boundary, flag_lower_boundary_included, upper_boundary, flag_upper_boundary_included); + list_of_ranges[num_of_ranges] = range; + + //printf("eigene range %f - %f\n\n", lower_boundary, upper_boundary); + + for(unsigned int r_ix=0; r_ix 0) { + return list_of_ranges[0].check_lut_correctness(num_of_ranges); + } + return false; +} + +bool Lookuptable :: get_lookuptable_is_correct_and_active() { + return lookuptable_is_correct_and_active; +} + +int Lookuptable :: get_score(float input) { + //TODO: WHEN ACTIVATED!? + return list_of_ranges[0].check_belong_to_range(input); +} + +void Lookuptable :: printf_ranges() { + + for(unsigned int i=0; i + +#define MAX_BUFFER_LENGTH_MASTERAGENT_HANDLER 300 + +MasterAgentHandlerOfAgent :: MasterAgentHandlerOfAgent() { + masterAgentSlotOfAgent = NULL; + maxBufferLength = MAX_BUFFER_LENGTH_MASTERAGENT_HANDLER; +} + +bool MasterAgentHandlerOfAgent :: mount_masterAgentIntoSlaveAgentSlot(Channel* comPort) { + masterAgentSlotOfAgent = new MasterAgentSlotOfAgent(); + if(masterAgentSlotOfAgent != NULL) { + if(masterAgentSlotOfAgent->set_comPort(comPort)) { + return true; + } + + } + delete masterAgentSlotOfAgent; + return false; +} + +MasterAgentSlotOfAgent* MasterAgentHandlerOfAgent :: get_masterAgentSlotAddress() { + return masterAgentSlotOfAgent; +} + +bool MasterAgentHandlerOfAgent :: demount_masterAgent() { + if(masterAgentSlotOfAgent != NULL) { + delete masterAgentSlotOfAgent; + masterAgentSlotOfAgent = NULL; + return true; + } + return false; +} + +bool MasterAgentHandlerOfAgent :: set_maxBufferLength(unsigned int maxBufferLength) { + if(maxBufferLength <= MAX_BUFFER_LENGTH_MASTERAGENT_HANDLER) { + this->maxBufferLength = maxBufferLength; + return true; + } + return false; +} + +unsigned int MasterAgentHandlerOfAgent :: get_maxBufferLength() { + return maxBufferLength; +} + +bool MasterAgentHandlerOfAgent :: pass_msgToSendBuffer(float msg) { + //TODO: make message handler and shift following lines to it! + //TODO: try/catch for pushback function! + Message* message = new Message(msg); + lSendBuffer.push_back(message); + return false; +} + +bool MasterAgentHandlerOfAgent :: pass_msgToSendBuffer(int msg) { + //TODO: make message handler and shift following lines to it! + //TODO: try/catch for pushback function! + Message* message = new Message(msg); + lSendBuffer.push_back(message); + return false; +} + +unsigned int MasterAgentHandlerOfAgent :: get_avlSendBuffer() { + return maxBufferLength - get_occSendBuffer(); +} + +unsigned int MasterAgentHandlerOfAgent :: get_occSendBuffer() { + return lSendBuffer.size(); +} + +bool MasterAgentHandlerOfAgent :: send_msgs() { + if(masterAgentSlotOfAgent != NULL) { + Channel* comPort = masterAgentSlotOfAgent->get_comPort(); + if(comPort != NULL) { + //TODO: also other sending mode... current MODE: only send it when all packets can be sended + if(get_occSendBuffer() <= comPort->get_avlInputBufferUp()) { + //for(unsigned int i=0; i 0){ + //TODO: make message handler and shift following lines to it! + //TODO: try/catch for pushback function! + comPort->send_MsgUp(lSendBuffer.front()); + lSendBuffer.pop_front(); + } + } + } + } + return false; +} + +MasterAgentHandlerOfAgent :: ~MasterAgentHandlerOfAgent() +{ + delete masterAgentSlotOfAgent; +} diff --git a/Version_Max_07_05_2018_CMake/src/MasterAgentHandlerOfAgent.h b/Version_Max_07_05_2018_CMake/src/MasterAgentHandlerOfAgent.h new file mode 100755 index 0000000..31956da --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MasterAgentHandlerOfAgent.h @@ -0,0 +1,36 @@ +#ifndef MASTERAGENTHANDLEROFAGENT_HEADERFILE +#define MASTERAGENTHANDLEROFAGENT_HEADERFILE + +#include "MasterAgentSlotOfAgent.h" +#include "Unit.h" + +class MasterAgentHandlerOfAgent : public Unit { + + private: + MasterAgentSlotOfAgent* masterAgentSlotOfAgent; + + list lSendBuffer; + unsigned int maxBufferLength; + + public: + MasterAgentHandlerOfAgent(); + + bool mount_masterAgentIntoSlaveAgentSlot(Channel* comPort); + MasterAgentSlotOfAgent* get_masterAgentSlotAddress(); + bool demount_masterAgent(); + + bool set_maxBufferLength(unsigned int maxBufferLength); + unsigned int get_maxBufferLength(); + + bool pass_msgToSendBuffer(float msg); + bool pass_msgToSendBuffer(int msg); + unsigned int get_avlSendBuffer(); + unsigned int get_occSendBuffer(); + bool send_msgs(); + + ~MasterAgentHandlerOfAgent(); + +}; + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.cpp new file mode 100755 index 0000000..60b461d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.cpp @@ -0,0 +1,5 @@ +#include "MasterAgentSlotOfAgent.h" + +MasterAgentSlotOfAgent :: MasterAgentSlotOfAgent() { + +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h new file mode 100755 index 0000000..dd94ad1 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h @@ -0,0 +1,17 @@ +#ifndef MASTERAGENTSLOTOFAGENT_HEADERFILE +#define MASTERAGENTSLOTOFAGENT_HEADERFILE + +#include "SlotOfAgent.h" + +class MasterAgentSlotOfAgent : public SlotOfAgent { + + private: + MasterAgentSlotOfAgent* masterAgentSlotOfAgent; + + public: + MasterAgentSlotOfAgent(); + +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/MaximumValue.cpp b/Version_Max_07_05_2018_CMake/src/MaximumValue.cpp new file mode 100755 index 0000000..31c8919 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MaximumValue.cpp @@ -0,0 +1,27 @@ +#include "MaximumValue.h" + +MaximumValue ::MaximumValue() { + resetMaximumValue(); +} + +void MaximumValue :: resetMaximumValue() { + flagMaxValueIsSet = false; +} + +void MaximumValue:: injectAndCalculateMaximumValue(float value) { + if (flagMaxValueIsSet == true) { + if (value > maxValue) { + maxValue = value; + } + } + else { + flagMaxValueIsSet = true; + maxValue = value; + } +} + +float MaximumValue:: getMaximumValue() { + return maxValue; +} + + diff --git a/Version_Max_07_05_2018_CMake/src/MaximumValue.h b/Version_Max_07_05_2018_CMake/src/MaximumValue.h new file mode 100755 index 0000000..3f66648 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MaximumValue.h @@ -0,0 +1,19 @@ +#ifndef MAXIMUMVALUE_HEADERFILE +#define MAXIMUMVALUE_HEADERFILE + +class MaximumValue { + +private: + float maxValue; + bool flagMaxValueIsSet; + +public: + MaximumValue(); + + void resetMaximumValue(); + + void injectAndCalculateMaximumValue(float value); + float getMaximumValue(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Message.cpp b/Version_Max_07_05_2018_CMake/src/Message.cpp new file mode 100755 index 0000000..9d0ddae --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Message.cpp @@ -0,0 +1,58 @@ +#include "Message.h" + +#include + +#define MSG_IS_FLOAT true +#define MSG_IS_INT false + +/* +Message :: Message() { + +} +*/ + +Message :: Message(float msg) { + messageType = MSG_IS_FLOAT; + fMsg = msg; +} + +Message :: Message(int msg) { + messageType = MSG_IS_INT; + iMsg = msg; +} + +bool Message :: isMsgFloat() { + if(messageType == MSG_IS_FLOAT) { + return true; + } + + if(messageType == MSG_IS_INT) { + return false; + } + + + return false; +} + +bool Message :: isMsgInt() { + if(messageType == MSG_IS_INT) { + return true; + } + return false; +} + +bool Message :: getMsg(float* msg) { + if(messageType == MSG_IS_FLOAT) { + *msg = fMsg; + return true; + } + return false; +} + +bool Message :: getMsg(int* msg) { + if(messageType == MSG_IS_INT) { + *msg = iMsg; + return true; + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Message.h b/Version_Max_07_05_2018_CMake/src/Message.h new file mode 100755 index 0000000..3030bef --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Message.h @@ -0,0 +1,23 @@ +#ifndef MESSAGE_HEADERFILE +#define MESSAGE_HEADERFILE + +class Message { + + private: + bool messageType; + float fMsg; + int iMsg; + + public: + //Message(); + Message(float msg); + Message(int msg); + + bool isMsgFloat(); + bool isMsgInt(); + + bool getMsg(float* msg); + bool getMsg(int* msg); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/MinumumValue.cpp b/Version_Max_07_05_2018_CMake/src/MinumumValue.cpp new file mode 100755 index 0000000..3317ecf --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MinumumValue.cpp @@ -0,0 +1,25 @@ +#include "MinumumValue.h" + +MinimumValue :: MinimumValue() { + resetMinimumValue(); +} + +void MinimumValue :: resetMinimumValue() { + flagMinValueIsSet = false; +} + +void MinimumValue :: injectAndCalculateMinimumValue(float value) { + if (flagMinValueIsSet == true) { + if (value < minValue) { + minValue = value; + } + } + else { + flagMinValueIsSet = true; + minValue = value; + } +} + +float MinimumValue :: getMinimumValue() { + return minValue; +} diff --git a/Version_Max_07_05_2018_CMake/src/MinumumValue.h b/Version_Max_07_05_2018_CMake/src/MinumumValue.h new file mode 100755 index 0000000..67461c3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/MinumumValue.h @@ -0,0 +1,19 @@ +#ifndef MINIMUMVALUE_HEADERFILE +#define MINIMUMVALUE_HEADERFILE + +class MinimumValue { + +private: + float minValue; + bool flagMinValueIsSet; + +public: + MinimumValue(); + + void resetMinimumValue(); + + void injectAndCalculateMinimumValue(float value); + float getMinimumValue(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Module.cpp b/Version_Max_07_05_2018_CMake/src/Module.cpp new file mode 100755 index 0000000..51c7b1d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Module.cpp @@ -0,0 +1,19 @@ +#include "Module.h" + +Module :: Module() { + set_name(NO_NAME); +} + +Module :: Module(char* name) { + set_name(name); +} + + +void Module :: set_name(char* name) { + strncpy (this->name, name, MAX_LENGTH_NAME); +} + +char* Module :: get_name() { + return this->name; +} + diff --git a/Version_Max_07_05_2018_CMake/src/Module.h b/Version_Max_07_05_2018_CMake/src/Module.h new file mode 100755 index 0000000..0fc0f74 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Module.h @@ -0,0 +1,20 @@ +#ifndef MODULE_HEADERFILE +#define MODULE_HEADERFILE + +#include +#include "Unit.h" + +class Module : public Unit { + + protected: + char name[MAX_LENGTH_NAME]; + + public: + Module(); + Module(char* name); + + void set_name(char* name); + char* get_name(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Node.cpp b/Version_Max_07_05_2018_CMake/src/Node.cpp new file mode 100755 index 0000000..9f24184 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Node.cpp @@ -0,0 +1,20 @@ +#include "Node.h" + +#define MAX_WORKCYCLE 4294967295 + +Node :: Node() { + workingCycle = 1; +} + +bool Node :: set_workingCycle(unsigned int workingCycle) { + if(workingCycle <= MAX_WORKCYCLE) { + this->workingCycle = workingCycle; + return true; + } + return false; +} + +unsigned int Node :: get_workingCycle() { + return workingCycle; +} + diff --git a/Version_Max_07_05_2018_CMake/src/Node.h b/Version_Max_07_05_2018_CMake/src/Node.h new file mode 100755 index 0000000..b6591b6 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Node.h @@ -0,0 +1,23 @@ +#ifndef NODE_HEADERFILE +#define NODE_HEADERFILE + +#include "Module.h" + +#define ACTIVATED true +#define DEACTIVATED false + +class Node : public Module { + + private: + unsigned int workingCycle; + + public: + Node(); + + bool set_workingCycle(unsigned int workingCycle); + unsigned int get_workingCycle(); + +}; + +#endif + diff --git a/Version_Max_07_05_2018_CMake/src/Range.cpp b/Version_Max_07_05_2018_CMake/src/Range.cpp new file mode 100755 index 0000000..47f342b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Range.cpp @@ -0,0 +1,224 @@ +#include "Range.h" +#include + +unsigned int Range :: range_counter; + +Range :: Range() { + range_below = nullptr; + range_upon = nullptr; + + lower_boundary_included = false; + upper_boundary_included = false; +} + +Range :: Range(int score, float lower_boundary, bool lower_boundary_included, float upper_boundary, bool upper_boundary_included) { + range_below = nullptr; + range_upon = nullptr; + + this->score = score; + + this->lower_boundary = lower_boundary; + this->lower_boundary_included = lower_boundary_included; + this->upper_boundary = upper_boundary; + this->upper_boundary_included = upper_boundary_included; +} + +void Range :: set_score(int score) { + this->score = score; +} + +int Range :: get_score() { + return score; +} + +void Range :: set_range_below(Range* range_below) { + this->range_below = range_below; +} + +Range* Range :: get_range_below() { + return range_below; +} + +void Range :: set_range_upon(Range* range_upon) { + this->range_upon = range_upon; +} + +Range* Range :: get_range_upon() { + return range_upon; +} + +void Range :: set_lower_boundary(float lower_boundary){ + this->lower_boundary = lower_boundary; +} + +float Range :: get_lower_boundary(){ + return lower_boundary; +} + +void Range :: set_upper_boundary(float upper_boundary){ + this->upper_boundary = upper_boundary; +} + +float Range :: get_upper_boundary(){ + return upper_boundary; +} + +void Range :: set_lower_boundary_included(bool lower_boundary_included){ + this->lower_boundary_included = lower_boundary_included; +} + +bool Range :: get_lower_boundary_included(){ + return lower_boundary_included; +} + +void Range :: set_upper_boundary_included(bool upper_boundary_included){ + this->upper_boundary_included = upper_boundary_included; +} + +bool Range :: get_upper_boundary_included(){ + return upper_boundary_included; +} + +bool Range :: check_lut_correctness(unsigned int num_of_ranges) { + bool path_down_correct = true; + bool path_up_correct = true; + range_counter = 1; + + if(range_below != nullptr) { + path_down_correct = range_below->check_lut_correctness_down(); + } + + if(range_upon != nullptr) { + path_up_correct = range_upon->check_lut_correctness_up(); + } + + if(path_down_correct && path_up_correct && range_counter == num_of_ranges) { + return true; + } + //printf("da is er durchgebrunst\npath_down_correct = %i\npath_up_correct = %i\nnum_of_ranges = %u\nrange_counter=%u\n", path_down_correct, path_up_correct, num_of_ranges, range_counter); + + return false; +} + +bool Range :: check_lut_correctness_down() { + range_counter++; + //printf("down count = %u\n", range_counter); + if(range_below == nullptr) { + return true; + } + else { + if(lower_boundary != range_below->get_upper_boundary() || lower_boundary_included == range_below->get_upper_boundary_included()) { + printf("jetzt false _ down"); + return false; + } + else { + return range_below->check_lut_correctness_down(); + } + } +} + +bool Range :: check_lut_correctness_up() { + range_counter++; + //printf("up count = %u\n", range_counter); + if(range_upon == nullptr) { + return true; + } + else { + if(upper_boundary != range_upon->get_lower_boundary() || upper_boundary_included == range_upon->get_lower_boundary_included()) { + printf("jetzt false _ up"); + return false; + } + else { + return range_upon->check_lut_correctness_up(); + } + } +} + +int Range :: check_belong_to_range(float input) { + if(range_below == nullptr && range_upon == nullptr) { + return score; + } + else if(range_below == nullptr) { + if(upper_boundary_included) { + if(input <= upper_boundary) { + return score; + } + else { + return range_upon->check_belong_to_range(input); + } + } + else { + if(input < upper_boundary) { + return score; + } + else { + return range_upon->check_belong_to_range(input); + } + } + } + else if(range_upon == nullptr) { + if(lower_boundary_included) { + if(input >= lower_boundary) { + return score; + } + else { + return range_below->check_belong_to_range(input); + } + } + else { + if(input > lower_boundary) { + return score; + } + else { + return range_below->check_belong_to_range(input); + } + } + } + else { + if(lower_boundary_included && upper_boundary_included) { + + if(input < lower_boundary) { + return range_below->check_belong_to_range(input); + } + else if(input > upper_boundary) { + return range_upon->check_belong_to_range(input); + } + else { + return score; + } + } + else if(lower_boundary_included) { + if(input < lower_boundary) { + return range_below->check_belong_to_range(input); + } + else if(input >= upper_boundary) { + return range_upon->check_belong_to_range(input); + } + else { + return score; + } + } + else if(upper_boundary_included) { + if(input <= lower_boundary) { + return range_below->check_belong_to_range(input); + } + else if(input > upper_boundary) { + return range_upon->check_belong_to_range(input); + } + else { + return score; + } + } + else { + if(input <= lower_boundary) { + return range_below->check_belong_to_range(input); + } + else if(input >= upper_boundary) { + return range_upon->check_belong_to_range(input); + } + else { + return score; + } + } + } +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Range.h b/Version_Max_07_05_2018_CMake/src/Range.h new file mode 100755 index 0000000..cbf4616 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Range.h @@ -0,0 +1,50 @@ +#ifndef RANGE_HEADERFILE +#define RANGE_HEADERFILE + +class Range { + + private: + int score; + Range* range_below; + Range* range_upon; + float lower_boundary; + float upper_boundary; + bool lower_boundary_included; + bool upper_boundary_included; + + static unsigned int range_counter; + + + public: + Range(); + Range(int score, float lower_boundary, bool lower_boundary_included, float upper_boundary, bool upper_boundary_included); + + void set_score(int score); + int get_score(); + + void set_range_below(Range* range_below); + Range* get_range_below(); + + void set_range_upon(Range* range_upon); + Range* get_range_upon(); + + void set_lower_boundary(float lower_boundary); + float get_lower_boundary(); + + void set_upper_boundary(float upper_boundary); + float get_upper_boundary(); + + void set_lower_boundary_included(bool lower_boundary_included); + bool get_lower_boundary_included(); + + void set_upper_boundary_included(bool upper_boundary_included); + bool get_upper_boundary_included(); + + bool check_lut_correctness(unsigned int num_of_ranges); + bool check_lut_correctness_down(); + bool check_lut_correctness_up(); + + int check_belong_to_range(float input); +}; + +#endif \ No newline at end of file diff --git "a/Version_Max_07_05_2018_CMake/src/Readme_\303\204nderungen.txt" "b/Version_Max_07_05_2018_CMake/src/Readme_\303\204nderungen.txt" new file mode 100755 index 0000000..9e114e0 --- /dev/null +++ "b/Version_Max_07_05_2018_CMake/src/Readme_\303\204nderungen.txt" @@ -0,0 +1,11 @@ +Änderungen um Sourcecode zum Rennen zu bekommen: + +Auskommentiert: +Datei: rlutil.h +Zeile 603 MultiByteToWideChar(CP_ACP, 0, str_temp, -1, str, 4096); //Add this line + + +Geändert: +Datei: Module.cpp +Zeile 14 strncpy_s (this->name, name, MAX_LENGTH_NAME); zu +strncpy (this->name, name, MAX_LENGTH_NAME); da strncpy_s auf ubuntu nicht vorhanden ist. \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Sensor.cpp b/Version_Max_07_05_2018_CMake/src/Sensor.cpp new file mode 100755 index 0000000..ba89188 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Sensor.cpp @@ -0,0 +1,166 @@ +#include "Sensor.h" +#include + +//unsigned int Sensor :: number_of_sensors = 0; + +void Sensor :: initialize_sensor() { + this->flag_masteragent_is_mounted = UNMOUNTED; + this->flag_masteragent_outputport_is_active = INACTIVE; + this->flag_sensor_value_is_valid = INVALID; + this->flag_sensor_value_has_changed = NO; + this->flag_send_value_only_when_changed = NO; + + workingCycleCounter = 1; +} + +Sensor :: Sensor() { + set_name(NO_NAME); + initialize_sensor(); +} + +Sensor :: Sensor(char* name) { + set_name(name); + initialize_sensor(); +} + + +// ----- Runtime Functions ----- +void Sensor :: set_sensorValue(float sensor_value) { + if(this->sensor_value != sensor_value) { + flag_sensor_value_has_changed = YES; + } + flag_sensor_value_is_valid = VALID; + this->sensor_value = sensor_value; + + //printf("Sensor %s updated with: %f\n", name, sensor_value); +} + +float Sensor :: get_sensorValue() { + return sensor_value; +} + +void Sensor :: trigger() { + if (workingCycleCounter == 1) { + //TODO: difference int and float + if(this->flag_sensor_value_is_valid && this->flag_masteragent_is_mounted && this->flag_masteragent_outputport_is_active){ + if(flag_send_value_only_when_changed) { + if(flag_sensor_value_has_changed) { + mounted_masteragent_outputport->send_MsgUp(sensor_value); + flag_sensor_value_has_changed = NO; + } + } + else { + mounted_masteragent_outputport->send_MsgUp(sensor_value); + flag_sensor_value_has_changed = NO; + } + } + } + + if (workingCycleCounter < get_workingCycle()) + workingCycleCounter++; + else + workingCycleCounter = 1; +} + + +// ----- Setup Functions ----- +bool Sensor :: mount_agent(Channel* outputport) { + if(outputport != NULL) { + this->mounted_masteragent_outputport = outputport; + this->flag_masteragent_is_mounted = MOUNTED; + this->flag_masteragent_outputport_is_active = ACTIVE; + return true; + } + return false; +} + +void Sensor :: set_flag_send_value_only_when_changed(bool flag_send_value_only_when_changed) { + this->flag_send_value_only_when_changed = flag_send_value_only_when_changed; +} + +bool Sensor :: get_flag_send_value_only_when_changed() { + return this->flag_send_value_only_when_changed; +} + +// ----- set/get ----- +void Sensor :: set_flag_sensor_value_is_valid(bool flag_sensor_value_is_valid) { + this->flag_sensor_value_is_valid = flag_sensor_value_is_valid; +} + +bool Sensor :: get_flag_sensor_value_is_valid() { + return this->flag_sensor_value_is_valid; +} + +void Sensor :: set_flag_sensor_value_has_changed(bool flag_sensor_value_has_changed) { + this->flag_sensor_value_has_changed = flag_sensor_value_has_changed; +} + +bool Sensor :: get_flag_sensor_value_has_changed() { + return this->flag_sensor_value_has_changed; +} + + + + + + + + + + + + + + +/* +void Sensor :: set_sensor_id(unsigned int id) { + sensor_id = id; +} +unsigned int Sensor :: get_sensor_id() { + return sensor_id; +}*/ + + + +void Sensor :: set_active_state_flag(bool flag) { + active_state_flag = flag; +} +bool Sensor :: get_active_state_flag() { + return active_state_flag; +} + +/* +void Sensor :: set_number_of_scores (unsigned int number) { + number_of_scores = number; +} +unsigned int Sensor :: get_number_of_scores() { + return number_of_scores; +} +*/ +float Sensor :: get_hardcoded_threshold(unsigned int score, unsigned int boundary) { + return hardcoded_thresholds[score][boundary]; +} +void Sensor :: set_hardcoded_threshold(unsigned int score, unsigned int boundary, float value) { + hardcoded_thresholds[score][boundary] = value; +} + +float Sensor :: get_learned_threshold(unsigned int score, unsigned int boundary) { + return learned_thresholds[score][boundary]; +} +void Sensor :: set_learned_threshold(unsigned int score, unsigned int boundary, float value) { + learned_thresholds[score][boundary] = value; +} + +void Sensor :: set_flag_learned_boundary_exist(unsigned int score, unsigned int boundary, bool flag) { + flag_learned_boundary_exist[score][boundary] = flag; +} +bool Sensor :: get_flag_learned_boundary_exist(unsigned int score, unsigned int boundary) { + return flag_learned_boundary_exist[score][boundary]; +} + +void Sensor :: set_flag_use_learned_data(bool flag) { + flag_use_learned_data = flag; +} +bool Sensor :: get_flag_use_learned_data() { + return flag_use_learned_data; +} diff --git a/Version_Max_07_05_2018_CMake/src/Sensor.h b/Version_Max_07_05_2018_CMake/src/Sensor.h new file mode 100755 index 0000000..5619d3d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Sensor.h @@ -0,0 +1,119 @@ +#ifndef SENSOR_HEADERFILE +#define SENSOR_HEADERFILE + +#include "project_settings.h" +#include "Node.h" +#include "Channel.h" + +#define MAX_NUM_OF_SCORES 10 + +#define LOWER_BOUNDARY 0 +#define UPPER_BOUNDARY 1 + +#define LEARNED_BOUNDARY_DOES_EXIST true +#define LEARNED_BOUNDARY_DOESNT_EXIST false + +#define USE_LEARNED_DATA true +#define DONT_USE_LEARNED_DATA false + +#define VALID true +#define INVALID false + +class Sensor : public Node { + + private: + + // ----- Runtime ----- + float sensor_value; + bool flag_sensor_value_is_valid; + bool flag_sensor_value_has_changed; + + + // ----- Setup Master ----- + bool flag_masteragent_is_mounted; + Channel* mounted_masteragent_outputport; + bool flag_masteragent_outputport_is_active; //unnötig? + + // ----- Setup Behavior ----- + bool flag_send_value_only_when_changed; + + unsigned int workingCycleCounter; + + + //noch nicht überarbeitet + bool active_state_flag; + + float hardcoded_thresholds[MAX_NUM_OF_SCORES][2]; + float learned_thresholds[MAX_NUM_OF_SCORES][2]; + bool flag_learned_boundary_exist[MAX_NUM_OF_SCORES][2]; + + bool flag_use_learned_data; + + + + void initialize_sensor(); + + + public: + Sensor(); + Sensor(char* name); + + // ----- Runtime Functions ----- + void set_sensorValue(float sensor_value); + float get_sensorValue(); + void trigger(); + + // ----- Setup ----- + bool mount_agent(Channel* outputport); + + void set_flag_send_value_only_when_changed(bool flag_send_value_only_when_changed); + bool get_flag_send_value_only_when_changed(); + + + + + /* + void set_sensor_id(unsigned int id); + unsigned int get_sensor_id(); + */ + + // ----- set/get ----- + void set_flag_sensor_value_is_valid(bool flag_sensor_value_is_valid); + bool get_flag_sensor_value_is_valid(); + void set_flag_sensor_value_has_changed(bool flag_sensor_value_has_changed); + bool get_flag_sensor_value_has_changed(); + + + + + + + + + + + + + + + + + + void set_active_state_flag(bool flag); + bool get_active_state_flag(); + + float get_hardcoded_threshold(unsigned int score, unsigned int boundary); + void set_hardcoded_threshold(unsigned int score, unsigned int boundary, float value); + + float get_learned_threshold(unsigned int score, unsigned int boundary); + void set_learned_threshold(unsigned int score, unsigned int boundary, float value); + + void set_flag_learned_boundary_exist(unsigned int score, unsigned int boundary, bool flag); + bool get_flag_learned_boundary_exist(unsigned int score, unsigned int boundary); + + void set_flag_use_learned_data(bool flag); + bool get_flag_use_learned_data(); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.cpp new file mode 100755 index 0000000..81f48da --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.cpp @@ -0,0 +1,207 @@ +#include "SensorHandlerOfAgent.h" +#include +#include "printError.h" + +#include + +#define MAXNUMOF_MOUNTEDSENSORS 100 + +using namespace std; + +SensorHandlerOfAgent :: SensorHandlerOfAgent() { + init_sensorHandler(); +} + +void SensorHandlerOfAgent :: init_sensorHandler() { + maxNumOf_mountedSensors = MAXNUMOF_MOUNTEDSENSORS; +} + +//TODO: if(vMountedSensors.size() < maxNumOf_mountedSensors) als aller erste Abfrage machen ... noch bevor "SensorSlotOfAgent* sensorSlotOfAgent = new SensorSlotOfAgent();" +//TODO: delete object if it cannot added to vector +bool SensorHandlerOfAgent :: mount_sensorIntoSensorSlot(Channel* inputPort) { + SensorSlotOfAgent* sensorSlotOfAgent = new SensorSlotOfAgent(); + if(sensorSlotOfAgent != NULL) { + if(sensorSlotOfAgent->set_comPort(inputPort)) { + try { + if(vMountedSensors.size() < maxNumOf_mountedSensors) { + vMountedSensors.push_back(sensorSlotOfAgent); + } + else { + printError("Max number of mounted sensors is already reached!"); + + return false; + } + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + return false; + } + return true; + } + else { + printError("Input port is no set!"); + vMountedSensors.pop_back(); //TODO: check if it is right?!?! + + return false; + } + } + else { + printError("Couldn't create SensorSlot!"); + + return false; + } +} + +//TODO: what to do when 2 sensorSlots have the same inputPort??!! +SensorSlotOfAgent* SensorHandlerOfAgent :: get_sensorSlotAddress(Channel* inputPort) { + for(auto &sensorSlot : vMountedSensors) { + if(sensorSlot->get_comPort() == inputPort) { + return sensorSlot; + } + } + return NULL; +} + +//TODO: what to do when 2 slaveAgentSlots have the same inputPort??!! +//TODO: case if slot with comPort is not in this vector +unsigned int SensorHandlerOfAgent :: get_sensorSlotNumber(Channel* inputPort) { + unsigned int slotNumber = 0; + for(auto &sensorSlot : vMountedSensors) { + if(sensorSlot->get_comPort() == inputPort) { + return slotNumber; + } + slotNumber++; + } + return NULL; +} + +//TODO: what to do when 2 sensorSlots have the same historyModule??!! +SensorSlotOfAgent* SensorHandlerOfAgent :: get_sensorSlotAddress(HistoryModule* historyModule) { + for(auto &sensorSlot : vMountedSensors) { + if(sensorSlot->get_historyModule() == historyModule) { + return sensorSlot; + } + } + return NULL; +} + +//TODO: what to do when 2 sensorSlots have the same confidenceModule??!! +SensorSlotOfAgent* SensorHandlerOfAgent :: get_sensorSlotAddress(ConfidenceModule* confidenceModule) { + for(auto &sensorSlot : vMountedSensors) { + if(sensorSlot->get_confidenceModule() == confidenceModule) { + return sensorSlot; + } + } + return NULL; +} + +bool SensorHandlerOfAgent :: demount_sensor(Channel* inputPort) { + vMountedSensors.erase(vMountedSensors.begin() + get_sensorSlotNumber(inputPort)); + return false; +} + +//TODO: do it also for integer variables +bool SensorHandlerOfAgent :: read_sensorValue(SensorSlotOfAgent* sensorSlotOfAgent) { + if(sensorSlotOfAgent != NULL) { + Channel* channel = sensorSlotOfAgent->get_comPort(); + if(channel != NULL) { + float inputValue; + if(channel->get_MsgUp(&inputValue)) { + sensorSlotOfAgent->set_sensorValue(inputValue); + return true; + } + } + } + return false; +} + +bool SensorHandlerOfAgent :: read_allSensorValues() { + bool flag_readSensor = false; + for(auto &sensorSlot : vMountedSensors) { + if(read_sensorValue(sensorSlot)) { + flag_readSensor = true; + } + } + return flag_readSensor; +} + +bool SensorHandlerOfAgent :: attach_historyModule(Channel* inputPort, HistoryModule* historyModule) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + if(sensorSlotOfAgent != NULL) { + return sensorSlotOfAgent->set_historyModule(historyModule); + } + return false; +} + +bool SensorHandlerOfAgent :: detach_historyModule(SensorSlotOfAgent* sensorSlotOfAgent) { + if(sensorSlotOfAgent != NULL) { + return sensorSlotOfAgent->del_historyModule(); + } + return false; +} + +bool SensorHandlerOfAgent :: detach_historyModule(Channel* inputPort) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + return detach_historyModule(sensorSlotOfAgent); +} + +bool SensorHandlerOfAgent :: detach_historyModule(HistoryModule* historyModule) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(historyModule); + return detach_historyModule(sensorSlotOfAgent); +} + +HistoryModule* SensorHandlerOfAgent :: get_historyModuleOfSensorSlot(Channel* inputPort) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + return sensorSlotOfAgent->get_historyModule(); +} + +bool SensorHandlerOfAgent :: attach_confidenceModule(Channel* inputPort, ConfidenceModule* confidenceModule) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + if(sensorSlotOfAgent != NULL) { + return sensorSlotOfAgent->set_confidenceModule(confidenceModule); + } + return false; +} + +bool SensorHandlerOfAgent :: detach_confidenceModule(SensorSlotOfAgent* sensorSlotOfAgent) { + if(sensorSlotOfAgent != NULL) { + return sensorSlotOfAgent->del_confidenceModule(); + } + return false; +} + +bool SensorHandlerOfAgent :: detach_confidenceModule(Channel* inputPort) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + return detach_confidenceModule(sensorSlotOfAgent); +} + +bool SensorHandlerOfAgent :: detach_confidenceModule(ConfidenceModule* confidenceModule) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(confidenceModule); + return detach_confidenceModule(sensorSlotOfAgent); +} + +ConfidenceModule* SensorHandlerOfAgent :: get_confidenceModuleOfSensorSlot(Channel* inputPort) { + SensorSlotOfAgent* sensorSlotOfAgent = get_sensorSlotAddress(inputPort); + return sensorSlotOfAgent->get_confidenceModule(); +} + +vector* SensorHandlerOfAgent :: get_vMountedSensors() { + return &vMountedSensors; +} + +void SensorHandlerOfAgent :: delete_all_Mounted_Sensors() +{ + SensorSlotOfAgent* cur_Sensor_Slot_Agent; + unsigned int index_cur_Sen_Slo_Ag; + unsigned int size_vec_Mount_Sensors = vMountedSensors.size(); + for(index_cur_Sen_Slo_Ag = 0; index_cur_Sen_Slo_Ag < size_vec_Mount_Sensors; index_cur_Sen_Slo_Ag++){ + cur_Sensor_Slot_Agent = vMountedSensors[index_cur_Sen_Slo_Ag]; + delete cur_Sensor_Slot_Agent; + } + vMountedSensors.clear(); +} + +SensorHandlerOfAgent :: ~SensorHandlerOfAgent() +{ + delete_all_Mounted_Sensors(); +} diff --git a/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.h b/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.h new file mode 100755 index 0000000..f1276b3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorHandlerOfAgent.h @@ -0,0 +1,56 @@ +#ifndef SENSORHANDLEROFAGENT_HEADERFILE +#define SENSORHANDLEROFAGENT_HEADERFILE + +#include +#include "Unit.h" +//#include "Agent.h" +#include "SensorSlotOfAgent.h" + +using namespace std; + +class SensorHandlerOfAgent : public Unit { + + private: + //TODO: set- and get function for maxNumOf_mountedSensors; + vector vMountedSensors; + unsigned int maxNumOf_mountedSensors; + + void init_sensorHandler(); + + void delete_all_Mounted_Sensors(); + + public: + SensorHandlerOfAgent(); + //SensorHandler(char* name); + + bool mount_sensorIntoSensorSlot(Channel* inputPort); + SensorSlotOfAgent* get_sensorSlotAddress(Channel* inputPort); + unsigned int get_sensorSlotNumber(Channel* inputPort); + SensorSlotOfAgent* get_sensorSlotAddress(HistoryModule* history); + SensorSlotOfAgent* get_sensorSlotAddress(ConfidenceModule* confidenceModule); + bool demount_sensor(Channel* inputPort); + + bool read_sensorValue(SensorSlotOfAgent* sensorSlot); + bool read_allSensorValues(); + + + bool attach_historyModule(Channel* inputPort, HistoryModule* historyModule); + bool detach_historyModule(SensorSlotOfAgent* sensorSlotOfAgent); + bool detach_historyModule(Channel* inputPort); + bool detach_historyModule(HistoryModule* historyModule); + HistoryModule* get_historyModuleOfSensorSlot(Channel* inputPort); + + bool attach_confidenceModule(Channel* inputPort, ConfidenceModule* confidenceModule); + bool detach_confidenceModule(SensorSlotOfAgent* sensorSlotOfAgent); + bool detach_confidenceModule(Channel* inputPort); + bool detach_confidenceModule(ConfidenceModule* confidenceModule); + ConfidenceModule* get_confidenceModuleOfSensorSlot(Channel* inputPort); + + vector* get_vMountedSensors(); + + ~SensorHandlerOfAgent(); + +}; + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.cpp new file mode 100755 index 0000000..0191796 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.cpp @@ -0,0 +1,45 @@ +#include +#include "SensorSlotOfAgent.h" + + + +SensorSlotOfAgent :: SensorSlotOfAgent() { + flagSensorValueIsSet = false; + flagSensorValueHasChanged = false; +} + +void SensorSlotOfAgent :: set_sensorValue(float sensorValue) { + if(flagSensorValueIsSet == false) { + this->sensorValue = sensorValue; + flagSensorValueHasChanged = true; + flagSensorValueIsSet = true; + } + else { + if(this->sensorValue != sensorValue) { + this->sensorValue = sensorValue; + flagSensorValueHasChanged = true; + } + else { + flagSensorValueHasChanged = false; + } + } + + //printf("sensorSlot updated with: %f\n", this->sensorValue); +} + +bool SensorSlotOfAgent :: get_sensorValue(float* sensorValue) { + if(flagSensorValueIsSet == true) { + *sensorValue = this->sensorValue; + return true; + } + return false; +} + +bool SensorSlotOfAgent :: get_flagSensorValueIsSet() { + return flagSensorValueIsSet; +} + +bool SensorSlotOfAgent :: get_flagSensorValueHasChanged() { + return flagSensorValueHasChanged; +} + diff --git a/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.h new file mode 100755 index 0000000..4e8e6f1 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorSlotOfAgent.h @@ -0,0 +1,24 @@ +#ifndef SENSORSLOT_HEADERFILE +#define SENSORSLOT_HEADERFILE + +#include "SlotOfAgent.h" + +//TODO: set name of slot as the name of the sensor is (+ "slot"); +class SensorSlotOfAgent : public SlotOfAgent { + + private: + float sensorValue; + bool flagSensorValueIsSet; + bool flagSensorValueHasChanged; + + public: + SensorSlotOfAgent(); + + void set_sensorValue(float sensorValue); + bool get_sensorValue(float* sensorValue); + + bool get_flagSensorValueIsSet(); + bool get_flagSensorValueHasChanged(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.cpp b/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.cpp new file mode 100755 index 0000000..b453f2f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.cpp @@ -0,0 +1,56 @@ +#include "SensorSlotOfTestbench.h" + +void SensorSlotOfTestbench :: init_sensorSlotOfTestbench() { + sensor = NULL; + csvReaderModule = NULL; +} + +SensorSlotOfTestbench :: SensorSlotOfTestbench() { + init_sensorSlotOfTestbench(); +} + +bool SensorSlotOfTestbench :: set_sensor(Sensor* sensor) { + if(sensor != NULL) { + this->sensor = sensor; + return true; + } + return false; +} + +bool SensorSlotOfTestbench :: del_sensor() { + if(sensor != NULL) { + sensor = NULL; + return true; + } + return false; +} + +Sensor* SensorSlotOfTestbench :: get_sensor() { + return sensor; +} + +bool SensorSlotOfTestbench :: set_csvReaderModule(CSVreaderModule* csvReaderModule) { + if(csvReaderModule != NULL) { + this->csvReaderModule = csvReaderModule; + return true; + } + return false; +} + +bool SensorSlotOfTestbench :: del_csvReaderModule() { + if(csvReaderModule != NULL) { + csvReaderModule = NULL; + return true; + } + return false; +} + +CSVreaderModule* SensorSlotOfTestbench :: get_csvReaderModule() { + return csvReaderModule; +} + +SensorSlotOfTestbench :: ~SensorSlotOfTestbench(){ + del_sensor(); + del_csvReaderModule(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.h b/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.h new file mode 100755 index 0000000..098eaf0 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SensorSlotOfTestbench.h @@ -0,0 +1,29 @@ +#ifndef SENSORSLOTOFTESTBENCH_HEADERFILE +#define SENSORSLOTOFTESTBENCH_HEADERFILE + +#include "CSVreaderModule.h" +#include "Sensor.h" + +class SensorSlotOfTestbench { + + protected: + Sensor* sensor; + CSVreaderModule* csvReaderModule; + + void init_sensorSlotOfTestbench(); + + public: + SensorSlotOfTestbench(); + + bool set_sensor(Sensor* sensor); + bool del_sensor(); + Sensor* get_sensor(); + + bool set_csvReaderModule(CSVreaderModule* csvReaderModule); + bool del_csvReaderModule(); + CSVreaderModule* get_csvReaderModule(); + + ~SensorSlotOfTestbench(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.cpp new file mode 100755 index 0000000..db9ec85 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.cpp @@ -0,0 +1,226 @@ +#include "SlaveAgentHandlerOfAgent.h" + +#include "instruction_set_architecture.h" +#include +#include "printError.h" + + +#include + +#define MAXNUMOF_MOUNTEDSENSORS 100 + +using namespace std; + +SlaveAgentHandlerOfAgent :: SlaveAgentHandlerOfAgent() { + initSlaveAgentHandler(); +} + +void SlaveAgentHandlerOfAgent :: initSlaveAgentHandler() { + maxNumOfMountedSlaveAgents = MAXNUMOF_MOUNTEDSENSORS; +} + +bool SlaveAgentHandlerOfAgent :: mount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = new SlaveAgentSlotOfAgent(); + if(slaveAgentSlotOfAgent != NULL) { + if(slaveAgentSlotOfAgent->set_comPort(inputPort)) { + if(vMountedSlaveAgents.size() < maxNumOfMountedSlaveAgents) { + try { + vMountedSlaveAgents.push_back(slaveAgentSlotOfAgent); + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete slaveAgentSlotOfAgent; + return false; + } + } + else { + printError("Max number of mounted slaveAgents is already reached!"); + delete slaveAgentSlotOfAgent; + return false; + } + return true; + } + else { + printError("Input port is no set!"); + vMountedSlaveAgents.pop_back(); //TODO: check if it is right?!?! + delete slaveAgentSlotOfAgent; + return false; + } + } + else { + printError("Couldn't create SlaveAgentSlot!"); + return false; + } +} + +//TODO: what to do when 2 slaveAgentSlots have the same inputPort??!! +SlaveAgentSlotOfAgent* SlaveAgentHandlerOfAgent :: get_slaveAgentSlotAddress(Channel* inputPort) { + for(auto &slaveAgentSlot : vMountedSlaveAgents) { + if(slaveAgentSlot->get_comPort() == inputPort) { + return slaveAgentSlot; + } + } + return NULL; +} + +//TODO: what to do when 2 slaveAgentSlots have the same inputPort??!! +//TODO: case if slot with comPort is not in this vector +unsigned int SlaveAgentHandlerOfAgent :: get_slaveAgentSlotNumber(Channel* inputPort) { + unsigned int slotNumber = 0; + for(auto &slaveAgentSlot : vMountedSlaveAgents) { + if(slaveAgentSlot->get_comPort() == inputPort) { + return slotNumber; + } + slotNumber++; + } + return NULL; +} + +//TODO: what to do when 2 slaveAgentSlots have the same historyModule??!! +SlaveAgentSlotOfAgent* SlaveAgentHandlerOfAgent :: get_slaveAgentSlotAddress(HistoryModule* historyModule) { + for(auto &slaveAgentSlot : vMountedSlaveAgents) { + if(slaveAgentSlot->get_historyModule() == historyModule) { + return slaveAgentSlot; + } + } + return NULL; +} + +//TODO: what to do when 2 slaveAgentSlots have the same confidenceModule??!! +SlaveAgentSlotOfAgent* SlaveAgentHandlerOfAgent :: get_slaveAgentSlotAddress(ConfidenceModule* confidenceModule) { + for(auto &slaveAgentSlot : vMountedSlaveAgents) { + if(slaveAgentSlot->get_confidenceModule() == confidenceModule) { + return slaveAgentSlot; + } + } + return NULL; +} + +bool SlaveAgentHandlerOfAgent :: demount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort) { + vMountedSlaveAgents.erase(vMountedSlaveAgents.begin() + get_slaveAgentSlotNumber(inputPort)); + return false; +} + +//TODO: do it also for integer variables +bool SlaveAgentHandlerOfAgent :: read_slaveAgentValue(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) { + if(slaveAgentSlotOfAgent != NULL) { + Channel* channel = slaveAgentSlotOfAgent->get_comPort(); + if(channel != NULL) { + int msg; + if(channel->get_MsgUp(&msg)) { + if(msg == ISA_SensoryData) { + //printf("got msg: \n"); + float inputValue; + if(channel->get_MsgUp(&inputValue)) { + slaveAgentSlotOfAgent->setSlaveAgentValue(inputValue); + //printf("got value: %f\n", inputValue); + return true; + } + } + } + } + } + return false; +} + +bool SlaveAgentHandlerOfAgent :: read_allSlaveAgentValues() { + bool flag_readSlaveAgent = true; + for(auto &slaveAgentSlot : vMountedSlaveAgents) { + if(!read_slaveAgentValue(slaveAgentSlot)) { + flag_readSlaveAgent = false; + } + } + + printf("\n"); + + return flag_readSlaveAgent; +} + +bool SlaveAgentHandlerOfAgent :: attach_historyModule(Channel* inputPort, HistoryModule* historyModule) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + if(slaveAgentSlotOfAgent != NULL) { + return slaveAgentSlotOfAgent->set_historyModule(historyModule); + } + return false; +} + +bool SlaveAgentHandlerOfAgent :: detach_historyModule(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) { + if(slaveAgentSlotOfAgent != NULL) { + return slaveAgentSlotOfAgent->del_historyModule(); + } + return false; +} + +bool SlaveAgentHandlerOfAgent :: detach_historyModule(Channel* inputPort) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + return detach_historyModule(slaveAgentSlotOfAgent); +} + +bool SlaveAgentHandlerOfAgent :: detach_historyModule(HistoryModule* historyModule) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(historyModule); + return detach_historyModule(slaveAgentSlotOfAgent); +} + +HistoryModule* SlaveAgentHandlerOfAgent :: get_historyModuleOfSlaveAgentSlot(Channel* inputPort) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + return slaveAgentSlotOfAgent->get_historyModule(); +} + +bool SlaveAgentHandlerOfAgent :: attach_confidenceModule(Channel* inputPort, ConfidenceModule* confidenceModule) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + if(slaveAgentSlotOfAgent != NULL) { + return slaveAgentSlotOfAgent->set_confidenceModule(confidenceModule); + } + return false; +} + +bool SlaveAgentHandlerOfAgent :: detach_confidenceModule(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) { + if(slaveAgentSlotOfAgent != NULL) { + return slaveAgentSlotOfAgent->del_confidenceModule(); + } + return false; +} + +bool SlaveAgentHandlerOfAgent :: detach_confidenceModule(Channel* inputPort) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + return detach_confidenceModule(slaveAgentSlotOfAgent); +} + +bool SlaveAgentHandlerOfAgent :: detach_confidenceModule(ConfidenceModule* confidenceModule) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(confidenceModule); + return detach_confidenceModule(slaveAgentSlotOfAgent); +} + +ConfidenceModule* SlaveAgentHandlerOfAgent :: get_confidenceModuleOfSlaveAgentSlot(Channel* inputPort) { + SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent = get_slaveAgentSlotAddress(inputPort); + return slaveAgentSlotOfAgent->get_confidenceModule(); +} + +vector* SlaveAgentHandlerOfAgent :: get_vMountedSlaveAgents() { + return &vMountedSlaveAgents; +} + +bool SlaveAgentHandlerOfAgent::saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent) { + if (slaveAgentSlotOfAgent != NULL) { + //TODO: change this hardcoded value //Zeitfenster Sliding Window!!!! + while (slaveAgentSlotOfAgent->getHistoryLength() >= 10) { + slaveAgentSlotOfAgent->deleteOldestHistoryEntry(); + } + + //JUST FOR TESTING + //slaveAgentSlotOfAgent->printHistory(); + + return slaveAgentSlotOfAgent->saveValueInHistory(); + } + return false; +} + +bool SlaveAgentHandlerOfAgent::saveAllValuesInHistory() { + bool flagSavingSuccesful = true; + for (auto &slaveAgentSlot : vMountedSlaveAgents) { + if (!saveValueInHistory(slaveAgentSlot)) { + flagSavingSuccesful = false; + } + } + return flagSavingSuccesful; +} diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.h b/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.h new file mode 100755 index 0000000..0a8145c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentHandlerOfAgent.h @@ -0,0 +1,53 @@ +#ifndef SLAVEAGENTHANDLEROFAGENT_HEADERFILE +#define SLAVEAGENTHANDLEROFAGENT_HEADERFILE + +#include "SlaveAgentSlotOfAgent.h" +#include "Unit.h" +#include + +using namespace std; + +class SlaveAgentHandlerOfAgent : public Unit { + + private: + + //TODO: set- and get function for maxNumOf_mountedSlaveAgents; + vector vMountedSlaveAgents; + unsigned int maxNumOfMountedSlaveAgents; + + void initSlaveAgentHandler(); + + public: + SlaveAgentHandlerOfAgent(); + + bool mount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort); + SlaveAgentSlotOfAgent* get_slaveAgentSlotAddress(Channel* inputPort); + unsigned int get_slaveAgentSlotNumber(Channel* inputPort); + SlaveAgentSlotOfAgent* get_slaveAgentSlotAddress(HistoryModule* history); + SlaveAgentSlotOfAgent* get_slaveAgentSlotAddress(ConfidenceModule* confidenceModule); + bool demount_slaveAgentIntoSlaveAgentSlot(Channel* inputPort); + + bool read_slaveAgentValue(SlaveAgentSlotOfAgent* slaveAgentSlot); + bool read_allSlaveAgentValues(); + + bool attach_historyModule(Channel* inputPort, HistoryModule* historyModule); + bool detach_historyModule(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent); + bool detach_historyModule(Channel* inputPort); + bool detach_historyModule(HistoryModule* historyModule); + HistoryModule* get_historyModuleOfSlaveAgentSlot(Channel* inputPort); + + bool attach_confidenceModule(Channel* inputPort, ConfidenceModule* confidenceModule); + bool detach_confidenceModule(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent); + bool detach_confidenceModule(Channel* inputPort); + bool detach_confidenceModule(ConfidenceModule* confidenceModule); + ConfidenceModule* get_confidenceModuleOfSlaveAgentSlot(Channel* inputPort); + + vector* get_vMountedSlaveAgents(); + + bool saveValueInHistory(SlaveAgentSlotOfAgent* slaveAgentSlotOfAgent); + bool saveAllValuesInHistory(); + +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp new file mode 100755 index 0000000..12ae84f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp @@ -0,0 +1,225 @@ +#include "SlaveAgentSlotOfAgent.h" +#include "stdio.h" +#include "printError.h" +#include "relationChecker.h" + +SlaveAgentSlotOfAgent :: SlaveAgentSlotOfAgent() { + flagSlaveAgentValueIsSet = false; + /* + flagSlaveAgentValueHasChanged = false; + flagSlaveAgentValueChangeIsSet = false; + /* + activeState = NULL; + backupState = NULL; + */ +} + +void SlaveAgentSlotOfAgent :: setSlaveAgentValue(float slaveAgentValue) { + this->slaveAgentValue = slaveAgentValue; + flagSlaveAgentValueIsSet = true; + + /* + if(flagSlaveAgentValueIsSet == false) { + this->slaveAgentValue = slaveAgentValue; + flagSlaveAgentValueIsSet = true; + flagSlaveAgentValueHasChanged = true; + } + else { + if(this->slaveAgentValue != slaveAgentValue) { + flagSlaveAgentValueHasChanged = true; + flagSlaveAgentValueChangeIsSet = true; + slaveAgentValueChange = slaveAgentValue - this->slaveAgentValue; + this->slaveAgentValue = slaveAgentValue; + } + else { + flagSlaveAgentValueHasChanged = false; + flagSlaveAgentValueChangeIsSet = true; + slaveAgentValueChange = 0; + } + } + */ + //printf("slaveAgentSlot updated with: %f\n", this->slaveAgentValue); +} + +bool SlaveAgentSlotOfAgent :: get_slaveAgentValue(float* slaveAgentValue) { + if(flagSlaveAgentValueIsSet == true) { + *slaveAgentValue = this->slaveAgentValue; + return true; + } + return false; +} + +bool SlaveAgentSlotOfAgent :: get_flagSlaveAgentValueIsSet() { + return flagSlaveAgentValueIsSet; +} + +//TODO: move these functions into -> HistoryHandler +bool SlaveAgentSlotOfAgent::saveValueInHistory() { + if (flagSlaveAgentValueIsSet) { + try { + //printf("history saving - value: %f\n", slaveAgentValue); + lSlaveAgentHistory.push_back(slaveAgentValue); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + } + } + return false; +} +unsigned int SlaveAgentSlotOfAgent::getHistoryLength() { + return lSlaveAgentHistory.size(); +} +bool SlaveAgentSlotOfAgent::deleteOldestHistoryEntry() { + if (!lSlaveAgentHistory.empty()) { + lSlaveAgentHistory.pop_front(); + return true; + } + return false; +} + + +unsigned int SlaveAgentSlotOfAgent::getNumberOfRelativesToActualValue(float threshold) { + unsigned int numberOfRelativesToActualValue = 0; + for (auto &entry : lSlaveAgentHistory) { + if (valueIsRelatedToReferenceValue(slaveAgentValue, entry, threshold)) { + numberOfRelativesToActualValue++; + } + } + return numberOfRelativesToActualValue; +} + + +//DATE18 +list SlaveAgentSlotOfAgent::getHistory() { + return lSlaveAgentHistory; +} + + + +void SlaveAgentSlotOfAgent::printHistory() { + printf("History: "); + for (auto &entry : lSlaveAgentHistory) { + printf("%f, ", entry); + } + printf("\n"); +} + +SlaveAgentSlotOfAgent :: ~SlaveAgentSlotOfAgent() +{ + int i = 0; +} + +/* +bool SlaveAgentSlotOfAgent :: get_flagSlaveAgentValueHasChanged() { + return flagSlaveAgentValueHasChanged; +} + +bool SlaveAgentSlotOfAgent :: get_slaveAgentValueChangingRate(float* slaveAgentValueChangingRate) { + if(flagSlaveAgentValueChangeIsSet) { + *slaveAgentValueChangingRate = this->slaveAgentValueChange; + return true; + } + return false; +} + +/* +bool SlaveAgentSlotOfAgent :: addStateToStatesVector(State* state) { + if (state != NULL) { + try { + vStates.push_back(state); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete state; + } + + } + return false; +} + + +vector* SlaveAgentSlotOfAgent :: getStatesVector() { + return &vStates; +} + + +bool SlaveAgentSlotOfAgent :: createNewStateAndMakeItActive() { + State* state = new State(); + if (addStateToStatesVector(state)) { + backupState = activeState; + activeState = state; + return true; + } + return false; +} + +bool SlaveAgentSlotOfAgent :: injectValueInActiveState() { + if (activeState == NULL) { + if (createNewStateAndMakeItActive()) { + return activeState->injectValue(slaveAgentValue); + } + } + return activeState->injectValue(slaveAgentValue); +} + +int SlaveAgentSlotOfAgent :: getIndexOfRelatedState(unsigned int startIndex, float thresholdToAverage) { + if (startIndex >= vStates.size()) + return -2; + + int index = 0; + for (vector::iterator state = vStates.begin() + startIndex; state < vStates.end(); state++, index++) { + if ((*state)->valueIsRelated(slaveAgentValue, thresholdToAverage)) { + return index; + } + } + + return -1; +} + +bool SlaveAgentSlotOfAgent :: relatedToActiveState(float thresholdToAverage) { + printf("a\n"); + if (activeState == NULL) { + printf("b\n"); + createNewStateAndMakeItActive(); + return true; + } + + return activeState->valueIsRelated(slaveAgentValue, thresholdToAverage); +} + +bool SlaveAgentSlotOfAgent :: valueIsRelated(unsigned int index, float thresholdToAverage) { + return vStates[index]->valueIsRelated(slaveAgentValue, thresholdToAverage); +} + +State* SlaveAgentSlotOfAgent :: getActiveState() { + return activeState; +} + +void SlaveAgentSlotOfAgent :: deleteActiveState() { + //if(vStates.empty() == false) + vStates.back()->deleteState(); + + vStates.pop_back(); + + if (backupState != NULL) { + activeState = backupState; + backupState = NULL; + } +} + +bool SlaveAgentSlotOfAgent :: setActiveState(unsigned int index) { + if (vStates.size() > index) { + activeState = vStates.at(index); + return true; + } + return false; +} + +unsigned int SlaveAgentSlotOfAgent::getNumberOfStates() { + if (!vStates.empty()) + printf("%u - ", activeState->getNumberOfInjections()); + return vStates.size(); +} +*/ diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h new file mode 100755 index 0000000..dfc9269 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h @@ -0,0 +1,83 @@ +#ifndef SLAVEAGENTSLOTOFAGENT_HEADERFILE +#define SLAVEAGENTSLOTOFAGENT_HEADERFILE + +#include "SlotOfAgent.h" +//#include "State.h" + +class SlaveAgentSlotOfAgent : public SlotOfAgent { + + private: + //TODO: set- and get function for maxNumOf_mountedSensors; + float slaveAgentValue; + list lSlaveAgentHistory; + + bool flagSlaveAgentValueIsSet; + /* + //XXX - next 3 variables needed? + bool flagSlaveAgentValueHasChanged; + bool flagSlaveAgentValueChangeIsSet; + float slaveAgentValueChange; + */ + + + + /* + vector vStates; + State* activeState; + State* backupState; + + bool + ateToStatesVector(State* state); + */ + + public: + SlaveAgentSlotOfAgent(); + + void setSlaveAgentValue(float slaveAgentValue); + bool get_slaveAgentValue(float* slaveAgentValue); + + bool get_flagSlaveAgentValueIsSet(); + + //TODO: move these functions into -> HistoryHandler + bool saveValueInHistory(); + unsigned int getHistoryLength(); + bool deleteOldestHistoryEntry(); + unsigned int getNumberOfRelativesToActualValue(float threshold); + + //DATE18 + list getHistory(); + + + + void printHistory(); + + ~SlaveAgentSlotOfAgent(); + + + /* + bool get_flagSlaveAgentValueHasChanged(); + + bool get_slaveAgentValueChangingRate(float* slaveAgentValueChangingRate); + + /* + vector* getStatesVector(); + bool createNewStateAndMakeItActive(); + bool injectValueInActiveState(); + int getIndexOfRelatedState(unsigned int startIndex, float thresholdToAverage); + + bool relatedToActiveState(float thresholdToAverage); + bool valueIsRelated(unsigned int index, float thresholdToAverage); + + State* getActiveState(); + void deleteActiveState(); + bool setActiveState(unsigned int index); + unsigned int getNumberOfStates(); + */ + /* + vector* getStatesVector(); + State* getActiveState(); + */ +}; + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Slot.cpp b/Version_Max_07_05_2018_CMake/src/Slot.cpp new file mode 100755 index 0000000..73bd51d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Slot.cpp @@ -0,0 +1,20 @@ +#include "Slot.h" + +#include + + +Slot :: Slot() { + +} + +bool Slot :: set_comPort(Channel* comPort) { + if(comPort != NULL) { + this->comPort = comPort; + return true; + } + return false; +} + +Channel* Slot :: get_comPort() { + return comPort; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/Slot.h b/Version_Max_07_05_2018_CMake/src/Slot.h new file mode 100755 index 0000000..65f202b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Slot.h @@ -0,0 +1,19 @@ +#ifndef SLOT_HEADERFILE +#define SLOT_HEADERFILE + +#include "Channel.h" +//#include "Slot.h" + +class Slot : public Unit { + + protected: + Channel* comPort; + + public: + Slot(); + + bool set_comPort(Channel* comPort); + Channel* get_comPort(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SlotOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SlotOfAgent.cpp new file mode 100755 index 0000000..09a6dc2 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlotOfAgent.cpp @@ -0,0 +1,47 @@ +#include "SlotOfAgent.h" + +#include + +SlotOfAgent :: SlotOfAgent() { + +} + +bool SlotOfAgent :: set_historyModule(HistoryModule* historyModule) { + if(historyModule != NULL) { + this->historyModule = historyModule; + return true; + } + return false; +} + +bool SlotOfAgent :: del_historyModule() { + if(historyModule != NULL) { + historyModule = NULL; + return true; + } + return false; +} + +HistoryModule* SlotOfAgent :: get_historyModule() { + return historyModule; +} + +bool SlotOfAgent :: set_confidenceModule(ConfidenceModule* confidenceModule) { + if(confidenceModule != NULL) { + this->confidenceModule = confidenceModule; + return true; + } + return false; +} + +bool SlotOfAgent :: del_confidenceModule() { + if(confidenceModule != NULL) { + confidenceModule = NULL; + return true; + } + return false; +} + +ConfidenceModule* SlotOfAgent :: get_confidenceModule() { + return confidenceModule; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/SlotOfAgent.h new file mode 100755 index 0000000..2369c69 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SlotOfAgent.h @@ -0,0 +1,27 @@ +#ifndef SLOTOFAGENT_HEADERFILE +#define SLOTOFAGENT_HEADERFILE + +#include "ConfidenceModule.h" +#include "HistoryModule.h" +#include "Slot.h" + +class SlotOfAgent : public Slot { + + protected: + HistoryModule* historyModule; + ConfidenceModule* confidenceModule; + //Abstraction + + public: + SlotOfAgent(); + + bool set_historyModule(HistoryModule* historyModule); + bool del_historyModule(); + HistoryModule* get_historyModule(); + + bool set_confidenceModule(ConfidenceModule* confidenceModule); + bool del_confidenceModule(); + ConfidenceModule* get_confidenceModule(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/State.cpp b/Version_Max_07_05_2018_CMake/src/State.cpp new file mode 100755 index 0000000..aac8c32 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/State.cpp @@ -0,0 +1,476 @@ +#include "State.h" + +#include "printError.h" +#include "relationChecker.h" + +#include "minmaxzeug.h" + +#define INJECTIONPARTITIONING 10 + +State::State() { + //discreteAveragePartitionSize = INJECTIONPARTITIONING; + discreteAveragePartitionCounter = 0; + stateIsValid = false; +} +/* +bool State::setDiscreteAveragePartitionSize(unsigned int discreteAveragePartitionSize) { + if (discreteAveragePartitionSize > 0) { + this->discreteAveragePartitionSize = discreteAveragePartitionSize; + return true; + } + return false; +} + +unsigned int State::getDiscreteAveragePartitionSize() { + return discreteAveragePartitionSize; +} +*/ +bool State::addSubState(vector* vSubStates, SlaveAgentSlotOfAgent* slot) { + SubState* subState = new (nothrow) SubState(); + if (subState != NULL) { + subState->setSlot(slot); + try { + vSubStates->push_back(subState); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete subState; + } + } + return false; +} + +bool State::addInputSubState(SlaveAgentSlotOfAgent* slot) { + return addSubState(&vInputSubStates, slot);; +} + +bool State::addOutputSubState(SlaveAgentSlotOfAgent* slot) { + return addSubState(&vOutputSubStates, slot); +} + +void State::resetDiscreteAveragePartitionCounter() { + discreteAveragePartitionCounter = 0; +} + +bool State::addNewdiscreteAveragePartition() { + bool flagWorkedForAll = true; + + for (auto &subState : vInputSubStates) { + if (!subState->addNewDiscreteAverage()) + flagWorkedForAll = false; + } + for (auto &subState : vOutputSubStates) { + if (!subState->addNewDiscreteAverage()) + flagWorkedForAll = false; + } + + return flagWorkedForAll; +} + +bool State::injectValues(unsigned int discreteAveragePartitionSize) { + + bool flagWorkedForAll = true; + + if (discreteAveragePartitionCounter == 0) { + for (auto &subState : vInputSubStates) { + subState->deleteLastDiscreteAverageBlockIfNotCompleted(discreteAveragePartitionSize); + } + for (auto &subState : vOutputSubStates) { + subState->deleteLastDiscreteAverageBlockIfNotCompleted(discreteAveragePartitionSize); + } + flagWorkedForAll = addNewdiscreteAveragePartition(); + } + + if (flagWorkedForAll) { + discreteAveragePartitionCounter++; + // XXX - >= or > ?? + if (discreteAveragePartitionCounter >= discreteAveragePartitionSize) { + discreteAveragePartitionCounter = 0; + } + + for (auto &subState : vInputSubStates) { + if (subState->injectValue()) + flagWorkedForAll = false; + } + for (auto &subState : vOutputSubStates) { + if (subState->injectValue()) + flagWorkedForAll = false; + } + + printf(" >>> Inject Values (partCounter: %u)\n", discreteAveragePartitionCounter); + //getchar(); + + } + + return flagWorkedForAll; +} + +bool State::injectValuesAndMakeNewDiscreteAveragePartition(unsigned int discreteAveragePartitionSize) { + discreteAveragePartitionCounter = 0; + return injectValues(discreteAveragePartitionSize); +} + + +bool State::variablesAreRelated(vector* vSubStates, float thresholdToBeRelated) { + bool flagAllValuesAreRelated = true; + + for (auto &subState : *vSubStates) { + if (!subState->valueIsRelated(thresholdToBeRelated)) { + flagAllValuesAreRelated = false; + } + + } + + return flagAllValuesAreRelated; +} + +bool State::inputVariablesAreRelated(float thresholdToBeRelated) { + return variablesAreRelated(&vInputSubStates, thresholdToBeRelated); +} + +bool State::outputVariablesAreRelated(float thresholdToBeRelated) { + return variablesAreRelated(&vOutputSubStates, thresholdToBeRelated); +} + +unsigned int State::getNumOfInjections() { + if (!vInputSubStates.empty()) { + return vInputSubStates.front()->getNumOfInjections(); + } + return 0; +} + + +bool State::checkSubStatesForNotDrifting(vector* vSubStates, unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift) { + for (auto &subState : *vSubStates) { + if (subState->getNumberOfCompletedDiscreteAverageBlocks(discreteAveragePartitionSize) > 1) { + + //printf("completed blocks = %u\n", subState->getNumberOfCompletedDiscreteAverageBlocks(discreteAveragePartitionSize)); + //getchar(); + + if (!valueIsRelatedToReferenceValue(subState->getDiscreteAverageOfFirstBlock(discreteAveragePartitionSize), subState->getDiscreteAverageOfLastBlock(discreteAveragePartitionSize), thresholdNotDrift)) { + //if (!valueIsRelatedToReferenceValue(subState->getDiscreteAverageOfBlockBeforeLastBlock(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition), subState->getDiscreteAverageOfLastBlock(discreteAveragePartitionSize), thresholdNotDrift)) { + + return false; + } + } + } + //getchar(); + return true; +} + + +bool State::checkAllVariablesForNotDrifting(unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift) { + + return checkSubStatesForNotDrifting(&vInputSubStates, discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift) && checkSubStatesForNotDrifting(&vOutputSubStates, discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift); +} + +//DATE18 +float State::checkSubStatesForDriftingFuzzy(vector* vSubStates, unsigned int discreteAveragePartitionSize, LinearFunctionBlock* Drift) { + + float confidenceDriftMax = 0; + + for (auto &subState : *vSubStates) { + + if (subState->getNumberOfCompletedDiscreteAverageBlocks(discreteAveragePartitionSize) > 1) { + + float confidenceDrift = Drift->getY(deviationValueReferenceValue(subState->getDiscreteAverageOfLastBlock(discreteAveragePartitionSize), subState->getDiscreteAverageOfFirstBlock(discreteAveragePartitionSize))); + + printf("confDrift = %f, deviationValueReferenceValue = %f\n", confidenceDrift, deviationValueReferenceValue(subState->getDiscreteAverageOfLastBlock(discreteAveragePartitionSize), subState->getDiscreteAverageOfFirstBlock(discreteAveragePartitionSize))); + + if (confidenceDrift > confidenceDriftMax) + confidenceDriftMax = confidenceDrift; + } + } + + return confidenceDriftMax; +} + +//DATE18 +float State::checkAllVariablesForDriftingFuzzy(unsigned int discreteAveragePartitionSize, LinearFunctionBlock* Drift) { + + float confidenceDriftInput = checkSubStatesForDriftingFuzzy(&vInputSubStates, discreteAveragePartitionSize, Drift); + float confidenceDriftOutput = checkSubStatesForDriftingFuzzy(&vOutputSubStates, discreteAveragePartitionSize, Drift); + + if (confidenceDriftInput > confidenceDriftOutput) + return confidenceDriftInput; + else + return confidenceDriftOutput; +} + + +//DATE18 +float State::variablesAreRelatedFuzzy(vector* vSubStates, LinearFunctionBlock* SameState) { + + float confRelatedMin = 1; + + for (auto &subState : *vSubStates) { + + float confRelated = subState->valueIsRelatedFuzzy(SameState); + printf("conf %f\n", confRelated); + + if (confRelated < confRelatedMin) + confRelatedMin = confRelated; + } + + return confRelatedMin; +} + +float State::inputVariablesAreRelatedFuzzy(LinearFunctionBlock* SameState) { + return variablesAreRelatedFuzzy(&vInputSubStates, SameState); +} + +float State::outputVariablesAreRelatedFuzzy(LinearFunctionBlock* SameState) { + return variablesAreRelatedFuzzy(&vOutputSubStates, SameState); +} + +bool State::insertValueInState(LinearFunctionBlock* FuncBlockConfValStateDev, LinearFunctionBlock* FuncBlockConfInvStateDev, LinearFunctionBlock* FuncBlockConfValStateTime, LinearFunctionBlock* FuncBlockConfInvStateTime, unsigned int historySize, unsigned int discreteAveragePartitionSize) { + + //bool insertionWorked = true; + + if (discreteAveragePartitionCounter == 0) { + for (auto &subState : vInputSubStates) + subState->deleteLastDiscreteAverageBlockIfNotCompleted(discreteAveragePartitionSize); + for (auto &subState : vOutputSubStates) + subState->deleteLastDiscreteAverageBlockIfNotCompleted(discreteAveragePartitionSize); + + //insertionWorked = addNewdiscreteAveragePartition(); + addNewdiscreteAveragePartition(); + } + + discreteAveragePartitionCounter++; + + if (discreteAveragePartitionCounter >= discreteAveragePartitionSize) + discreteAveragePartitionCounter = 0; + + confValidState = 1; + confInvalidState = 0; + + for (auto &subState : vInputSubStates) { + //if (!(subState->insertValueInSubState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, historySize))) + //insertionWorked = false; + subState->insertValueInSubState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, historySize); + + confValidState = fuzzyAND(confValidState, subState->getConfidenceValidState()); + confInvalidState = fuzzyOR(confInvalidState, subState->getConfidenceInvalidState()); + } + + for (auto &subState : vOutputSubStates) { + //if (!(subState->insertValueInSubState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, historySize))) + //insertionWorked = false; + subState->insertValueInSubState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, historySize); + + confValidState = fuzzyAND(confValidState, subState->getConfidenceValidState()); + confInvalidState = fuzzyOR(confInvalidState, subState->getConfidenceInvalidState()); + } + + printf("confValidState %f\nconfInvalidState %f\n", confValidState, confInvalidState); + //getchar(); + + if (confValidState > confInvalidState) { + printf("VALID STATE\n"); + stateIsValid = true; + return true; + } + + return false; + + //return insertionWorked; +} + +bool State::insertValueInState(float confValid, float confInvalid, unsigned int historySize, unsigned int discreteAveragePartitionSize) { + + return true; +} + + + +float State::getConfInputVarAreSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime) { + return getConfVarAreSim2State(&vInputSubStates, FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); +} + +float State::getConfInputVarAreDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime) { + return getConfVarAreDif2State(&vInputSubStates, FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); +} + +float State::getConfOutputVarAreSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime) { + return getConfVarAreSim2State(&vOutputSubStates, FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); +} + +float State::getConfOutputVarAreDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime) { + return getConfVarAreDif2State(&vOutputSubStates, FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); +} + + +unsigned int State::getLengthOfHistory() { + if (!vInputSubStates.empty()) { + printf("historyLength: %u\n", vInputSubStates.front()->getSampleHistoryLength()); + + return vInputSubStates.front()->getSampleHistoryLength(); + } + return 0; +} + +bool State::isStateValid() { + return stateIsValid; +} + +float State::getConfStateValid() { + return confValidState; +} + +float State::getConfStateInvalid() { + return confInvalidState; +} + + +//new +float State::getConfVarAreSim2State(vector* vSubStates, LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime) { + + float lowestConfOfAllVarAreRelated = 1; + + for (auto &subState : *vSubStates) + lowestConfOfAllVarAreRelated = fuzzyAND(lowestConfOfAllVarAreRelated, subState->getConfVarIsSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime)); + + return lowestConfOfAllVarAreRelated; +} + +float State::getConfVarAreDif2State(vector* vSubStates, LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime) { + float highestConfOfAllVarAreNotRelated = 0; + + for (auto &subState : *vSubStates) + highestConfOfAllVarAreNotRelated = fuzzyOR(highestConfOfAllVarAreNotRelated, subState->getConfVarIsDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime)); + + return highestConfOfAllVarAreNotRelated; +} + +bool State::delete_All_Input_Substates() +{ + SubState* cur_Sub_State; + unsigned int index_cur_Sub_State; + unsigned int size_vInSubStates = vInputSubStates.size(); + for(index_cur_Sub_State = 0; index_cur_Sub_State < size_vInSubStates; index_cur_Sub_State++){ + cur_Sub_State = vInputSubStates[index_cur_Sub_State]; + delete cur_Sub_State; + } + vInputSubStates.clear(); +} + +bool State::delete_All_Output_Substates() +{ + SubState* cur_Sub_State; + unsigned int index_cur_Sub_State; + unsigned int size_vOutSubStates = vOutputSubStates.size(); + for(index_cur_Sub_State = 0; index_cur_Sub_State < size_vOutSubStates; index_cur_Sub_State++){ + cur_Sub_State = vOutputSubStates[index_cur_Sub_State]; + delete cur_Sub_State; + } + vOutputSubStates.clear(); +} + +State::~State() +{ + delete_All_Input_Substates(); + delete_All_Output_Substates(); +} + + + + + + + + + + + + + + +/* +bool State :: setInjectionPartitioning(unsigned int injectionPartitioning) { + if (injectionPartitioning > 0) { + this->injectionPartitioning = injectionPartitioning; + return true; + } + return false; +} + +unsigned int State :: getInjectionPartitioning() { + return injectionPartitioning; +} + +bool State :: addDiscreteAveragePartition() { + AverageValue* avg = new AverageValue(); + if (avg != NULL) { + try { + vDiscreteAveragePartition.push_back(avg); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete avg; + } + } + return false; +} + +bool State :: injectValue(float value) { + + AverageValue* avg = NULL; + + continuousStatisticValue.injectAndCalculateExtremeValue(value); + //injectionCounter++; + + if (injectionPartitionCounter == 0) { + if (addDiscreteAveragePartition()) { + injectionPartitionCounter++; + avg = vDiscreteAveragePartition.back(); + } + } + else { + avg = vDiscreteAveragePartition.back(); + } + + if (avg != NULL) { + avg->injectAndCalculateAverageValue(value); + if (injectionPartitionCounter > injectionPartitioning) { + injectionPartitionCounter = 0; + } + return true; + } + return false; +} + +bool State :: valueIsRelated(float value, float thresholdToAverage) { + float diff; + float avg = continuousStatisticValue.getAverageValue(); + + printf("value: %f, avg: %f, th: %f\n", value, avg, thresholdToAverage); + + if (value > avg) + diff = value - avg; + else + diff = avg - value; + + if (diff / avg <= thresholdToAverage) + return true; + + return false; +} + +bool State :: isNew() { + if (continuousStatisticValue.getInjectedValuesCounter() == 0) + return true; + return false; +} + +unsigned int State :: getNumberOfInjections() { + return continuousStatisticValue.getInjectedValuesCounter(); +} + +void State :: deleteState() { + vDiscreteAveragePartition.swap(vDiscreteAveragePartition); +} + +*/ diff --git a/Version_Max_07_05_2018_CMake/src/State.h b/Version_Max_07_05_2018_CMake/src/State.h new file mode 100755 index 0000000..3bbba99 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/State.h @@ -0,0 +1,114 @@ +#ifndef STATE_HEADERFILE +#define STATE_HEADERFILE + +#include "SlaveAgentSlotOfAgent.h" +#include "SubState.h" +#include +#include "LinearFunctionBlock.h" + +class State { + + private: + + vector vInputSubStates; + vector vOutputSubStates; + + //unsigned int discreteAveragePartitionSize; + unsigned int discreteAveragePartitionCounter; + + /* + StatisticValue continuousStatisticValue; + vector vDiscreteAveragePartition; + + bool addDiscreteAveragePartition(); + */ + + bool addSubState(vector* vSubStates, SlaveAgentSlotOfAgent* slot); + + bool variablesAreRelated(vector* vSubStates, float thresholdToBeRelated); + + bool checkSubStatesForNotDrifting(vector* vSubStates, unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift); + + float confValidState; + float confInvalidState; + + bool stateIsValid; + + bool delete_All_Input_Substates(); + bool delete_All_Output_Substates(); + + public: + State(); + /* + bool setDiscreteAveragePartitionSize(unsigned int discreteAverage); + unsigned int getDiscreteAveragePartitionSize(); + */ + bool addInputSubState(SlaveAgentSlotOfAgent* slot); + bool addOutputSubState(SlaveAgentSlotOfAgent* slot); + + void resetDiscreteAveragePartitionCounter(); + + bool addNewdiscreteAveragePartition(); + + bool injectValues(unsigned int discreteAveragePartitionSize); + + bool injectValuesAndMakeNewDiscreteAveragePartition(unsigned int discreteAveragePartitionSize); + + bool inputVariablesAreRelated(float thresholdToBeRelated); + bool outputVariablesAreRelated(float thresholdToBeRelated); + + unsigned int getNumOfInjections(); + + bool checkAllVariablesForNotDrifting(unsigned int discreteAveragePartitionSize, unsigned int compareDistanceDiscreteAveragePartition, float thresholdNotDrift); + + + //DATE18 + float checkSubStatesForDriftingFuzzy(vector* vSubStates, unsigned int discreteAveragePartitionSize, LinearFunctionBlock* Drift); + float checkAllVariablesForDriftingFuzzy(unsigned int discreteAveragePartitionSize, LinearFunctionBlock* Drift); + float variablesAreRelatedFuzzy(vector* vSubStates, LinearFunctionBlock* SameState); + float inputVariablesAreRelatedFuzzy(LinearFunctionBlock* SameState); + float outputVariablesAreRelatedFuzzy(LinearFunctionBlock* SameState); + + bool insertValueInState(LinearFunctionBlock* FuncBlockConfValStateDev, LinearFunctionBlock* FuncBlockConfInvStateDev, LinearFunctionBlock* FuncBlockConfValStateTime, LinearFunctionBlock* ConfInvStateTime, unsigned int historySize, unsigned int discreteAveragePartitionSize); + + bool insertValueInState(float confValid, float confInvalid, unsigned int historySize, unsigned int discreteAveragePartitionSize); + + + + float getConfInputVarAreSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime); + float getConfInputVarAreDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime); + float getConfOutputVarAreSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime); + float getConfOutputVarAreDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime); + + unsigned int getLengthOfHistory(); + + bool isStateValid(); + + float getConfStateValid(); + float getConfStateInvalid(); + + ~State(); + + private: + float getConfVarAreSim2State(vector* vSubStates, LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime); + float getConfVarAreDif2State(vector* vSubStates, LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime); + + + + /* + + + bool injectValue(float value); + bool valueIsRelated(float value, float thresholdToAverage); + + bool isNew(); + + unsigned int getNumberOfInjections(); + + void deleteState(); + */ + + +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/StateHandler.cpp b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp new file mode 100755 index 0000000..70c93e9 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp @@ -0,0 +1,1785 @@ +#include "StateHandler.h" + +#include +#include "printError.h" +#include "rlutil.h" + +#include "relationChecker.h" + +#include "minmaxzeug.h" + + +#include +#include + +//CHANGE ALSO BOTH FUZZY FUNCTION!!! +// is used for the history length of the number of values which will be compared +//to the current value +#define MAX_STATE_HISTORY_LENGTH 10 //10 + +#define STOP_WHEN_BROKEN +//#define STOP_AFTER_BROKEN +//#define STOP_WHEN_DRIFT +//#define STOP_WHEN_STATE_VALID + +//TODO: also change also hardcoded value in "SlaveAgentHandlerOfAgent.cpp" +#define SLIDINGWINDOWSIZE 3 //3 //10 +#define STABLENUMBER 2 //2 //8 +#define STABLETHRESHOLD (float)0.04 //0.4 //0.03 +#define RELATEDTHRESHOLD (float)0.08 //0.08 + +#define INJECTIONPARTITIONING 5 +#define CMPDISTANCE 3 +#define THDRIFT (float)0.08 //0.8 + +#define MINNUMTOBEVALIDSTATE 11 //11 //8 //10 + +//three different status are for the system possible +#define STATUS_BROKEN 1 +#define STATUS_DRIFT 2 +#define STATUS_OKAY 3 + + +using namespace rlutil; + + +void StateHandler::initStateHandler() { + + flagVariablesWereStable = false; + + slidingWindowBufferSize = SLIDINGWINDOWSIZE; + minNumOfRelatedValuesToBeStable = STABLENUMBER; + thresholdToBeStable = STABLETHRESHOLD; + + thresholdToBeRelated = RELATEDTHRESHOLD; + + discreteAveragePartitionSize = INJECTIONPARTITIONING; + compareDistanceDiscreteAveragePartition = CMPDISTANCE; + thresholdNotDrift = THDRIFT; + + minNumToBeValidState = MINNUMTOBEVALIDSTATE; + + activeState = NULL; + + maxStateHistoryLength = MAX_STATE_HISTORY_LENGTH; + + + time_t rawtime; + struct tm * timeinfo; + char output_file_name[200]; + char datetime[80]; + const std::string output_directory_name = "./output_data_csv/Opel/2018-08-09/"; + std::string output_file_name_str; + + time(&rawtime); + timeinfo = localtime(&rawtime); + + strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", timeinfo); + output_file_name_str = output_directory_name + "output" + datetime + ".csv"; + cout << output_file_name_str << endl; + + //XXX - only for now: + if(csv_writer == NULL) { + csv_writer = new CSV_Writer("CSV Writer", (char*) output_file_name_str.c_str()); + } + + + + + //DATE18 + confidenceStableInput = 0; + confidenceStableOutput = 0; + confidenceStable = 0; + confStableAdjustableThreshold = 0.5; + + confidenceUnstableInput = 0; + confidenceUnstableOutput = 0; + confidenceUnstable = 0; + confidenceUnstableAdjustableThreshold = 0.5; + + + confidenceSameStateInput = 0; + confSameStateInputAdjustableThreshold = 0.5; + confidenceSameStateOutput = 0; + confSameStateOutputAdjustableThreshold = 0.5; + + confidenceValidState = 0; + confValidStateAdjustableThreshold = 0.5; + + brokenCounter = 0; + confidenceBroken = 0; + confidenceBrokenAdjustableThreshold = 0.5; + + driftCounter = 0; + confidenceDrift = 0; + confidenceDriftAdjustableThreshold = 0.5; + + +} + +StateHandler::StateHandler() { + set_name(NO_NAME); + initStateHandler(); +} + +StateHandler::StateHandler(char* name) { + set_name(name); + initStateHandler(); +} + +bool StateHandler::setDiscreteAveragePartitionSize(unsigned int discreteAveragePartitionSize) { + if (discreteAveragePartitionSize > 0) { + this->discreteAveragePartitionSize = discreteAveragePartitionSize; + return true; + } + return false; +} + +unsigned int StateHandler::getDiscreteAveragePartitionSize() { + return discreteAveragePartitionSize; +} + +bool StateHandler::addVariable(vector* vVariables, SlaveAgentSlotOfAgent* slot) { + if (vVariables != NULL && slot != NULL) { + if (find((*vVariables).begin(), (*vVariables).end(), slot) == (*vVariables).end()) { + try { + (*vVariables).push_back(slot); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + } + } + } + return false; +} + +bool StateHandler::addInputVariable(SlaveAgentSlotOfAgent* slot) { + return addVariable(&vInputVariables, slot); +} + +bool StateHandler::addOutputVariable(SlaveAgentSlotOfAgent* slot) { + return addVariable(&vOutputVariables, slot); +} + +bool StateHandler::delete_all_OuputVariables() +{ + SlaveAgentSlotOfAgent* cur_sl_ag_sl_ag; + unsigned int index_v_OutVar; + unsigned int size_v_OutVar = vOutputVariables.size(); + for(index_v_OutVar = 0; index_v_OutVar < size_v_OutVar; index_v_OutVar++) { + cur_sl_ag_sl_ag = vOutputVariables[index_v_OutVar]; + delete cur_sl_ag_sl_ag; + } + vOutputVariables.clear(); +} + +bool StateHandler::delete_all_InputVariables() +{ + SlaveAgentSlotOfAgent* cur_sl_ag_sl_ag; + unsigned int index_v_InpVar; + unsigned int size_v_InpVar = vInputVariables.size(); + for(index_v_InpVar = 0; index_v_InpVar < size_v_InpVar; index_v_InpVar++) { + cur_sl_ag_sl_ag = vInputVariables[index_v_InpVar]; + delete cur_sl_ag_sl_ag; + } + vInputVariables.clear(); +} + +bool StateHandler::delete_allStates() +{ + State* cur_state; + unsigned int index_v_State; + unsigned int size_v_State = vStates.size(); + for(index_v_State = 0; index_v_State < size_v_State; index_v_State++) { + cur_state = vStates[index_v_State]; + delete cur_state; + } + vStates.clear(); +} + +bool StateHandler::setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize) { + if (slidingWindowBufferSize >= minNumOfRelatedValuesToBeStable) { + this->slidingWindowBufferSize = slidingWindowBufferSize; + return true; + } + return false; +} + +bool StateHandler::setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable) { + if (minNumOfRelatedValuesToBeStable <= slidingWindowBufferSize) { + this->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable; + return true; + } + return false; +} + +bool StateHandler::setThresholdToBeStable(float thresholdToBeStable) { + if (thresholdToBeStable >= 0 && thresholdToBeStable <= 1) { + this->thresholdToBeStable = thresholdToBeStable; + return true; + } + return false; +} + +bool StateHandler::setThresholdToBeRelated(float thresholdToBeRelated) { + if (thresholdToBeRelated >= 0 && thresholdToBeRelated <= 1) { + this->thresholdToBeRelated = thresholdToBeRelated; + return true; + } + return false; +} + + + + +bool StateHandler::variablesAreStable(vector* vVariables) { + bool flagAllVariablesAreStable = true; + for (auto &slot : *vVariables) { + if (slot->getHistoryLength() >= slidingWindowBufferSize - 1) { //-1 because actual value is not in the history + if (slot->getNumberOfRelativesToActualValue(thresholdToBeStable) < minNumOfRelatedValuesToBeStable) { //-1 because actual value is also on of minNumOfRelatedValuesToBeStable + flagAllVariablesAreStable = false; + } + } + else { + return false; + } + } + + return flagAllVariablesAreStable; +} + +//Sorting with bigger Value in Front +struct descending +{ + template + bool operator()(T const &a, T const &b) const { return a > b; } +}; + +//DATE18 +float StateHandler::getConfVariableIsStable(SlaveAgentSlotOfAgent* variable) { + float bestConfOf1Var = 0; + float sample; + if (variable->get_slaveAgentValue(&sample)) { + + list lHistoryTemporary = variable->getHistory(); + vector vDeviations; + + for (auto &h : lHistoryTemporary) + vDeviations.push_back(deviationValueReferenceValue(sample, h)); + + std::sort(std::begin(vDeviations), std::end(vDeviations)); + + //all adaptabilities within the history of one variable + for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) { + + float worstConfOfHistSampleSet = 1; + unsigned int histSampleCounter = 0; + + for (auto &deviation : vDeviations) { + if (histSampleCounter >= numOfHistSamplesIncluded) + break; + + worstConfOfHistSampleSet = minValueOf2Values(worstConfOfHistSampleSet, StabDeviation->getY(deviation)); + + histSampleCounter++; + } + + bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(worstConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter))); + } + } + + return bestConfOf1Var; +} + +//DATE18 +float StateHandler::getConfVariablesAreStable(vector* vVariables) { + float worstConfOfAllVariables = 1; + + for (auto &slot : *vVariables) + worstConfOfAllVariables = minValueOf2Values(worstConfOfAllVariables, getConfVariableIsStable(slot)); + + return worstConfOfAllVariables; +} + +//DATE18 +float StateHandler::getConfVariableIsUnstable(SlaveAgentSlotOfAgent* variable) { + float bestConfOf1Var = 0; + float sample; + if (variable->get_slaveAgentValue(&sample)) { + + list lHistoryTemporary = variable->getHistory(); + vector vDeviations; + + for (auto &h : lHistoryTemporary) + vDeviations.push_back(deviationValueReferenceValue(sample, h)); + + sort(begin(vDeviations), end(vDeviations), descending()); + + //all adaptabilities within the history of one variable + for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) { + + //float bestConfOfHistSampleSet = 1; + float bestConfOfHistSampleSet = 0; + unsigned int histSampleCounter = 0; + + for (auto &deviation : vDeviations) { + if (histSampleCounter >= numOfHistSamplesIncluded) + break; + + //bestConfOfHistSampleSet = minValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation)); + bestConfOfHistSampleSet = maxValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation)); + + histSampleCounter++; + } + + bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(bestConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter))); + } + } + + return bestConfOf1Var; +} + +//DATE18 - Is there one unstable variable? +float StateHandler::getConfVariablesAreUnstable(vector* vVariables) { + float bestConfOfAllVariables = 0; + + for (auto &slot : *vVariables) + bestConfOfAllVariables = maxValueOf2Values(bestConfOfAllVariables, getConfVariableIsUnstable(slot)); + + return bestConfOfAllVariables; +} + + + + +bool StateHandler::getConfAndUnconfVariableIsMatching(State* state, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf) { + float bestUnconfOf1Var = 0; + float worstConfOf1Var = 1; + + if (state != NULL) { + + + } + + /* + float sample; + if (variable->get_slaveAgentValue(&sample)) { + + list lHistoryTemporary = variable->getHistory(); + vector vDeviations; + + for (auto &h : lHistoryTemporary) + vDeviations.push_back(deviationValueReferenceValue(sample, h)); + + sort(begin(vDeviations), end(vDeviations), descending()); + + //all adaptabilities within the history of one variable + for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) { + + //float bestConfOfHistSampleSet = 1; + float bestConfOfHistSampleSet = 0; + unsigned int histSampleCounter = 0; + + for (auto &deviation : vDeviations) { + if (histSampleCounter >= numOfHistSamplesIncluded) + break; + + //bestConfOfHistSampleSet = minValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation)); + bestConfOfHistSampleSet = maxValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation)); + + histSampleCounter++; + } + + bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(bestConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter))); + } + } + + return bestConfOf1Var; + */ + + return 0; +} + +/* +bool StateHandler::getConfAndUnconfVariablesAreMatching(vector* vVariables, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf) { + + float bestUnconfOfAllVariables = 0; + float worstConfOfAllVariables = 1; + + for (auto &variable :* vVariables) { + bestUnconfOfAllVariables = maxValueOf2Values(bestUnconfOfAllVariables, getConfAndUnconfVariableIsMatching(variable, confDeviation, confTime, conf, unconf)); + worstConfOfAllVariables = minValueOf2Values(worstConfOfAllVariables, getConfAndUnconfVariableIsMatching(variable, confDeviation, confTime, conf, unconf)); + } + + *conf = worstConfOfAllVariables; + *unconf = bestUnconfOfAllVariables; + + return true; +} +*/ + + + + + +State* StateHandler::makeNewState() { + State* state = new (nothrow) State(); + if (state != NULL) { + bool flagLoadVariablesWorked = true; + for (auto &slot : vInputVariables) { + if (!state->addInputSubState(slot)) + flagLoadVariablesWorked = false; + } + for (auto &slot : vOutputVariables) { + if (!state->addOutputSubState(slot)) + flagLoadVariablesWorked = false; + } + if (!flagLoadVariablesWorked) { + delete state; + return NULL; + } + } + else { + return NULL; + } + + return state; +} + +bool StateHandler::addActiveStateToStateVector() { + + printf(" >> Save Active State\n"); + + if (activeState != NULL) { + for (auto &state : vStates) { + if (state == activeState) + return true; + } + +#ifdef STOP_WHEN_STATE_VALID + getchar(); +#endif // STOP_WHEN_STATE_VALID + + try { + vStates.push_back(activeState); + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete activeState; + } + } + return false; +} + +/* +bool StateHandler::addStateAndMakeItActive() { + State* state = addState(); + if (state != NULL) { + activeState = state; + return true; + } + return false; +} +*/ + +bool StateHandler::makeNewActiveState() { + State* state = makeNewState(); + if (state != NULL) { + activeState = state; + return true; + } + return false; +} + + +State* StateHandler::findRelatedState() { + for (auto &state : vStates) { + if (state->inputVariablesAreRelated(thresholdToBeRelated) && state->outputVariablesAreRelated(thresholdToBeRelated)) { + return state; + } + } + return NULL; +} + +bool StateHandler::findRelatedStateAndMakeItActive() { + State* state = findRelatedState(); + if (state != NULL) { + activeState = state; + return true; + } + return false; +} + +void StateHandler::eraseStatesWithLessInjections() { + if (activeState != NULL) { + if (activeState->getNumOfInjections() < minNumToBeValidState) { + activeState = NULL; + } + } + + for (vector::iterator state = vStates.begin(); state < vStates.end(); state++) { + if ((*state)->getNumOfInjections() < minNumToBeValidState) { + //TODO: also delete all subStates (etc.) of the State? Because: Memory Leakage. + vStates.erase(state); + state--; + } + } + + + + + + + + + /* + for (auto &state : vStates) { + //TODO: also delete all subStates (etc.) of the State? Because: Memory Leakage. + if (state->getNumOfInjections() < minNumToBeValidState) { + vStates.erase(state); + } + } + */ + +} + +void StateHandler :: reset_States() +{ + this->delete_allStates(); + this->activeState = NULL; +} + +void StateHandler :: reset_States_and_Slave_Agents() +{ + reset_States(); + this->delete_all_InputVariables(); + this->delete_all_OuputVariables(); +} + + +StateHandler :: ~StateHandler() +{ + delete_all_OuputVariables(); + delete_all_InputVariables(); + delete_allStates(); + + //delete csv_writer; +} + + +//XXX - only for now +bool test = true; +unsigned int brokenCounter = 0, driftCounter = 0; + +void printDrift() { + driftCounter++; + setColor(TXTCOLOR_YELLOW); + printf(" >> DRIFT\n"); + setColor(TXTCOLOR_GREY); + test = true; +} + +void printBroken() { + brokenCounter++; + setColor(TXTCOLOR_LIGHTRED); + printf(" >> BROKEN\n"); + setColor(TXTCOLOR_GREY); + test = true; +} + +//XXX - only for now +unsigned int old_cycle = 1; + +int brokentest = 0; + +/* + * makes a new state and reports if there is a anomaly = hearth piece of CAM :-) + */ +void StateHandler::trigger(unsigned int cycle) { + printf("cycle: %u\n", cycle); + + + bool flagGotValues = true; + printf("Input Sample Values:\n"); + for (auto &slot : vInputVariables) { + float sampleValue; + if (!(slot->get_slaveAgentValue(&sampleValue))) + flagGotValues = false; //program never executes this line of code + printf("In, %s: %f\n", slot->get_comPort()->get_name(), sampleValue); + + if (cycle == 1) + csv_writer->write_field(slot->get_comPort()->get_name()); + else + csv_writer->write_field(sampleValue); + csv_writer->make_new_field(); + } + printf("Output Sample Values:\n"); + for (auto &slot : vOutputVariables) { + float sampleValue; + if (!(slot->get_slaveAgentValue(&sampleValue))) + flagGotValues = false; //program never executes this line of code + printf("Out, %s: %f\n", slot->get_comPort()->get_name(), sampleValue); + + if (cycle == 1) + csv_writer->write_field(slot->get_comPort()->get_name()); + else + csv_writer->write_field(sampleValue); + csv_writer->make_new_field(); + } + + if (cycle == 1){ + csv_writer->write_field("State Nr"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf State Valid"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf State Invalid"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf Input unchanged"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf Input changed"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf Output unchanged"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf Output changed"); + csv_writer->make_new_field(); + + csv_writer->write_field("Status"); + csv_writer->make_new_field(); + + csv_writer->write_field("Conf Status"); + csv_writer->make_new_field(); + } + else { + //in the beginning, a active state has to be created + if (activeState == NULL && vStates.empty()) { + brokenCounter = 0; + + printf(" > new active state\n"); + makeNewActiveState(); + if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize)) + addActiveStateToStateVector(); + //NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime + float newBoundary = (float)activeState->getLengthOfHistory(); + FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary); + FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary); + + csv_writer->write_field((int)vStates.size() + 1); + csv_writer->make_new_field(); + + csv_writer->write_field(activeState->getConfStateValid()); + csv_writer->make_new_field(); + + csv_writer->write_field(activeState->getConfStateInvalid()); + csv_writer->make_new_field(); + + csv_writer->write_field(0); //confInputVarAreSim2ActiveState + csv_writer->make_new_field(); + + csv_writer->write_field(0); //confInputVarAreDif2ActiveState + csv_writer->make_new_field(); + + csv_writer->write_field(0); //confOutputVarAreSim2ActiveState + csv_writer->make_new_field(); + + csv_writer->write_field(0); //confOutputVarAreDif2ActiveState + csv_writer->make_new_field(); + + + csv_writer->write_field(STATUS_OKAY); + csv_writer->make_new_field(); + + csv_writer->write_field(0); //Status Conf + csv_writer->make_new_field(); + + + } + //there is an active state and/or other states + else { + float confInputVarAreSim2ActiveState = activeState->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + float confInputVarAreDif2ActiveState = activeState->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + float confOutputVarAreSim2ActiveState = activeState->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + float confOutputVarAreDif2ActiveState = activeState->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + + float confInputIsSteady = confInputVarAreSim2ActiveState - confInputVarAreDif2ActiveState; + float confOutputIsSteady = confOutputVarAreSim2ActiveState - confOutputVarAreDif2ActiveState; + + printf("input (sim/dif) %f/%f\noutput (sim/dif) %f/%f\n", confInputVarAreSim2ActiveState, confInputVarAreDif2ActiveState, confOutputVarAreSim2ActiveState, confOutputVarAreDif2ActiveState); + + + //same state + if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) { + brokenCounter = 0; + + printf(" > same state\n"); + if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize)) + addActiveStateToStateVector(); + //NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime + float newBoundary = (float)activeState->getLengthOfHistory(); + FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary); + FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary); + + //print state number + if(activeState->isStateValid()) + csv_writer->write_field((int)vStates.size()); + else + csv_writer->write_field((int)vStates.size()+1); + csv_writer->make_new_field(); + + //print conf valid + csv_writer->write_field(activeState->getConfStateValid()); + csv_writer->make_new_field(); + csv_writer->write_field(activeState->getConfStateInvalid()); + csv_writer->make_new_field(); + + //print conf statechange + csv_writer->write_field(confInputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confInputVarAreDif2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreDif2ActiveState); + csv_writer->make_new_field(); + + + confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation); + float confidenceNoDrift = 1 - confidenceDrift; + + /* + //print conf drift + csv_writer->write_field(confidenceNoDrift); + csv_writer->make_new_field(); + csv_writer->write_field(confidenceDrift); + csv_writer->make_new_field(); + */ + + if (confidenceDrift > 0.5) { + setColor(TXTCOLOR_YELLOW); + printf("DRIFT\n"); +#ifdef STOP_WHEN_DRIFT + getchar(); +#endif // STOP_WHEN_DRIFT + setColor(TXTCOLOR_GREY); + + //print drift + csv_writer->write_field(STATUS_DRIFT); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(fuzzyAND(confidenceDrift, activeState->getConfStateValid()), fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState)); + csv_writer->write_field(conf); + + } + else { + setColor(TXTCOLOR_LIGHTGREEN); + printf("OK\n"); + setColor(TXTCOLOR_GREY); + + //print ok + csv_writer->write_field(STATUS_OKAY); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift)); + csv_writer->write_field(conf); + } + csv_writer->make_new_field(); + + + + } + //state change + else { + //was Valid + if (activeState->isStateValid()) { + + //only one sub set changed + if (((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState <= confOutputVarAreDif2ActiveState)) || ((confInputVarAreSim2ActiveState <= confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState))) { + + + //print state number + if (activeState->isStateValid()) + csv_writer->write_field((int)vStates.size()); + else + csv_writer->write_field((int)vStates.size() + 1); + csv_writer->make_new_field(); + + //print conf valid + csv_writer->write_field(activeState->getConfStateValid()); + csv_writer->make_new_field(); + csv_writer->write_field(activeState->getConfStateInvalid()); + csv_writer->make_new_field(); + + //print conf statechange + csv_writer->write_field(confInputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confInputVarAreDif2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreDif2ActiveState); + csv_writer->make_new_field(); + + + + + + + + brokenCounter++; + printf("brokenCounter: %u\n", brokenCounter); + + confidenceBroken = FuncBlockConfBrokenSamples->getY((float) brokenCounter); + float confidenceOK = 1 - confidenceBroken; + + if (confidenceBroken > 0.5) { + setColor(TXTCOLOR_LIGHTRED); + printf("BROKEN\n"); + setColor(TXTCOLOR_GREY); +#ifdef STOP_AFTER_BROKEN + brokentest = 1; +#endif // STOP_AFTER_BROKEN +#ifdef STOP_WHEN_BROKEN + getchar(); +#endif // STOP_WHEN_BROKEN + + //print broken + csv_writer->write_field(STATUS_BROKEN); + csv_writer->make_new_field(); + + //calculate and print conf + float conf = fuzzyAND(fuzzyOR(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(confidenceBroken, activeState->getConfStateValid())); + csv_writer->write_field(conf); + //csv_writer->make_new_field(); + } + else { + //print ok + csv_writer->write_field(STATUS_OKAY); + csv_writer->make_new_field(); + + //calculate and print conf + float conf = fuzzyAND(fuzzyOR(fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState), fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState)), fuzzyAND(confidenceOK, activeState->getConfStateValid())); + csv_writer->write_field(conf); + } + + + + + + + } + //In- and output changed + else { + brokenCounter = 0; + + printf(" > delete active state\n"); + activeState = NULL; + printf(" > new active state\n"); + + // search in vector for matching state //TODO in future: look for the best matching, Not for the first matching + bool flagFoundMatchingState = false; + float confInputVarAreSim2ActiveState; + float confInputVarAreDif2ActiveState; + float confOutputVarAreSim2ActiveState; + float confOutputVarAreDif2ActiveState; + for (auto &state : vStates) { + confInputVarAreSim2ActiveState = state->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + confInputVarAreDif2ActiveState = state->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + confOutputVarAreSim2ActiveState = state->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + confOutputVarAreDif2ActiveState = state->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + + if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) { + activeState = state; + flagFoundMatchingState = true; + } + } + + if (flagFoundMatchingState == false) { + makeNewActiveState(); + confInputVarAreSim2ActiveState = 0; + confInputVarAreDif2ActiveState = 0; + confOutputVarAreSim2ActiveState = 0; + confOutputVarAreDif2ActiveState = 0; + } + + //insert in activeState + if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize)) + addActiveStateToStateVector(); + //NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime + float newBoundary = (float)activeState->getLengthOfHistory(); + FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary); + FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary); + + + //print state number + if (activeState->isStateValid()) + csv_writer->write_field((int)vStates.size()); + else + csv_writer->write_field((int)vStates.size() + 1); + csv_writer->make_new_field(); + + //print conf valid + csv_writer->write_field(activeState->getConfStateValid()); + csv_writer->make_new_field(); + csv_writer->write_field(activeState->getConfStateInvalid()); + csv_writer->make_new_field(); + + //print conf statechange + csv_writer->write_field(confInputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confInputVarAreDif2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreDif2ActiveState); + csv_writer->make_new_field(); + + + + + confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation); + float confidenceNoDrift = 1 - confidenceDrift; + + if (confidenceDrift > 0.5) { + setColor(TXTCOLOR_YELLOW); + printf("DRIFT\n"); +#ifdef STOP_WHEN_DRIFT + getchar(); +#endif // STOP_WHEN_DRIFT + setColor(TXTCOLOR_GREY); + + //print drift + csv_writer->write_field(STATUS_DRIFT); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(confidenceDrift, activeState->getConfStateValid()); + csv_writer->write_field(conf); + + } + else { + setColor(TXTCOLOR_LIGHTGREEN); + printf("OK\n"); + setColor(TXTCOLOR_GREY); + + //print ok + csv_writer->write_field(STATUS_OKAY); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift)); + csv_writer->write_field(conf); + } + csv_writer->make_new_field(); + } + + + } + //was NOT Valid + else { + + brokenCounter = 0; + + printf(" > delete active state\n"); + delete activeState; + activeState = NULL; + printf(" > new active state\n"); + + + // search in vector for matching state //TODO in future: look for the best matching, Not for the first matching + bool flagFoundMatchingState = false; + float confInputVarAreSim2ActiveState; + float confInputVarAreDif2ActiveState; + float confOutputVarAreSim2ActiveState; + float confOutputVarAreDif2ActiveState; + for (auto &state : vStates) { + confInputVarAreSim2ActiveState = state->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + confInputVarAreDif2ActiveState = state->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + confOutputVarAreSim2ActiveState = state->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime); + confOutputVarAreDif2ActiveState = state->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime); + + if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) { + activeState = state; + flagFoundMatchingState = true; + } + } + + if (flagFoundMatchingState == false) { + makeNewActiveState(); + confInputVarAreSim2ActiveState = 0; + confInputVarAreDif2ActiveState = 0; + confOutputVarAreSim2ActiveState = 0; + confOutputVarAreDif2ActiveState = 0; + } + + //insert in active state + if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize)) + addActiveStateToStateVector(); + //NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime + float newBoundary = (float)activeState->getLengthOfHistory(); + FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary); + FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary); + + + //print state number + if (activeState->isStateValid()) + csv_writer->write_field((int)vStates.size()); + else + csv_writer->write_field((int)vStates.size() + 1); + csv_writer->make_new_field(); + + //print conf valid + csv_writer->write_field(activeState->getConfStateValid()); + csv_writer->make_new_field(); + csv_writer->write_field(activeState->getConfStateInvalid()); + csv_writer->make_new_field(); + + //print conf statechange + csv_writer->write_field(confInputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confInputVarAreDif2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreSim2ActiveState); + csv_writer->make_new_field(); + csv_writer->write_field(confOutputVarAreDif2ActiveState); + csv_writer->make_new_field(); + + + + + confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation); + float confidenceNoDrift = 1 - confidenceDrift; + + if (confidenceDrift > 0.5) { + setColor(TXTCOLOR_YELLOW); + printf("DRIFT\n"); +#ifdef STOP_WHEN_DRIFT + getchar(); +#endif // STOP_WHEN_DRIFT + setColor(TXTCOLOR_GREY); + + //print drift + csv_writer->write_field(2); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(confidenceDrift, activeState->getConfStateValid()); + csv_writer->write_field(conf); + + } + else { + setColor(TXTCOLOR_LIGHTGREEN); + printf("OK\n"); + setColor(TXTCOLOR_GREY); + + //print ok + csv_writer->write_field(STATUS_OKAY); + csv_writer->make_new_field(); + + //calc and print conf + float conf = fuzzyAND(fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift)); + csv_writer->write_field(conf); + } + csv_writer->make_new_field(); + + + + } + + } + + printf("STATES: %u\n", vStates.size()); + } + } + + csv_writer->make_new_line(); + + if (brokentest) + getchar(); + + + + + + + + + + + + + + + + + + + + + /* + //XXX - only for now + for (unsigned int i = 1; i < (cycle - old_cycle); i++) { + csv_writer->make_new_field(); + csv_writer->make_new_field(); + csv_writer->make_new_field(); + csv_writer->make_new_line(); + //printf("%u\n", i); + } + old_cycle = cycle; + + confidenceStableInput = getConfVariablesAreStable(&vInputVariables); + confidenceStableOutput = getConfVariablesAreStable(&vOutputVariables); + confidenceStable = minValueOf2Values(confidenceStableInput, confidenceStableOutput); + printf("confidence stable: %f\n", confidenceStable); + + + confidenceUnstableInput = getConfVariablesAreUnstable(&vInputVariables); + confidenceUnstableOutput = getConfVariablesAreUnstable(&vOutputVariables); + printf("unstable In: %f, Out: %f\n", confidenceUnstableInput, confidenceUnstableOutput); + confidenceUnstable = maxValueOf2Values(confidenceUnstableInput, confidenceUnstableOutput); + printf("confidence unstable: %f\n", confidenceUnstable); + + if (confidenceUnstableInput > 0) { + printf("jetzt\n"); + getchar(); + } + + + //TEST + if (confidenceStable > confidenceUnstable) { + setColor(TXTCOLOR_LIGHTBLUE); + printf("jetzt\n"); + setColor(TXTCOLOR_GREY); + + getchar(); + } + + //getchar(); + + + if (confidenceStable > confidenceUnstable) { + //if (false) { + printf(" > stable\n"); + + //for the beginning (there is no state available/created) -> create state + if (activeState == NULL && vStates.empty()) { + printf(" > new state\n"); + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections()); + } + //there is an active state + else if (activeState != NULL) { + + //caclulate confidences of deciding for same state + float confidenceSameStateInput = activeState->inputVariablesAreRelatedFuzzy(SameState); + float confidenceSameStateOutput = activeState->outputVariablesAreRelatedFuzzy(SameState); + printf("ConfSameState\nIn: %f\nout: %f\n", confidenceSameStateInput, confidenceSameStateOutput); + + + //In- and Outputs are unchanged + if ((confidenceSameStateInput > confSameStateInputAdjustableThreshold) && (confidenceSameStateOutput > confSameStateOutputAdjustableThreshold)) { + + printf(" > same state\n"); + + //inject values + activeState->injectValues(discreteAveragePartitionSize); + //calculate the confidence to have a validState + confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections()); + + //TODO DATE + //check for drifting!!! + //printDrift(); + + + } + //In- and Outputs have changed + else if ((confidenceSameStateInput <= confSameStateInputAdjustableThreshold) && (confidenceSameStateOutput <= confSameStateOutputAdjustableThreshold)) { + + printf(" > change state\n"); + getchar(); + //active state is/was valid + if (confidenceValidState > confValidStateAdjustableThreshold) { + + printf("speicher\n"); + getchar(); + + + addActiveStateToStateVector(); + + //TODO DATE + //search for matching state + //or + printf(" > new state\n"); + //create an new active state + makeNewActiveState(); + + //inject values + activeState->injectValues(discreteAveragePartitionSize); + //calculate the confidence to have a validState + confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections()); + + //TODO DATE + //check for drifting!!! + //printDrift(); + + } + } + //Only in- or outputs have changed + else { + //active state is/was valid + if (confidenceValidState > confValidStateAdjustableThreshold) { + + addActiveStateToStateVector(); + + printf(" > broken\n"); + brokenCounter++; + confidenceBroken = BrokenCounterSamples->getY(brokenCounter); + + //getchar(); + + //TODO DATE?? + //Save State + } + } + } + //there is no active state, but there is/are state(s) + else { + + printf(" > old or new state\n"); + + //getchar(); + //TODO DATE + //search for matching state + //or + printf(" > new state\n"); + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections()); + + //TODO DATE + //check for drifting!!! + //printDrift(); + } + + + if (activeState != NULL) { + confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation); + } + + //getchar(); + } + //unstable + else { + + printf(" > unstable\n"); + + //there is/was an active state + if (activeState != NULL) { + //delete activeState; + + if (confidenceValidState > confValidStateAdjustableThreshold) + addActiveStateToStateVector(); + + activeState = NULL; + } + } + + //DATE TODO + //STABLE CONFIDENCE MITEINBEZIEHEN + if ((confidenceBroken >= confidenceBroken) && (confidenceBroken > confidenceBrokenAdjustableThreshold)) { + setColor(TXTCOLOR_LIGHTRED); + printf(" >> BROKEN - confidence %f\n", confidenceBroken); + setColor(TXTCOLOR_GREY); + + getchar(); + } + else if (confidenceDrift > confidenceDriftAdjustableThreshold) { + setColor(TXTCOLOR_YELLOW); + printf(" >> DRIFT - confidence %f\n", confidenceDrift); + setColor(TXTCOLOR_GREY); + + //XXXXXXXXXX ???????????????????????????????????? + if (brokenCounter > 0) + brokenCounter--; + + getchar(); + } + else { + setColor(TXTCOLOR_LIGHTGREEN); + + float confidenceOK; + if (confidenceDrift > confidenceBroken) + confidenceOK = 1 - confidenceDrift; + else + confidenceOK = 1 - confidenceBroken; + + printf(" >> SYSTEM OK - confidence %f\n", confidenceOK); + setColor(TXTCOLOR_GREY); + } + + + + printf("brokenCounter %u\n", brokenCounter); + printf("number of states: %i\n", vStates.size()); + */ + + + + + + + + + /* + if (variablesAreStable(&vInputVariables) && variablesAreStable(&vOutputVariables)) { + printf(" > stable\n"); + + //XXX - only for now + csv_writer->write_field(2); //stable + csv_writer->make_new_field(); + + //getchar(); + + if (activeState == NULL && vStates.empty()) { + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + + //XXX - only for now + csv_writer->write_field(1); //new active state + csv_writer->make_new_field(); + csv_writer->make_new_field(); + } + else { + if (activeState != NULL) { + + printf("\nbeginning here:\n"); + + bool flagInputUnchanged = activeState->inputVariablesAreRelated(thresholdToBeRelated); + bool flagOutputUnchanged = activeState->outputVariablesAreRelated(thresholdToBeRelated); + + //input and/or output unchanged? + if (flagInputUnchanged && flagOutputUnchanged) { + activeState->injectValues(discreteAveragePartitionSize); + if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) { + printDrift(); + + //XXX - only for now + csv_writer->make_new_field(); + csv_writer->write_field(1); //drift + csv_writer->make_new_field(); + } + //XXX - only for now + else { + csv_writer->make_new_field(); + csv_writer->make_new_field(); + } + } + else { + if (activeState->getNumOfInjections() >= minNumToBeValidState) { + if ((!flagInputUnchanged && flagOutputUnchanged) || (flagInputUnchanged && !flagOutputUnchanged)) { + printBroken(); + getchar(); + + //XXX - only for now + csv_writer->make_new_field(); + csv_writer->write_field(2); //broken + csv_writer->make_new_field(); + } + else { + addActiveStateToStateVector(); + if (!findRelatedStateAndMakeItActive()) { + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + + //XXX - only for now + csv_writer->write_field(1); //new active state + csv_writer->make_new_field(); + csv_writer->make_new_field(); + } + else { + //next line is new + activeState->resetDiscreteAveragePartitionCounter(); + + //XXX - only for now + csv_writer->write_field(2); //change to existing state + csv_writer->make_new_field(); + + + activeState->injectValues(discreteAveragePartitionSize); + if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) { + printDrift(); + + //XXX - only for now + csv_writer->write_field(1); //drift + csv_writer->make_new_field(); + } + //XXX - only for now + else { + csv_writer->make_new_field(); + } + } + } + } + else { + delete activeState; + if (!findRelatedStateAndMakeItActive()) { + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + + //XXX - only for now + csv_writer->write_field(1); //new active state + csv_writer->make_new_field(); + csv_writer->make_new_field(); + } + else { + //next line is new + activeState->resetDiscreteAveragePartitionCounter(); + + //XXX - only for now + csv_writer->write_field(2); //change to existing state + csv_writer->make_new_field(); + + activeState->injectValues(discreteAveragePartitionSize); + if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) { + printDrift(); + + //XXX - only for now + csv_writer->write_field(1); //drift + csv_writer->make_new_field(); + } + //XXX - only for now + else { + csv_writer->make_new_field(); + } + } + } + } + } + else { + if (!findRelatedStateAndMakeItActive()) { + makeNewActiveState(); + activeState->injectValues(discreteAveragePartitionSize); + + //XXX - only for now + csv_writer->write_field(1); //new active state + csv_writer->make_new_field(); + csv_writer->make_new_field(); + } + else { + //next line is new + activeState->resetDiscreteAveragePartitionCounter(); + + //XXX - only for now + csv_writer->write_field(2); //change to existing state + csv_writer->make_new_field(); + + activeState->injectValues(discreteAveragePartitionSize); + if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) { + printDrift(); + + //XXX - only for now + csv_writer->write_field(1); //drift + csv_writer->make_new_field(); + } + //XXX - only for now + else { + csv_writer->make_new_field(); + } + } + } + } + + + + + + if (activeState != NULL) { + printf(" -- an activeState exist: \n"); + printf(" --- injections: %u\n", activeState->getNumOfInjections()); + + //XXX - only for now + csv_writer->write_field((int)activeState->getNumOfInjections()); //number of injections + csv_writer->make_new_line(); + } + //XXX - only for now + else { + csv_writer->make_new_field(); + } + + + printf(" -- Number of States (excl. activeState): %u\n", vStates.size()); + for (auto &s : vStates) { + printf(" --- injections: %u\n", s->getNumOfInjections()); + } + printf(" ... BrokenCounter: %u\n", brokenCounter); + printf(" ... driftCounter: %u\n", driftCounter); + printf("cycle: %u\n", cycle); + + + if (test) { + test = false; + //getchar(); + } + + flagVariablesWereStable = true; + } + + else { + + printf(" > unstable\n"); + //XXX - only for now + csv_writer->write_field(1); //unstable + csv_writer->make_new_field(); + csv_writer->make_new_field(); + csv_writer->make_new_field(); + csv_writer->make_new_line(); + + + if (flagVariablesWereStable) + test = true; + + //search for states with less injections in all states + if (flagVariablesWereStable) { + if (activeState != NULL) { + + if (activeState->getNumOfInjections() >= minNumToBeValidState) { + addActiveStateToStateVector(); + + } + else { + delete activeState; + } + activeState = NULL; + + + //getchar(); + + } + } + + flagVariablesWereStable = false; + } + + + + //xxx - only for now + //csv_writer->make_new_line(); + */ +} + + +void StateHandler::closeCsvFile() { + if(csv_writer != NULL) + csv_writer->close_file(); +} + +string StateHandler::create_Output_File_Name(string cfg_parameter) +{ + time_t rawtime; + struct tm * timeinfo; + char output_file_name[200]; + char datetime[80]; + const std::string output_directory_name = "./output_data_csv/OMV/"; + std::string output_file_name_str; + + time(&rawtime); + timeinfo = localtime(&rawtime); + + strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", timeinfo); + output_file_name_str = output_directory_name + "output" + datetime + cfg_parameter + ".csv"; + //cout << output_file_name_str << endl; + + return output_file_name_str; +} + +void StateHandler::set_CSV_Writer_parameter(string cfg_parameter) +{ + string cur_Output_File_Name = this->create_Output_File_Name(cfg_parameter); + csv_writer->reset_fpointer(cur_Output_File_Name); +} + + + +/* +void StateHandler :: initStateHandler() { + //activeState = NULL; + thresholdToAverage = THRESHOLDTOAVG; + minNumOfChangedForValidStateChange = MINNUMCHANGEDFORVALIDSTATECHANGE; + + minimumInjectionsForBeingState = MININJFORBEINGSTATE; +} + +StateHandler :: StateHandler() { + set_name(NO_NAME); + initStateHandler(); +} + +StateHandler :: StateHandler(char* name) { + set_name(name); + initStateHandler(); +} + +bool StateHandler :: setMinimumInjectionsForBeingState(unsigned int minimumInjectionsForBeingState) { + if (minimumInjectionsForBeingState > 0) { + this->minimumInjectionsForBeingState = minimumInjectionsForBeingState; + return true; + } + return false; +} + +unsigned int StateHandler :: getMinimumInjectionsForBeingState() { + return minimumInjectionsForBeingState; +} + +bool StateHandler :: add_slot(SlaveAgentSlotOfAgent* slot) { + if(slot != NULL) { + try { + vSlots.push_back(slot); + return true; + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete slot; + } + } + return false; +} + +void StateHandler :: setThresholdToAverage(float thresholdToAverage) { + this->thresholdToAverage = thresholdToAverage; +} + +float StateHandler :: getThresholdToAverage() { + return thresholdToAverage; +} + +void StateHandler::set_minNumOfChangedForValidStateChange(unsigned int minNumOfChangedForValidStateChange) { + this->minNumOfChangedForValidStateChange = minNumOfChangedForValidStateChange; +} + +unsigned int StateHandler::get_minNumOfChangedForValidStateChange() { + return minNumOfChangedForValidStateChange; +} + + +bool StateHandler :: trigger() { + + bool flagWorked = true; + + printf("NumOfStates: "); + for (auto &slot : vSlots) { + printf("%u, ", slot->getNumberOfStates()); + } + printf("\n"); + + + //Check all input values if they have changed more than threshold ...and count how many changed + unsigned int numberOfChanges = 0; + for (auto &slot : vSlots) { + float value; + if (slot->get_slaveAgentValue(&value)) { + + State* activeState = slot->getActiveState(); + if (activeState != NULL) { + printf("act - "); + if (activeState->isNew()) { + printf("new - "); + //numberOfChanges++; + } + else if (activeState->valueIsRelated(value, thresholdToAverage)) { + printf("rel - "); + } + else { + printf("nrel - "); + numberOfChanges++; + } + } + + else { + printf("nact - "); + } + } + } + printf("\n"); + + + + + + + + + + printf(" >> Number of Changes: %u\n", numberOfChanges); + //nothing has changes more than threshold + + if (numberOfChanges == 0) { + printf("\n\n >>> inject in active state\n"); + for (auto &slot : vSlots) { + slot->injectValueInActiveState(); + } + } + else if(numberOfChanges >= minNumOfChangedForValidStateChange) { + printf("\n\n >>> new (or another) state\n"); + + for (auto &slot : vSlots) { + State* activeState = slot->getActiveState(); + if (activeState != NULL) { + if (activeState->getNumberOfInjections() < minimumInjectionsForBeingState) { + slot->deleteActiveState(); + printf(" >> delete State\n"); + } + } + } + + //search for existing state + bool flagRelated = false; + if (vSlots.empty() == false) { + int ix = vSlots.front()->getIndexOfRelatedState(0, thresholdToAverage); + while (ix > -2) { + if (ix >= 0) { + //TODO: maybe another state fits a bit better.. approach -> euklidean distance? + flagRelated = true; + for (vector::iterator slot = vSlots.begin() + 1; slot < vSlots.end(); slot++) { + if ((*slot)->valueIsRelated(ix, thresholdToAverage) == false) { + flagRelated = false; + } + } + if (flagRelated == true) { + for (auto &slot : vSlots) { + slot->setActiveState(ix); + } + break; + } + ix = vSlots.front()->getIndexOfRelatedState(ix+1, thresholdToAverage); + } + } + } + + if (flagRelated == false) { + printf(" >> No related state found\n"); + + printf("\n\n >>> inject in active state\n"); + for (auto &slot : vSlots) { + slot->injectValueInActiveState(); + } + } + + + } + + + printf("ende\n"); + + return false; +} +*/ diff --git a/Version_Max_07_05_2018_CMake/src/StateHandler.h b/Version_Max_07_05_2018_CMake/src/StateHandler.h new file mode 100755 index 0000000..fcfc650 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateHandler.h @@ -0,0 +1,194 @@ +#ifndef STATEHANDLER_HEADERFILE +#define STATEHANDLER_HEADERFILE + +#include "Module.h" +#include "SlaveAgentSlotOfAgent.h" +#include "State.h" + +#include "StateVariable.h" +#include + +//XXX - only for now +#include "CSV_Writer.h" +#include "LinearFunctionBlock.h" + + +using namespace std; + + +class StateHandler : public Module { + public: + LinearFunctionBlock* StabSamples; + LinearFunctionBlock* StabDeviation; + LinearFunctionBlock* UnstabDeviation; + LinearFunctionBlock* SameState; + LinearFunctionBlock* DriftDeviation; + LinearFunctionBlock* BrokenCounterSamples; + LinearFunctionBlock* ValidState; + + //NEU: + //compare + LinearFunctionBlock* FuncBlockConfSim2StateDev; + LinearFunctionBlock* FuncBlockConfDif2StateDev; + LinearFunctionBlock* FuncBlockConfSim2StateTime; + LinearFunctionBlock* FuncBlockConfDif2StateTime; + //insert + LinearFunctionBlock* FuncBlockConfValStateDev; + LinearFunctionBlock* FuncBlockConfInvStateDev; + LinearFunctionBlock* FuncBlockConfValStateTime; + LinearFunctionBlock* FuncBlockConfInvStateTime; + + LinearFunctionBlock* FuncBlockConfBrokenSamples; + + + + + + private: + + //DATE18 + //XXX - >0,5? + //discreate Average Partition Size adjustable? + float confidenceStableInput; + float confidenceStableOutput; + float confidenceStable; + float confStableAdjustableThreshold; + + float confidenceUnstableInput; + float confidenceUnstableOutput; + float confidenceUnstable; + float confidenceUnstableAdjustableThreshold; + + float confidenceSameStateInput; + float confSameStateInputAdjustableThreshold; + float confidenceSameStateOutput; + float confSameStateOutputAdjustableThreshold; + + float confidenceValidState; + float confValidStateAdjustableThreshold; + + unsigned int brokenCounter; + float confidenceBroken; + float confidenceBrokenAdjustableThreshold; + + unsigned int driftCounter; + float confidenceDrift; + float confidenceDriftAdjustableThreshold; + + + + //XXX - Maybe Object "StateVariable" between StateHandler and Slot?! + vector vInputVariables; + vector vOutputVariables; + + vector vStates; + State* activeState; + unsigned int minNumToBeValidState; + + bool flagVariablesWereStable; + unsigned int slidingWindowBufferSize; + unsigned int minNumOfRelatedValuesToBeStable; + float thresholdToBeStable; + + float thresholdToBeRelated; + + unsigned int discreteAveragePartitionSize; + unsigned int compareDistanceDiscreteAveragePartition; + float thresholdNotDrift; + + unsigned int maxStateHistoryLength; + + void initStateHandler(); + + bool addVariable(vector* vVariables, SlaveAgentSlotOfAgent* slot); + bool variablesAreStable(vector* vVariables); + + //DATE18 + float getConfVariableIsStable(SlaveAgentSlotOfAgent* variable); + float getConfVariablesAreStable(vector* vVariables); + float getConfVariableIsUnstable(SlaveAgentSlotOfAgent* variable); + float getConfVariablesAreUnstable(vector* vVariables); + + //bool getConfAndUnconfVariableIsMatching(SlaveAgentSlotOfAgent* variable, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf); + bool getConfAndUnconfVariableIsMatching(State* state, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf); + bool getConfAndUnconfVariablesAreMatching(vector* vVariables, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf); + + + State* makeNewState(); + + string create_Output_File_Name(string cfg_Parameter); + + bool addActiveStateToStateVector(); + //bool addStateAndMakeItActive(); + + bool makeNewActiveState(); + + State* findRelatedState(); + bool findRelatedStateAndMakeItActive(); + + void eraseStatesWithLessInjections(); + + bool delete_all_OuputVariables(); + bool delete_all_InputVariables(); + bool delete_allStates(); + //XXX - only for now: + CSV_Writer* csv_writer; + + + public: + StateHandler(); + StateHandler(char* name); + + bool setDiscreteAveragePartitionSize(unsigned int discreteAverage); + unsigned int getDiscreteAveragePartitionSize(); + + bool addInputVariable(SlaveAgentSlotOfAgent* slot); + bool addOutputVariable(SlaveAgentSlotOfAgent* slot); + + bool setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize); + bool setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable); + bool setThresholdToBeStable(float thresholdToBeStable); + + bool setThresholdToBeRelated(float thresholdToBeRelated); + + void trigger(unsigned int cycle); + + //XXX - only for now + void closeCsvFile(); + + void set_CSV_Writer_parameter(string cfg_parameter); + void reset_States(); + void reset_States_and_Slave_Agents(); + + ~StateHandler(); + + + + /* + private: + vector vSlots; + + unsigned int minNumOfChangedForValidStateChange; + + unsigned int minimumInjectionsForBeingState; + + void initStateHandler(); + + public: + StateHandler(); + StateHandler(char* name); + + bool setMinimumInjectionsForBeingState(unsigned int minimumInjectionsForBeingState); + unsigned int getMinimumInjectionsForBeingState(); + + //TODO: function for deleting slot and function with the whole vector as parameter + bool add_slot(SlaveAgentSlotOfAgent* slot); + + void set_minNumOfChangedForValidStateChange(unsigned int minNumOfChangedForValidStateChange); + unsigned int get_minNumOfChangedForValidStateChange(); + + bool trigger(); + */ +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/StateModule.cpp b/Version_Max_07_05_2018_CMake/src/StateModule.cpp new file mode 100755 index 0000000..d8186fb --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateModule.cpp @@ -0,0 +1,84 @@ +#include "StateModule.h" + + +/* +#include "printError.h" + +#define MAX_NUM_OF_STATES 1000 + +void StateModule :: initStateModule() { + if(MAX_NUM_OF_STATES <= vStates.max_size()) { + maxNumOfStates = MAX_NUM_OF_STATES; + } + else { + maxNumOfStates = vStates.max_size(); + } + + delimitationMode = DELIMITATE_MODE_SRWF; +} + +StateModule :: StateModule() { + set_name(NO_NAME); + initStateModule(); +} + +StateModule :: StateModule(char* name) { + initStateModule(); + set_name(name); +} + +bool StateModule :: set_maxNumOfStates(unsigned int maxNumOfStates) { + if(maxNumOfStates <= MAX_NUM_OF_STATES && maxNumOfStates <= vStates.max_size()) { + this->maxNumOfStates = maxNumOfStates; + return true; + } + return false; +} + +unsigned int StateModule :: get_maxNumOfStates() { + return maxNumOfStates; +} + +bool StateModule :: set_delimitationMode(int delimitationMode) { + if(delimitationMode > DELIMITATE_MODE_LBOUND && delimitationMode < DELIMITATE_MODE_UBOUND) { + this->delimitationMode = delimitationMode; + return true; + } + return false; +} + +int StateModule :: get_delimitationMode() { + return delimitationMode; +} + +State* StateModule :: add_state() +{ + if(vStates.size() <= maxNumOfStates) { + State* state = new State(); + if(state != NULL) { + + try { + vStates.push_back(state); + return state; + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + } + } + else { + printError("Couldn't create new State!"); + } + } + else { + switch(delimitationMode) { + case DELIMITATE_MODE_SRWF: + printError("Limit of States reached!"); + break; + default : + printError("Limit of States reached! DelimitationMode isn't set!"); + break; + } + } + return NULL; +} +*/ \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/StateModule.h b/Version_Max_07_05_2018_CMake/src/StateModule.h new file mode 100755 index 0000000..8ee31ed --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateModule.h @@ -0,0 +1,34 @@ +#ifndef STATEMODULE_HEADERFILE +#define STATEMODULE_HEADERFILE +/* +#include "State.h" +#include "Module.h" +#include + +using namespace std; + +class StateModule : public Module { + + private: + vector vStates; + unsigned int maxNumOfStates; + int delimitationMode; + + void initStateModule(); + + public: + StateModule(); + StateModule(char* name); + + bool set_maxNumOfStates(unsigned int maxNumOfStates); + unsigned int get_maxNumOfStates(); + + bool set_delimitationMode(int delimitationMode); + int get_delimitationMode(); + + State* add_state(); + +}; +*/ + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/StateVariable.cpp b/Version_Max_07_05_2018_CMake/src/StateVariable.cpp new file mode 100755 index 0000000..c610ca6 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateVariable.cpp @@ -0,0 +1,5 @@ +#include "StateVariable.h" + +StateVariable::StateVariable() { + +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/StateVariable.h b/Version_Max_07_05_2018_CMake/src/StateVariable.h new file mode 100755 index 0000000..31e3413 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StateVariable.h @@ -0,0 +1,19 @@ +#ifndef STATEVARIABLE_HEADERFILE +#define STATEVARIABLE_HEADERFILE + +#include "SlaveAgentSlotOfAgent.h" + +class StateVariable { + +private: + //TODO: for all slots ... generalize slot (not SlavAgent and Sensor) + SlaveAgentSlotOfAgent* slot; + +public: + StateVariable(); + + + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/StatisticValue.cpp b/Version_Max_07_05_2018_CMake/src/StatisticValue.cpp new file mode 100755 index 0000000..2cf7fc3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StatisticValue.cpp @@ -0,0 +1,15 @@ +#include "StatisticValue.h" + +StatisticValue :: StatisticValue() { + +} + +void StatisticValue :: resetStatisticValue() { + resetAverageValue(); + resetExtremeValue(); +} + +void StatisticValue ::injectAndCalculateStatisticValue(float value) { + injectAndCalculateAverageValue(value); + injectAndCalculateExtremeValue(value); +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/StatisticValue.h b/Version_Max_07_05_2018_CMake/src/StatisticValue.h new file mode 100755 index 0000000..c9b298b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/StatisticValue.h @@ -0,0 +1,18 @@ +#ifndef STATISTICVALUE_HEADERFILE +#define STATISTICVALUE_HEADERFILE + +#include "AverageValue.h" +#include "ExtremeValue.h" + +class StatisticValue : public AverageValue, public ExtremeValue { + +public: + StatisticValue(); + + void resetStatisticValue(); + + void injectAndCalculateStatisticValue(float value); + +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/SubState.cpp b/Version_Max_07_05_2018_CMake/src/SubState.cpp new file mode 100755 index 0000000..4a62dda --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SubState.cpp @@ -0,0 +1,347 @@ +#include "SubState.h" + +#include "printError.h" +#include "relationChecker.h" + +#include "minmaxzeug.h" +#include +#include +#include + +SubState::SubState() { + confidenceValidState = 0; + confidenceInvalidState = 1; +} + +void SubState::setSlot(SlaveAgentSlotOfAgent* slot) { + this->slot = slot; +} + +SlaveAgentSlotOfAgent* SubState::getSlot() { + return slot; +} + +bool SubState::addNewDiscreteAverage() { + + AverageValue* averageValue = new (nothrow) AverageValue(); + if (averageValue != NULL) { + try { + vDiscreteAverage.push_back(averageValue); + + //printf("vDiscreteAverage size = %u\n", vDiscreteAverage.size()); + + return true; + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + delete averageValue; + } + } + return false; +} + + +bool SubState::injectValue() { + float value; + + if (slot->get_slaveAgentValue(&value)) { + statisticValue.injectAndCalculateStatisticValue(value); + + if (!vDiscreteAverage.empty()) { + vDiscreteAverage.back()->injectAndCalculateAverageValue(value); + return true; + } + } + + return false; +} + + +bool SubState::valueIsRelated(float thresholdToBeRelated) { + float value; + if (slot->get_slaveAgentValue(&value)) { + return valueIsRelatedToReferenceValueOrBetweenMinAndMax(statisticValue.getAverageValue(), statisticValue.getMinimumValue(), statisticValue.getMaximumValue(), value, thresholdToBeRelated); + } + + return false; +} + +unsigned int SubState::getNumOfInjections() { + return statisticValue.getInjectedValuesCounter(); +} + +bool SubState::lastDiscreteAverageBlockIsCompleted(unsigned int discreteAveragePartitionSize) { + if (!vDiscreteAverage.empty()) { + if (vDiscreteAverage.back()->getInjectedValuesCounter() < discreteAveragePartitionSize) { + return false; + } + } + return true; +} + +unsigned int SubState::getNumberOfCompletedDiscreteAverageBlocks(unsigned int discreteAveragePartitionSize) { + + unsigned int numberOfDiscreteAverageBlocks = vDiscreteAverage.size(); + + //printf("vDiscreteAverage.size() = %u\n", numberOfDiscreteAverageBlocks); + + if (!lastDiscreteAverageBlockIsCompleted(discreteAveragePartitionSize)) { + numberOfDiscreteAverageBlocks--; + } + + return vDiscreteAverage.size(); +} + + +float SubState::getDiscreteAverageOfFirstBlock(unsigned int discreteAveragePartitionSize) { + + if (getNumberOfCompletedDiscreteAverageBlocks(discreteAveragePartitionSize) > 0) { + return vDiscreteAverage.front()->getAverageValue(); + } + //TODO: error handling - return 0 is not acceptable + return 0; +} + +float SubState::getDiscreteAverageOfLastBlock(unsigned int discreteAveragePartitionSize) { + + if (lastDiscreteAverageBlockIsCompleted(discreteAveragePartitionSize)) { + return vDiscreteAverage.back()->getAverageValue(); + } + else if (vDiscreteAverage.size() > 1) { + return vDiscreteAverage.at(vDiscreteAverage.size()-1)->getAverageValue(); + } + //TODO: error handling - return 0 is not acceptable + return 0; +} + +float SubState::getDiscreteAverageOfBlockBeforeLastBlock(unsigned int discreteAveragePartitionSize, unsigned int jumpBackDistance) { + + + if (getNumberOfCompletedDiscreteAverageBlocks(discreteAveragePartitionSize) > jumpBackDistance) { + + if (lastDiscreteAverageBlockIsCompleted(discreteAveragePartitionSize)) { + return vDiscreteAverage.at(vDiscreteAverage.size() - jumpBackDistance)->getAverageValue(); + } + else { + return vDiscreteAverage.at(vDiscreteAverage.size() - (jumpBackDistance + 1))->getAverageValue(); + } + + } + else { + return vDiscreteAverage.front()->getAverageValue(); + } +} + +void SubState::deleteLastDiscreteAverageBlockIfNotCompleted(unsigned int discreteAveragePartitionSize) { + if (!vDiscreteAverage.empty()) { + if (vDiscreteAverage.back()->getInjectedValuesCounter() < discreteAveragePartitionSize) { + vDiscreteAverage.pop_back(); + } + } +} + +//DATE18 +float SubState::valueIsRelatedFuzzy(LinearFunctionBlock* SameState) { + + //XXX - Original war: valueIsRelatedToReferenceValueOrBetweenMinAndMax! + float sampleValue; + if (slot->get_slaveAgentValue(&sampleValue)) { + printf("geht hinein - sample: %f, average: %f\n", sampleValue, statisticValue.getAverageValue()); + return SameState->getY(deviationValueReferenceValue(sampleValue, statisticValue.getAverageValue())); + } + + printf("leider hier\n"); + + //todo: isn't the best error handling + return 0; +} + +bool SubState::insertValueInSubState(LinearFunctionBlock* FuncBlockConfValStateDev, LinearFunctionBlock* FuncBlockConfInvStateDev, LinearFunctionBlock* FuncBlockConfValStateTime, LinearFunctionBlock* FuncBlockConfInvStateTime, unsigned int historySize) { + + bool insertionWorked = true; + + float sampleValue; + if (slot->get_slaveAgentValue(&sampleValue)) { + + //statistic value + statisticValue.injectAndCalculateStatisticValue(sampleValue); + + //DABs + if (vDiscreteAverage.empty()) + insertionWorked = false; + else + vDiscreteAverage.back()->injectAndCalculateAverageValue(sampleValue); + + float worstConfidenceDeviation = 1; + float bestConfidenceDeviation = 0; + for (auto &historyValue : lSampleHistory) { + bestConfidenceDeviation = maxValueOf2Values(bestConfidenceDeviation, FuncBlockConfInvStateDev->getY(deviationValueReferenceValue(sampleValue, historyValue))); + worstConfidenceDeviation = minValueOf2Values(worstConfidenceDeviation, FuncBlockConfValStateDev->getY(deviationValueReferenceValue(sampleValue, historyValue))); + } + lBestConfidencesDeviation.push_front(bestConfidenceDeviation); + lWorstConfidencesDeviation.push_front(worstConfidenceDeviation); + + //save actual value in history + try { + lSampleHistory.push_front(sampleValue); + } + catch (bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + insertionWorked = false; + } + + //delete last history- and deviation entry if history is full + while (lSampleHistory.size() > historySize) { + lSampleHistory.pop_back(); + lBestConfidencesDeviation.pop_back(); + lWorstConfidencesDeviation.pop_back(); + } + + + //calculate the confidence with that the actual value fits to all of the history values + bestConfidenceDeviation = 0; + worstConfidenceDeviation = 1; + for (auto &confDev : lBestConfidencesDeviation) + bestConfidenceDeviation = minValueOf2Values(bestConfidenceDeviation, confDev); + for (auto &confDev : lWorstConfidencesDeviation) + worstConfidenceDeviation = maxValueOf2Values(worstConfidenceDeviation, confDev); + + + //printf("confidence invalid time: %f\n", FuncBlockConfInvStateTime->getY((float)lSampleHistory.size())); + + + confidenceValidState = minValueOf2Values(worstConfidenceDeviation, FuncBlockConfValStateTime->getY((float)lSampleHistory.size())); + confidenceInvalidState = maxValueOf2Values(bestConfidenceDeviation, FuncBlockConfInvStateTime->getY((float)lSampleHistory.size())); + } + + return insertionWorked; + + + /* + float value; + + if (slot->get_slaveAgentValue(&value)) { + statisticValue.injectAndCalculateStatisticValue(value); + + if (!vDiscreteAverage.empty()) { + vDiscreteAverage.back()->injectAndCalculateAverageValue(value); + return true; + } + } + + return false; + */ + + +} + + +float SubState::getConfidenceValidState() { + return confidenceValidState; +} + +float SubState::getConfidenceInvalidState() { + return confidenceInvalidState; +} + +float SubState::getConfVarIsSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime) { + + float highestConfOf1Var = 0; + float sampleValue; + float deviation = 0.0; + if (slot->get_slaveAgentValue(&sampleValue)) { + + vector vDeviations; + vDeviations.clear(); + + for (auto &h : lSampleHistory) { + deviation = deviationValueReferenceValue(sampleValue, h); + vDeviations.push_back(deviation); + } + + + sort(begin(vDeviations), end(vDeviations)); + + //all adaptabilities within the history of one variable + for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) { + + float lowestConfOfSamplesIncluded = 1; + unsigned int histSampleCounter = 0; + + for (auto &deviation : vDeviations) { + if (histSampleCounter >= numOfHistSamplesIncluded) + break; + lowestConfOfSamplesIncluded = fuzzyAND(lowestConfOfSamplesIncluded, FuncBlockConfSim2StateDev->getY(deviation)); + histSampleCounter++; + } + + highestConfOf1Var = fuzzyOR(highestConfOf1Var, fuzzyAND(lowestConfOfSamplesIncluded, FuncBlockConfSim2StateTime->getY((float)histSampleCounter))); + } + } + + return highestConfOf1Var; +} + +//Sorting with bigger Value in Front +struct descending +{ + template + bool operator()(T const &a, T const &b) const { return a > b; } +}; + +float SubState::getConfVarIsDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime) { + + //float highestConfOf1Var = 0; + float highestConfOf1Var = 1; + float sampleValue; + if (slot->get_slaveAgentValue(&sampleValue)) { + + vector vDeviations; + + for (auto &h : lSampleHistory) + vDeviations.push_back(deviationValueReferenceValue(sampleValue, h)); + + sort(begin(vDeviations), end(vDeviations), descending()); + + //all adaptabilities within the history of one variable + for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) { + + float highestConfOfSamplesIncluded = 0; + unsigned int histSampleCounter = 0; + + for (auto &deviation : vDeviations) { + if (histSampleCounter >= numOfHistSamplesIncluded) + break; + highestConfOfSamplesIncluded = fuzzyOR(highestConfOfSamplesIncluded, FuncBlockConfDif2StateDev->getY(deviation)); + histSampleCounter++; + } + + //highestConfOf1Var = fuzzyOR(highestConfOf1Var, fuzzyOR(highestConfOfSamplesIncluded, FuncBlockConfDif2StateTime->getY((float)histSampleCounter))); + highestConfOf1Var = fuzzyAND(highestConfOf1Var, fuzzyOR(highestConfOfSamplesIncluded, FuncBlockConfDif2StateTime->getY((float)histSampleCounter))); + + } + } + + return highestConfOf1Var; +} + +unsigned int SubState::getSampleHistoryLength() { + return lSampleHistory.size(); +} + +void SubState::remove_Average_Values() +{ + AverageValue* cur_Average_Value; + unsigned int cur_index_Average_Value; + unsigned int size_vec_Avergae_Values = vDiscreteAverage.size(); + for(cur_index_Average_Value = 0; cur_index_Average_Value < size_vec_Avergae_Values; cur_index_Average_Value++){ + cur_Average_Value = vDiscreteAverage[cur_index_Average_Value]; + delete cur_Average_Value; + } + vDiscreteAverage.clear(); +} + +SubState::~SubState() +{ + remove_Average_Values(); +} diff --git a/Version_Max_07_05_2018_CMake/src/SubState.h b/Version_Max_07_05_2018_CMake/src/SubState.h new file mode 100755 index 0000000..6a2310f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/SubState.h @@ -0,0 +1,68 @@ +#ifndef SUBSTATE_HEADERFILE +#define SUBSTATE_HEADERFILE + +#include "SlaveAgentSlotOfAgent.h" +#include "StatisticValue.h" + +#include "LinearFunctionBlock.h" + +class SubState { + + private: + SlaveAgentSlotOfAgent* slot; + StatisticValue statisticValue; + vector vDiscreteAverage; + + bool lastDiscreteAverageBlockIsCompleted(unsigned int discreteAveragePartitionSize); + + list lSampleHistory; + list lBestConfidencesDeviation; + list lWorstConfidencesDeviation; + + + //DATE18 + float confidenceValidState; + float confidenceInvalidState; + + void remove_Average_Values(); + + public: + SubState(); + + void setSlot(SlaveAgentSlotOfAgent* slot); + SlaveAgentSlotOfAgent* getSlot(); + + bool addNewDiscreteAverage(); + + bool injectValue(); + + bool valueIsRelated(float thresholdToBeRelated); + + unsigned int getNumOfInjections(); + + unsigned int getNumberOfCompletedDiscreteAverageBlocks(unsigned int discreteAveragePartitionSize); + + float getDiscreteAverageOfFirstBlock(unsigned int discreteAveragePartitionSize); + float getDiscreteAverageOfLastBlock(unsigned int discreteAveragePartitionSize); + + float getDiscreteAverageOfBlockBeforeLastBlock(unsigned int discreteAveragePartitionSize, unsigned int jumpBackDistance); + + void deleteLastDiscreteAverageBlockIfNotCompleted(unsigned int discreteAveragePartitionSize); + + //DATE18 + float valueIsRelatedFuzzy(LinearFunctionBlock* SameState); + + bool insertValueInSubState(LinearFunctionBlock* FuncBlockConfValStateDev, LinearFunctionBlock* FuncBlockConfInvStateDev, LinearFunctionBlock* FuncBlockConfValStateTime, LinearFunctionBlock* FuncBlockConfInvStateTime, unsigned int historySize); + + float getConfidenceValidState(); + float getConfidenceInvalidState(); + + float getConfVarIsSim2State(LinearFunctionBlock* FuncBlockConfSim2StateDev, LinearFunctionBlock* FuncBlockConfSim2StateTime); + float getConfVarIsDif2State(LinearFunctionBlock* FuncBlockConfDif2StateDev, LinearFunctionBlock* FuncBlockConfDif2StateTime); + + unsigned int getSampleHistoryLength(); + + ~SubState(); +}; + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Testbench.cpp b/Version_Max_07_05_2018_CMake/src/Testbench.cpp new file mode 100755 index 0000000..dc79a27 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Testbench.cpp @@ -0,0 +1,1024 @@ +#include "Testbench.h" + +#include "printError.h" +#include + +using namespace std; + +void Testbench :: init_testbench() { + //TODO + //some init source code to add, if necessary +} + +Testbench :: Testbench() { + set_name(NO_NAME); +} + +Testbench :: Testbench(char* name) { + set_name(name); +} + +bool Testbench :: register_agent(Agent* agent) { + AgentSlotOfTestbench* agentSlot = new AgentSlotOfTestbench(); + if(agentSlot != NULL) { + if(agentSlot->set_agent(agent)) { + try { + if(vector_registeredAgents.size() < MAXNUM_OF_REGISTERED_AGENTS) { + vector_registeredAgents.push_back(agentSlot); + } + else { + printError("Max number of registered agents is already reached!"); + return false; + } + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + return false; + } + return true; + } + else { + printError("Agent is not set!"); + vector_registeredAgents.pop_back(); //TODO: check if it is right?!?! + return false; + } + } + else { + printError("Couldn't create AgentSlot!"); + return false; + } +} + +bool Testbench :: register_sensor(Sensor* sensor) { + SensorSlotOfTestbench* sensorSlot = new SensorSlotOfTestbench(); + if(sensorSlot != NULL) { + if(sensorSlot->set_sensor(sensor)) { + try { + if(vector_registeredSensors.size() < MAXNUM_OF_REGISTERED_SENSORS) { + vector_registeredSensors.push_back(sensorSlot); + } + else { + printError("Max number of registered sensors is already reached!"); + return false; + } + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + return false; + } + return true; + } + else { + printError("Input port is no set!"); + vector_registeredSensors.pop_back(); //TODO: check if it is right?!?! + return false; + } + } + else { + printError("Couldn't create SensorSlot!"); + return false; + } +} + +SensorSlotOfTestbench* Testbench :: get_sensorSlotAddressOfTestbench(Sensor* sensor) { + for(auto &sensorSlot : vector_registeredSensors) { + if(sensorSlot->get_sensor() == sensor) { + return sensorSlot; + } + } + return NULL; +} + + +bool Testbench :: register_channel(Channel* channel) { + ChannelSlotOfTestbench* channelSlot = new ChannelSlotOfTestbench(); + if(channelSlot != NULL) { + if(channelSlot->set_channel(channel)) { + try { + if(vector_registeredChannels.size() < MAXNUM_OF_REGISTERED_CHANNELS) { + vector_registeredChannels.push_back(channelSlot); + } + else { + printError("Max number of registered channels is already reached!"); + return false; + } + } + catch(bad_alloc& error) { + printError("bad_alloc caught: ", error.what()); + return false; + } + return true; + } + else { + printError("Channel is not set!"); + vector_registeredChannels.pop_back(); //TODO: check if it is right?!?! + return false; + } + } + else { + printError("Couldn't create ChannelSlot!"); + return false; + } +} + +bool Testbench :: register_testbench_config(Testbench_Config* tb_config) +{ + vector_registered_Configs.push_back(tb_config); +} + +vector& Testbench :: get_all_registered_testbench_configs() +{ + return vector_registered_Configs; +} + +void Testbench :: simulate(unsigned int rounds) { + for(unsigned int cycle = 1; cycle <=rounds; cycle++) { + + if (cycle == 312) { + printf("DEBUG: Break point"); + } + //printf("cycle %u\n", sec); + + //update sensor values + for(auto &sensorSlot : vector_registeredSensors) { + Sensor *sensor = sensorSlot->get_sensor(); + printf("Name of Sensor %s \n", sensor->get_name()); + if(sensor != NULL) { + CSVreaderModule *csvReader = sensorSlot->get_csvReaderModule(); + if(csvReader != NULL) { + float inputValue; + if(csvReader->get_next_value(&inputValue)) { + sensor->set_sensorValue(inputValue); + } + } + } + } + + //trigger sensors + for(auto &sensorSlot : vector_registeredSensors) { + Sensor *sensor = sensorSlot->get_sensor(); + if(sensor != NULL) { + sensor->trigger(); + } + } + + //trigger channels + for(auto &channelSlot : vector_registeredChannels) { + Channel *channel = channelSlot->get_channel(); + if(channel != NULL) { + channel->trigger(); + } + } + + //trigger agents + for(auto &agentSlot : vector_registeredAgents) { + Agent *agent = agentSlot->get_agent(); + if(agent != NULL) { + agent->trigger(cycle); + } + } + + + + + + //if(sec % 500 == 0) + //getchar(); + } + + + + //XXX - only for now + for (auto &agentSlot : vector_registeredAgents) { + Agent *agent = agentSlot->get_agent(); + if (agent != NULL) { + StateHandler *stateHandler = agent->get_stateHandler2(); + if (stateHandler != NULL) { + stateHandler->closeCsvFile(); + } + } + } + + +} + +vector& Testbench :: get_all_registeredAgents() +{ + return vector_registeredAgents; +} + +void Testbench :: set_current_tb_config_index(const int index) +{ + Testbench_Config::set_active_Config(index); +} + + +void Testbench :: remove_all_Testbench_Configs() +{ + unsigned int index_tb_conf = 0; + unsigned int size_vec_tb_conf = vector_registered_Configs.size(); + for(index_tb_conf = 0; index_tb_conf < size_vec_tb_conf; index_tb_conf++) { + Testbench_Config* cur_config = vector_registered_Configs[index_tb_conf]; + delete cur_config; + } + vector_registered_Configs.clear(); + +} + +void Testbench :: remove_all_Agents() +{ + AgentSlotOfTestbench* cur_AgentSlot; + unsigned int index_ag; + unsigned int size_vec_reg_ag = vector_registeredAgents.size(); + + for(index_ag = 0; index_ag < size_vec_reg_ag; index_ag++) { + cur_AgentSlot = vector_registeredAgents[index_ag]; + delete cur_AgentSlot; + } + vector_registeredAgents.clear(); + +} +void Testbench :: remove_all_Channels() +{ + unsigned int index_ch; + unsigned int size_vec_reg_chan = vector_registeredChannels.size(); + for(index_ch = 0; index_ch < size_vec_reg_chan; index_ch++) { + ChannelSlotOfTestbench* cur_ChaSlot = vector_registeredChannels[index_ch]; + delete cur_ChaSlot; + } + vector_registeredChannels.clear(); + +} +void Testbench :: remove_all_Sensors() +{ + unsigned int index_sen; + unsigned int size_vec_reg_sens = vector_registeredSensors.size(); + for(index_sen = 0; index_sen < size_vec_reg_sens; index_sen++) { + SensorSlotOfTestbench* cur_SenSlot = vector_registeredSensors[index_sen]; + delete cur_SenSlot; + } + vector_registeredSensors.clear(); +} + +bool Testbench :: free_resources() +{ + AgentSlotOfTestbench* cur_Ag_Sl_Tb; + unsigned int index_reg_Agents; + unsigned int size_vec_reg_Agents = vector_registeredAgents.size(); + for(index_reg_Agents = 0; index_reg_Agents < size_vec_reg_Agents; index_reg_Agents++) + { + cur_Ag_Sl_Tb = vector_registeredAgents[index_reg_Agents]; + Agent* cur_Ag = cur_Ag_Sl_Tb->get_agent(); + //cur_Ag->del_stateHandler(); + } +} + +void Testbench::set_CSV_Writer_parameter() +{ + + unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size(); + AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1]; + Agent* viability_Agent = viability_slot_Agent->get_agent(); + StateHandler* cur_state_Handl = viability_Agent->get_stateHandler(); + Testbench_Config* cur_tb_cfg; + string tb_cfg; + + cur_tb_cfg = get_current_Testbench_config(); + if(cur_tb_cfg != NULL) { + tb_cfg = cur_tb_cfg->get_Config_as_String(); + cur_state_Handl->set_CSV_Writer_parameter(tb_cfg); + } +} + +Testbench_Config* Testbench :: get_current_Testbench_config() +{ + unsigned int index_cur_tb_cfg = 0; + unsigned int size_tb_cfg = vector_registered_Configs.size(); + Testbench_Config* cur_tb_cfg; + for(index_cur_tb_cfg = 0; index_cur_tb_cfg < size_tb_cfg; index_cur_tb_cfg++){ + cur_tb_cfg = vector_registered_Configs[index_cur_tb_cfg]; + if(cur_tb_cfg->get_own_index() == Testbench_Config::get_active_Config()){ + return cur_tb_cfg; + } + } + return NULL; +} + +void Testbench :: set_config_values_in_linear_functions() +{ + unsigned int index_reg_Agents = 0; + unsigned int size_of_vec_reg_Agents; + + vector vec_reg_Agents = this->get_all_registeredAgents(); + size_of_vec_reg_Agents = vec_reg_Agents.size(); + AgentSlotOfTestbench* viability_slot_Agent = vec_reg_Agents[vec_reg_Agents.size()-1]; + Agent* viability_Agent = viability_slot_Agent->get_agent(); + StateHandler* cur_state_Handl = viability_Agent->get_stateHandler(); + + set_parameters_FuncBlockConfSim2StateDev(cur_state_Handl->FuncBlockConfSim2StateDev); + set_parameters_FuncBlockConfDif2StateDev(cur_state_Handl->FuncBlockConfDif2StateDev); + set_parameters_FuncBlockConfSim2StateTime(cur_state_Handl->FuncBlockConfSim2StateTime); + set_parameters_FuncBlockConfDif2StateTime(cur_state_Handl->FuncBlockConfDif2StateTime); + set_parameters_FuncBlockConfValStateDev(cur_state_Handl->FuncBlockConfValStateDev); + set_parameters_FuncBlockConfInvStateDev(cur_state_Handl->FuncBlockConfInvStateDev); + set_parameters_FuncBlockConfValStateTime(cur_state_Handl->FuncBlockConfValStateTime); + set_parameters_FuncBlockConfInvStateTime(cur_state_Handl->FuncBlockConfInvStateTime); + set_parameters_DriftDeviation(cur_state_Handl->DriftDeviation); + set_parameters_FuncBlockConfBrokenSamples(cur_state_Handl->FuncBlockConfBrokenSamples); +} + +void Testbench :: set_parameters_FuncBlockConfSim2StateDev(LinearFunctionBlock* FuncBlockConfSim2StateDev) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfSim2StateDev->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_1) { + cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_2) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)0, (float)-cur_values.inner_bound_sim_dif, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_3) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_4){ + cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)1, (float)cur_values.outter_bound_sim_dif, (float)0); + }else if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_5){ + cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false); + cur_Lin_Fun->setKandD((float)0, (float)0); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfDif2StateDev(LinearFunctionBlock* FuncBlockConfDif2StateDev) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfDif2StateDev->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_1) { + cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_2) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)1, (float)-cur_values.inner_bound_sim_dif, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_3) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_4){ + cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)0, (float)cur_values.outter_bound_sim_dif, (float)1); + }else if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_5){ + cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfSim2StateTime(LinearFunctionBlock* FuncBlockConfSim2StateTime) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfSim2StateTime->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_1) { + cur_Lin_Fun->setDomain(false, true, (float)0); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_2) { + cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length); + cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.length, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_3) { + cur_Lin_Fun->setDomain(true, (float)cur_values.length, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfDif2StateTime(LinearFunctionBlock* FuncBlockConfDif2StateTime) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfDif2StateTime->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_1) { + cur_Lin_Fun->setDomain(false, true, (float)0); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_2) { + cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length); + cur_Lin_Fun->setKandD((float)0, (float)1, (float)cur_values.length, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_3) { + cur_Lin_Fun->setDomain(true, (float)cur_values.length, false); + cur_Lin_Fun->setKandD((float)0, (float)0); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfValStateDev(LinearFunctionBlock* FuncBlockConfValStateDev) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfValStateDev->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_1) { + cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_2) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)0, (float)-cur_values.inner_bound_sim_dif, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_3) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_4){ + cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)1, (float)cur_values.outter_bound_sim_dif, (float)0); + }else if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_5){ + cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false); + cur_Lin_Fun->setKandD((float)0, (float)0); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfInvStateDev(LinearFunctionBlock* FuncBlockConfInvStateDev) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfInvStateDev->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_1) { + cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if (cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_2) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)1, (float)-cur_values.inner_bound_sim_dif, (float)0); + }else if (cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_3) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_4){ + cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif); + cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)0, (float)cur_values.outter_bound_sim_dif, (float)1); + }else if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_5){ + cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfValStateTime(LinearFunctionBlock* FuncBlockConfValStateTime) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfValStateTime->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == VALID_STATE_TIME_1) { + cur_Lin_Fun->setDomain(false, true, (float)0); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if (cur_Lin_Fun->getName() == VALID_STATE_TIME_2) { + cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length); + cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.length, (float)1); + }else if (cur_Lin_Fun->getName() == VALID_STATE_TIME_3) { + cur_Lin_Fun->setDomain(true, (float)cur_values.length, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfInvStateTime(LinearFunctionBlock* FuncBlockConfInvStateTime) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfInvStateTime->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == INVALID_STATE_TIME_1) { + cur_Lin_Fun->setDomain(false, true, (float)0); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if (cur_Lin_Fun->getName() == INVALID_STATE_TIME_2) { + cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length); + cur_Lin_Fun->setKandD((float)0, (float)1, (float)cur_values.length, (float)0); + }else if (cur_Lin_Fun->getName() == INVALID_STATE_TIME_3) { + cur_Lin_Fun->setDomain(true, (float)cur_values.length, false); + cur_Lin_Fun->setKandD((float)0, (float)0); + } + } +} + +void Testbench :: set_parameters_DriftDeviation(LinearFunctionBlock* DriftDeviation) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = DriftDeviation->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_1) { + cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_drift); + cur_Lin_Fun->setKandD((float)0, (float)1); + }else if (cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_2) { + cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_drift, true, (float)-cur_values.inner_bound_drift); + cur_Lin_Fun->setKandD((float)-cur_values.inner_bound_drift, (float)1, (float)-cur_values.inner_bound_drift, (float)0); + }else if (cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_3) { + //this line causes a small deviation between the old solution with define and the new one + //I didn't figure out how to get an totally equal result. + cur_Lin_Fun->setDomain(true,(float) -cur_values.inner_bound_drift, true,(float) cur_values.inner_bound_drift); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_4){ + cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_drift, true, (float)cur_values.outter_bound_drift); + cur_Lin_Fun->setKandD((float)cur_values.inner_bound_drift, (float)0, (float)cur_values.outter_bound_drift, (float)1); + }else if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_5){ + cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_drift, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + +void Testbench :: set_parameters_FuncBlockConfBrokenSamples(LinearFunctionBlock* FuncBlockConfBrokenSamples) +{ + LinearFunction* cur_Lin_Fun; + vector vec_Lin_Fun = FuncBlockConfBrokenSamples->get_all_LinearFunctions(); + unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size(); + unsigned int index_cur_Lin_Fun = 0; + Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config(); + + for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++) + { + One_Config_t cur_values = cur_Tb_cfg->get_Config(); + cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun]; + if(cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_1) { + cur_Lin_Fun->setDomain(false, true, (float)0); + cur_Lin_Fun->setKandD((float)0, (float)0); + }else if (cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_2) { + cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.bound_broken); + cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.bound_broken, (float)1); + }else if (cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_3) { + cur_Lin_Fun->setDomain(true, (float)cur_values.bound_broken, false); + cur_Lin_Fun->setKandD((float)0, (float)1); + } + } +} + + + +void Testbench :: set_CSV_Reader_row(const int start_row) +{ + unsigned int size_of_vec_reg_Sens = vector_registeredSensors.size(); + SensorSlotOfTestbench* cur_sens_Slot; + unsigned int index_cur_Slot = 0; + CSVreaderModule* assigned_CSVReader; + for(index_cur_Slot = 0; index_cur_Slot < size_of_vec_reg_Sens; index_cur_Slot++){ + cur_sens_Slot = vector_registeredSensors[index_cur_Slot]; + assigned_CSVReader = cur_sens_Slot->get_csvReaderModule(); + assigned_CSVReader->reset_row(start_row); + } +} + +void Testbench :: set_CSV_Reader_to_beginning() +{ + unsigned int size_of_vec_reg_Sens = vector_registeredSensors.size(); + SensorSlotOfTestbench* cur_sens_Slot; + unsigned int index_cur_Slot = 0; + CSVreaderModule* assigned_CSVReader; + unsigned const int START_ROW = 1; + for(index_cur_Slot = 0; index_cur_Slot < size_of_vec_reg_Sens; index_cur_Slot++){ + cur_sens_Slot = vector_registeredSensors[index_cur_Slot]; + assigned_CSVReader = cur_sens_Slot->get_csvReaderModule(); + assigned_CSVReader->set_position_fpointer_to_start(); + } +} + + +void Testbench:: reset_States() +{ + unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size(); + AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1]; + Agent* viability_Agent = viability_slot_Agent->get_agent(); + StateHandler* cur_state_Handl = viability_Agent->get_stateHandler(); + + cur_state_Handl->reset_States(); +} + +void Testbench:: reset_States_and_Slave_Agents() +{ + unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size(); + AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1]; + Agent* viability_Agent = viability_slot_Agent->get_agent(); + StateHandler* cur_state_Handl = viability_Agent->get_stateHandler(); + + cur_state_Handl->reset_States_and_Slave_Agents(); + +} + +Testbench :: ~Testbench() +{ + remove_all_Testbench_Configs(); + remove_all_Agents(); + remove_all_Channels(); + remove_all_Sensors(); +} + + +/* +Testbench :: Testbench() { + num_of_registered_agents = 0; + num_of_registered_sensors = 0; + num_of_registered_channels = 0; + + this->id = num_of_units; + num_of_units++; + this->set_name(NO_NAME); + + //csv + flag_csv_reader_exist = false; + flag_csv_writer_exist = false; +} + +Testbench :: Testbench(char* name) { + num_of_registered_agents = 0; + num_of_registered_sensors = 0; + num_of_registered_channels = 0; + + this->id = num_of_units; + num_of_units++; + this->set_name(name); + + //csv + flag_csv_reader_exist = false; + flag_csv_writer_exist = false; +} + +void Testbench :: simulate() { + + if(flag_csv_writer_exist) { + + csv_writer->write_field("second"); + csv_writer->make_new_field(); + + for(unsigned int s_ix=0; s_ixwrite_field(registered_sensors[s_ix]->get_name()); + csv_writer->make_new_field(); + } + + for(unsigned int a_ix=0; a_ixwrite_field(registered_agents[a_ix]->get_name()); + csv_writer->make_new_field(); + + } + + csv_writer->write_field("confidence counter"); + csv_writer->make_new_field(); + + csv_writer->make_new_line(); + } + + + //TODO: HIER ENDLOSSCHLEIFE ODER SO - Irgendwas, dass stoppt, wenn file zu ende + for(unsigned int sec=1; sec<=29208; sec++) { + + printf("second %u\n", sec); + + if(flag_csv_writer_exist) { + csv_writer->write_field((int)sec); + csv_writer->make_new_field(); + } + + + //Update Sensor Values + for(unsigned int s_ix = 0; s_ix < num_of_registered_sensors; s_ix++) { + //TODO: make possibility of non-registered csv-reader + if(flag_sensor_has_csvr[s_ix]) { + + float value_from_csv; + + if(registered_sensors_csvr[s_ix] != NULL) { + + if(registered_sensors_csvr[s_ix]->get_next_value(&value_from_csv)) { + + registered_sensors[s_ix]->update_sensor_value(value_from_csv); + + //printf("field of %s: %f", registered_sensors[s_ix]->get_name(), value_from_csv); + } + } + } + } + + + for(unsigned int s_ix = 0; s_ix < num_of_registered_sensors; s_ix++) { + registered_sensors[s_ix]->trigger(); + + if(flag_csv_writer_exist) { + if(registered_sensors[s_ix]->get_flag_sensor_value_is_valid()) { + csv_writer->write_field(registered_sensors[s_ix]->get_sensor_value()); + } + csv_writer->make_new_field(); + } + } + + + + + + for(unsigned int c_ix = 0; c_ix < num_of_registered_channels; c_ix++) { + + //printf("\n\n\nTRIGGER CHANNELS\n"); + + registered_channels[c_ix]->trigger(); + } + + + + + + + for(unsigned int a_ix = 0; a_ix < num_of_registered_agents; a_ix++) { + + registered_agents[a_ix]->trigger(); + + if(flag_csv_writer_exist) { + + if(registered_agents[a_ix]->get_flag_bunched_score_exist()) { + csv_writer->write_field(registered_agents[a_ix]->get_bunched_score()); + csv_writer->make_new_field(); + csv_writer->write_field((int)registered_agents[a_ix]->get_bunch_score_confidency()); + } + else if(registered_agents[a_ix]->get_flag_abstracted_sensor_score_exist(0)) { + csv_writer->write_field(registered_agents[a_ix]->get_abstracted_sensor_score(0)); + } + + if(a_ix < num_of_registered_agents-1) { + csv_writer->make_new_field(); + } + } + } + + if(flag_csv_writer_exist) { + csv_writer->make_new_line(); + } + + + getchar(); + + } + + + if(flag_csv_writer_exist) { + csv_writer->close_file(); + } + + +} + +//for agents: +unsigned int Testbench :: get_num_of_registered_agents() { + return num_of_registered_agents; +} + +bool Testbench :: register_agent(Agent *agent) { + if(num_of_registered_agents < MAX_NUM_OF_AGENTS) { + registered_agents[num_of_registered_agents] = agent; + num_of_registered_agents++; + return true; + } + return false; +} + +bool Testbench :: deregister_agent(Agent *agent) { + unsigned int agent_ix; + + if(get_ix_of_agent(agent, &agent_ix)) { + return deregister_agent(agent_ix); + } + + return false; +} + +bool Testbench :: deregister_agent(unsigned int agent_ix) { + if(agent_ix < num_of_registered_agents) { + for(unsigned int a_ix=agent_ix; a_ixcsv_reader = csv_reader; + flag_csv_reader_exist = true; + return true; + } + return false; +} + +bool Testbench :: register_csv_writer(CSV_Writer* csv_writer) { + if(csv_writer != NULL) { + this->csv_writer = csv_writer; + flag_csv_writer_exist = true; + return true; + } + return false; +} +*/ diff --git a/Version_Max_07_05_2018_CMake/src/Testbench.h b/Version_Max_07_05_2018_CMake/src/Testbench.h new file mode 100755 index 0000000..d219b2e --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Testbench.h @@ -0,0 +1,219 @@ +#ifndef TESTBENCH_HEADERFILE +#define TESTBENCH_HEADERFILE + +#include +#include "AgentSlotOfTestbench.h" +#include "ChannelSlotOfTestbench.h" +#include "CSVreaderModule.h" +#include "SensorSlotOfTestbench.h" +#include "Unit.h" +#include "Agent.h" +#include "Testbench_Config.h" + + +/* +#include "Agent.h" +#include "Channel.h" +#include "CSVreader.h" +#include "CSV_Writer.h" + +#define MAX_NUM_OF_AGENTS 20 +#define MAX_NUM_OF_CHANNELS 80 +#define MAX_NUM_OF_SENSORS 20 +*/ +using namespace std; + +//definitions for the linear function blocks, with their associated linear function names +//first name of the linear function block and then the names of the linear functions registered +//within this function block, is later used to identify the right linear function +//to parameterize it correctly. +const string FUNC_BLOCK_NAME_SAME_STATE_DEV = "funcBlock:confSim2StateDev"; +const string CONF_SIM2_STATE_DEV_1 = "ConfSim2StateDev1"; +const string CONF_SIM2_STATE_DEV_2 = "ConfSim2StateDev2"; +const string CONF_SIM2_STATE_DEV_3 = "ConfSim2StateDev3"; +const string CONF_SIM2_STATE_DEV_4 = "ConfSim2StateDev4"; +const string CONF_SIM2_STATE_DEV_5 = "ConfSim2StateDev5"; +const string FUNC_BLOCK_NAME_ANOTHER_STATE_DEV = "funcBlock:confDif2StateDev"; +const string CONF_DIF2_STATE_DEV_1 = "ConfDif2StateDev1"; +const string CONF_DIF2_STATE_DEV_2 = "ConfDif2StateDev2"; +const string CONF_DIF2_STATE_DEV_3 = "ConfDif2StateDev3"; +const string CONF_DIF2_STATE_DEV_4 = "ConfDif2StateDev4"; +const string CONF_DIF2_STATE_DEV_5 = "ConfDif2StateDev5"; +const string FUNC_BLOCK_NAME_SAME_TIME = "funcBlock:confSim2StateTime"; +const string CONF_SIM2_STATE_TIME_1 = "ConfSim2StateTime1"; +const string CONF_SIM2_STATE_TIME_2 = "ConfSim2StateTime2"; +const string CONF_SIM2_STATE_TIME_3 = "ConfSim2StateTime3"; +const string FUNC_BLOCK_NAME_ANOTHER_STATE_TIME = "funcBlock:confDif2StateTime"; +const string CONF_DIF2_STATE_TIME_1 = "ConfDif2StateTime1"; +const string CONF_DIF2_STATE_TIME_2 = "ConfDif2StateTime2"; +const string CONF_DIF2_STATE_TIME_3 = "ConfDif2StateTime3"; +const string FUNC_BLOCK_NAME_VAILD_STATE_DEV = "funcBlock:confValidStateDev"; +const string CONF_VALID_STATE_DEV_1 = "ConfValidStateDev1"; +const string CONF_VALID_STATE_DEV_2 = "ConfValidStateDev2"; +const string CONF_VALID_STATE_DEV_3 = "ConfValidStateDev3"; +const string CONF_VALID_STATE_DEV_4 = "ConfValidStateDev4"; +const string CONF_VALID_STATE_DEV_5 = "ConfValidStateDev5"; +const string FUNC_BLOCK_NAME_INVALID_STATE_DEV = "funcBlock:confInvalidStateDev"; +const string CONF_INVALID_STATE_DEV_1 = "ConfInvalidStateDev1"; +const string CONF_INVALID_STATE_DEV_2 = "ConfInvalidStateDev2"; +const string CONF_INVALID_STATE_DEV_3 = "ConfInvalidStateDev3"; +const string CONF_INVALID_STATE_DEV_4 = "ConfInvalidStateDev4"; +const string CONF_INVALID_STATE_DEV_5 = "ConfInvalidStateDev5"; +const string FUNC_BLOCK_NAME_VALID_STATE_TIME = "funcBlock:confValidStateTime"; +const string VALID_STATE_TIME_1 = "ValidStateTime1"; +const string VALID_STATE_TIME_2 = "ValidStateTime2"; +const string VALID_STATE_TIME_3 = "ValidStateTime3"; +const string FUNC_BLOCK_NAME_INVALID_STATE_TIME = "funcBlock:confInvalidStateTime"; +const string INVALID_STATE_TIME_1 = "InvalidStateTime1"; +const string INVALID_STATE_TIME_2 = "InvalidStateTime2"; +const string INVALID_STATE_TIME_3 = "InvalidStateTime3"; +const string FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS = "confidence:confStateDrifts"; +const string CONFIDENCE_DRIFT_DEVIATION_1 = "ConfidenceDriftDeviation1"; +const string CONFIDENCE_DRIFT_DEVIATION_2 = "ConfidenceDriftDeviation2"; +const string CONFIDENCE_DRIFT_DEVIATION_3 = "ConfidenceDriftDeviation3"; +const string CONFIDENCE_DRIFT_DEVIATION_4 = "ConfidenceDriftDeviation4"; +const string CONFIDENCE_DRIFT_DEVIATION_5 = "ConfidenceDriftDeviation5"; +const string FUNC_BLOCK_NAME_CONFIDENCE_BROKEN = "confidence:broken"; +const string CONFIDENCE_BROKEN_1 = "ConfidenceBroken1"; +const string CONFIDENCE_BROKEN_2 = "ConfidenceBroken2"; +const string CONFIDENCE_BROKEN_3 = "ConfidenceBroken3"; + +class Testbench : public Module { + + private: + //TODO: set- and get function for maxNumOf_registeredAgents; + vector vector_registeredAgents; + + + //TODO: set- and get function for maxNumOf_registeredChannels; + vector vector_registeredChannels; + + + //TODO: set- and get function for maxNumOf_registeredSensors; + vector vector_registeredSensors; + + vector vector_registered_Configs; + void remove_all_Testbench_Configs(); + void remove_all_Agents(); + void remove_all_Channels(); + void remove_all_Sensors(); + + void set_parameters_FuncBlockConfSim2StateDev(LinearFunctionBlock* FuncBlockConfSim2StateDev); + void set_parameters_FuncBlockConfDif2StateDev(LinearFunctionBlock* FuncBlockConfDif2StateDev); + void set_parameters_FuncBlockConfSim2StateTime(LinearFunctionBlock* FuncBlockConfSim2StateTime); + void set_parameters_FuncBlockConfDif2StateTime(LinearFunctionBlock* FuncBlockConfDif2StateTime); + void set_parameters_FuncBlockConfValStateDev(LinearFunctionBlock* FuncBlockConfValStateDev); + void set_parameters_FuncBlockConfInvStateDev(LinearFunctionBlock* FuncBlockConfInvStateDev); + void set_parameters_FuncBlockConfValStateTime(LinearFunctionBlock* FuncBlockConfValStateTime); + void set_parameters_FuncBlockConfInvStateTime(LinearFunctionBlock* FuncBlockConfInvStateTime); + void set_parameters_DriftDeviation(LinearFunctionBlock* DriftDeviation); + void set_parameters_FuncBlockConfBrokenSamples(LinearFunctionBlock* FuncBlockConfBrokenSamples); + + + public: + static const unsigned int MAXNUM_OF_REGISTERED_AGENTS = 1000; + + static const unsigned int MAXNUM_OF_REGISTERED_CHANNELS = 1000; + + static const unsigned int MAXNUM_OF_REGISTERED_SENSORS = 1000; + + Testbench(); + Testbench(char* name); + + void init_testbench(); + + bool register_agent(Agent* agent); + + bool register_sensor(Sensor* sensor); + SensorSlotOfTestbench* get_sensorSlotAddressOfTestbench(Sensor* sensor); + + bool register_channel(Channel* channel); + + bool register_testbench_config(Testbench_Config* tb_config); + vector& get_all_registered_testbench_configs(); + void set_current_tb_config_index(const int index); + Testbench_Config* get_current_Testbench_config(); + + void set_config_values_in_linear_functions(); + + bool free_resources(); + + void set_CSV_Writer_parameter(); + + void set_CSV_Reader_row(const int start_row); + void set_CSV_Reader_to_beginning(); + + void reset_States(); + void reset_States_and_Slave_Agents(); + + void simulate(unsigned int rounds); + + vector& get_all_registeredAgents(); + + ~Testbench(); + + + + + /* + private: + + unsigned int num_of_registered_agents; + Agent* registered_agents[MAX_NUM_OF_AGENTS]; + + unsigned int num_of_registered_channels; + Channel* registered_channels[MAX_NUM_OF_CHANNELS]; + + unsigned int num_of_registered_sensors; + Sensor* registered_sensors[MAX_NUM_OF_SENSORS]; + CSV_Reader* registered_sensors_csvr[MAX_NUM_OF_SENSORS]; + bool flag_sensor_has_csvr[MAX_NUM_OF_SENSORS]; + + //csv + CSV_Reader* csv_reader; + bool flag_csv_reader_exist; + + CSV_Writer* csv_writer; + bool flag_csv_writer_exist; + + public: + Testbench(); + Testbench(char* name); + + void simulate(); + + //for agents: + unsigned int get_num_of_registered_agents(); + bool register_agent(Agent* agent); + bool deregister_agent(Agent* agent); + bool deregister_agent(unsigned int agent_ix); + bool get_ix_of_agent(Agent* agent, unsigned int *agent_ix); + + //for sensors: + unsigned int get_num_of_registered_sensors(); + bool register_sensor(Sensor* sensor); + bool register_sensor(Sensor* sensor, CSV_Reader *csvr); + bool deregister_sensor(Sensor* sensor); + bool deregister_sensor(unsigned int sensor_ix); + bool get_ix_of_sensor(Sensor* sensor, unsigned int *sensor_ix); + bool get_flag_sensor_has_csvr(unsigned int sensor_ix); + CSV_Reader* get_registered_sensors_csvr(unsigned int sensor_ix); + CSV_Reader* get_registered_sensors_csvr(Sensor* sensor); + + + + //for channels: + unsigned int get_num_of_registered_channels(); + bool register_channel(Channel* channel); + bool deregister_channel(Channel* channel); + bool deregister_channel(unsigned int channel_ix); + bool get_ix_of_channel(Channel* channel, unsigned int *channel_ix); + + //csv + bool register_csv_reader(CSV_Reader* csv_reader); + bool register_csv_writer(CSV_Writer* csv_writer); + */ +}; + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp b/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp new file mode 100755 index 0000000..9cca90a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp @@ -0,0 +1,226 @@ +/* + * Testbench_Config.cpp + * + * Created on: 26.06.2018 + * Author: edwin + */ + +#include "Testbench_Config.h" + + +vector Testbench_Config::s_vec_all_created_Configs; +int Testbench_Config::s_counter_of_all_created_configs = 0; +int Testbench_Config::s_active_Config = 0; + +/* + * + */ +void Testbench_Config::register_Config() +{ + if(s_vec_all_created_Configs.max_size() > s_vec_all_created_Configs.size()){ + s_vec_all_created_Configs.push_back(this); + this->m_current_index = s_counter_of_all_created_configs; + s_counter_of_all_created_configs = s_counter_of_all_created_configs + 1; + } else { + cout << "It is not possible to add an Testbench_Config to vector, Testbench_Config not registered" << endl; + } +} + +/* + * + */ +void Testbench_Config::deregister_Config() +{ + if (!s_vec_all_created_Configs.empty()) { + int index = 0; + int old_max_index = 0; + std::vector::iterator it = s_vec_all_created_Configs.begin(); + for (; index != this->m_current_index; it++) { + index = index + 1; + } + old_max_index = s_vec_all_created_Configs.size() -1; + if (index == this->m_current_index) { + s_vec_all_created_Configs.erase(it); + } + if(index < old_max_index) { + adapt_Indices(index); + } + this->m_current_index = s_object_is_deleted; + s_counter_of_all_created_configs = s_counter_of_all_created_configs - 1; + } +} + +/* + * + */ +void Testbench_Config::adapt_Indices(int from_index_to_change) +{ + int index = 0; + for(index = 0; index < s_vec_all_created_Configs.size(); index++){ + if(index >= from_index_to_change) { + Testbench_Config* cur_config = s_vec_all_created_Configs[index]; + cur_config->m_current_index = cur_config->m_current_index - 1; + } + } + +} + +Testbench_Config::Testbench_Config() +{ + this->configuration.bound_broken = float(2); + this->configuration.outter_bound_sim_dif = 0.20; + this->configuration.inner_bound_sim_dif = 0.01; + this->configuration.outter_bound_drift = 3 * this->configuration.outter_bound_sim_dif; + this->configuration.inner_bound_drift = this->configuration.outter_bound_sim_dif; + this->configuration.length = (float) 10; + register_Config(); +} + +/* + * + */ +Testbench_Config::Testbench_Config(One_Config_t& a_config) +{ + this->configuration = a_config; + register_Config(); +} + +/* + * return the index of the object in the static class vector + */ +int Testbench_Config::get_own_index() +{ + return this->m_current_index; +} + +/* + * + */ +One_Config_t Testbench_Config::get_Config() +{ + if(this != NULL && this->m_current_index != s_object_is_deleted){ + return this->configuration; + } +} + +/* + * + */ +void Testbench_Config::print() +{ + if(this != NULL && this->m_current_index != s_object_is_deleted) { + std::cout << "Index of the configuration: " << this->m_current_index; + std::cout << "The values of the configuration are: "; + std::cout << "Broken boundary: " << this->configuration.bound_broken << " "; + std::cout << "Inner boundary similar state: " << this->configuration.inner_bound_sim_dif << " "; + std::cout << "Outter boundary similar state: " << this->configuration.outter_bound_sim_dif << " "; + std::cout << "Inner boundary drift: " << this->configuration.inner_bound_drift << " "; + std::cout << "Outter boundary drift: " << this->configuration.outter_bound_drift << " "; + std::cout << "Length: " << this->configuration.length << " "; + std::cout << std::endl; + }else { + std::cout << "Object points to NULL" << std::endl; + } +} + +/** + * returns the index of the active config of the Testbench. + */ +int Testbench_Config::get_active_Config() +{ + return s_active_Config; +} + +/** + * Sets the index for the current config used. + * @param index value >= 0, -1 = Invalid Index + * + */ +void Testbench_Config::set_active_Config(const int index) +{ + if(index < s_counter_of_all_created_configs) { + s_active_Config = index; + }else { + s_active_Config = s_INVALID_INDEX; + } +} + + +void Testbench_Config::cut_number_of_decimal_digits(std::string & str_number) +{ const std::string delimeter = "."; + const std::string zero = "0"; + std::string str_temp; + std::size_t first_pos; + std::size_t length; + std::size_t first_not_zero; + std::size_t index; + length = str_number.length(); + first_pos = str_number.find_first_of(delimeter); + if (first_pos != std::string::npos) + { + //0 is the start of the string, add 1 to get also the delimeter into the string + str_temp =str_number.substr(0, first_pos + 1); + length = length - first_pos - 1; + str_number = str_number.substr(first_pos + 1, length); + first_not_zero = str_number.find_first_not_of(zero); + if(first_not_zero == std::string::npos) + { + str_number = str_temp + str_number[0] + str_number[1]; + } + else + { + for(index = 0; index <= first_not_zero; index++){ + str_temp = str_temp + str_number[index]; + } + str_number = str_temp; + } + } + + +} + +/** + * returns all parameters of the config as a string. + * B_b means bound broken border, I_B_d means inner bound drift border + * O_B_d means outter bound drift border, I_B_s_d means inner bound simular signal border + * O_B_s_d means outter bound simular signalr border + */ +std::string Testbench_Config::get_Config_as_String() +{ + std::string config; + std::string str_part; + str_part = std::to_string(this->configuration.bound_broken); + cut_number_of_decimal_digits(str_part); + + config = " B_b: " + str_part; + + str_part = std::to_string(this->configuration.inner_bound_drift); + cut_number_of_decimal_digits(str_part); + + config = config + " I_B_d: "+ str_part; + + str_part = std::to_string(this->configuration.outter_bound_drift); + cut_number_of_decimal_digits(str_part); + + config = config + " O_B_d: " + str_part; + + str_part = std::to_string(this->configuration.inner_bound_sim_dif); + cut_number_of_decimal_digits(str_part); + + config = config + " I_B_s_d: " + str_part; + + str_part = std::to_string(this->configuration.outter_bound_sim_dif); + cut_number_of_decimal_digits(str_part); + + config = config + " O_B_s_d: " + str_part + " "; + config = config + " Length: " + std::to_string(this->configuration.length) + " "; + return config; +} + +/* + * + */ +Testbench_Config::~Testbench_Config() +{ + deregister_Config(); +} diff --git a/Version_Max_07_05_2018_CMake/src/Testbench_Config.h b/Version_Max_07_05_2018_CMake/src/Testbench_Config.h new file mode 100755 index 0000000..b4af2cd --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Testbench_Config.h @@ -0,0 +1,72 @@ +/* + * Testbench_Config.h + * + * Created on: 26.06.2018 + * Author: edwin + */ + +#ifndef TESTBENCH_CONFIG_H_ +#define TESTBENCH_CONFIG_H_ + +#include +#include +#include +#include +#include + +using namespace std; + +typedef struct One_Config { + ///parameter of outter boundary for similar function + float outter_bound_sim_dif; + ///parameter of inner boundary for similar function + float inner_bound_sim_dif; + ///parameters of outter boundary for drift. + float outter_bound_drift; + ///parameters of inner boundary for drift. + float inner_bound_drift; + ///timer telling, after downsampling how many samples after input has changed it is allowed + ///that output is changing, for very slow system high value and for fast system low value + float bound_broken; + ///length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery. + ///history of the data depends of it, and should change, if it changes. + int length; +} One_Config_t; + +class Testbench_Config { + +private: + static vector s_vec_all_created_Configs; + static int s_counter_of_all_created_configs; + static int s_active_Config; + const static int s_object_is_deleted = -1; + const static int s_INVALID_INDEX = -1; + const static int s_MAX_LENGTH_FLOAT_STRING = 20; + + int m_current_index; + + One_Config_t configuration; + void register_Config(); + void deregister_Config(); + void adapt_Indices(int from_index_to_change); + void cut_number_of_decimal_digits(std::string & str_number); + +public: + Testbench_Config(); + Testbench_Config(One_Config_t& a_config); + int get_own_index(); + One_Config_t get_Config(); + void print(); + string get_Config_as_String(); + ~Testbench_Config(); + + static int get_active_Config(); + static void set_active_Config(const int index); + +}; + + + + + +#endif /* TESTBENCH_CONFIG_H_ */ diff --git a/Version_Max_07_05_2018_CMake/src/Unit.cpp b/Version_Max_07_05_2018_CMake/src/Unit.cpp new file mode 100755 index 0000000..f8b7d0b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Unit.cpp @@ -0,0 +1,16 @@ +#include "Unit.h" + +unsigned int Unit :: num_of_units = 0; + +Unit :: Unit() { + this->id = num_of_units; + num_of_units++; +} + +void Unit :: set_id(unsigned int id) { + this->id = id; +} + +unsigned int Unit :: get_id() { + return this->id; +} diff --git a/Version_Max_07_05_2018_CMake/src/Unit.h b/Version_Max_07_05_2018_CMake/src/Unit.h new file mode 100755 index 0000000..298d8ab --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/Unit.h @@ -0,0 +1,40 @@ +#ifndef UNIT_HEADERFILE +#define UNIT_HEADERFILE + +#define MAX_LENGTH_NAME 50 +#define NO_NAME "unnamed" + +#define MAX_NUM_OF_MOUNTED_SLAVEAGENTS 10 +#define MAX_NUM_OF_MOUNTED_SENSORS 10 + +#define MAX_NUM_OF_DATA_SETS 100 + +#define MOUNTED true +#define UNMOUNTED false + +#define ACTIVE true +#define INACTIVE false + +#define YES true +#define NO false + +#define BOUND true +#define NO_BOUND false + +#define RATES_OF_CHANGE true +#define NO_RATES_OF_CHANGE false + +class Unit { + + protected: + static unsigned int num_of_units; + unsigned int id; + + public: + Unit(); + + void set_id(unsigned int value); + unsigned int get_id(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/abstraction_functions.cpp b/Version_Max_07_05_2018_CMake/src/abstraction_functions.cpp new file mode 100755 index 0000000..e69de29 diff --git a/Version_Max_07_05_2018_CMake/src/abstraction_functions.h b/Version_Max_07_05_2018_CMake/src/abstraction_functions.h new file mode 100755 index 0000000..f70c84e --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/abstraction_functions.h @@ -0,0 +1,12 @@ +#ifndef ABSTRACTION_FUNCTIONS_HEADERFILE +#define ABSTRACTION_FUNCTIONS_HEADERFILE + +#define ABSTRACTION_SIMLY_ADD 1 +#define ABSTRACTION_ADD_WITH_CONDITION 2 + + + + + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/abstraction_interface.cpp b/Version_Max_07_05_2018_CMake/src/abstraction_interface.cpp new file mode 100755 index 0000000..0b35364 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/abstraction_interface.cpp @@ -0,0 +1,20 @@ +//GENERATED FILE + +#include "abstraction_interface.h" +#include "abstraction_functions.h" + +bool abstract_interface(unsigned int abstraction_method, + unsigned int num_of_mounted_slaveagents, bool* flag_input_data_int_is_in_use, int* input_data_int, + unsigned int num_of_mounted_sensors, bool* flag_input_data_float_is_in_use, float* input_data_float) { + + switch(abstraction_method) { + + + + default: return false; + + } + + + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/abstraction_interface.h b/Version_Max_07_05_2018_CMake/src/abstraction_interface.h new file mode 100755 index 0000000..75a72e0 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/abstraction_interface.h @@ -0,0 +1,6 @@ +#ifndef ABSTRACTION_INTERFACE_HEADERFILE +#define ABSTRACTION_INTERFACE_HEADERFILE + +bool abstract_interface(unsigned int abstraction_method, unsigned int num_of_mounted_slaveagents, bool* flag_input_data_int_is_in_use, int* input_data_int, unsigned int num_of_mounted_sensors, bool* flag_input_data_float_is_in_use, float* input_data_float); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/attach_modules.cpp b/Version_Max_07_05_2018_CMake/src/attach_modules.cpp new file mode 100755 index 0000000..7e29b3f --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/attach_modules.cpp @@ -0,0 +1,48 @@ +#include "attach_modules.h" +#include "rlutil.h" + +using namespace rlutil; + +bool attach_historyModuleToSensorSlotInAgent(Agent* agent, Sensor* sensor, Channel* inputPort, HistoryModule* historyModule) { + if(agent != NULL && inputPort != NULL && historyModule != NULL) { + SensorSlotOfAgent* sensorSlotOfAgent = agent->get_sensorHandlerOfAgent()->get_sensorSlotAddress(inputPort); + if(sensorSlotOfAgent != NULL) { + printf(" > HistoryModule "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", historyModule->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", historyModule->get_id()); + if(sensorSlotOfAgent->set_historyModule(historyModule)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("attached "); + setColor(TXTCOLOR_GREY); + printf("to Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) in Agent ", sensor->get_id()); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", agent->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("Couldn't attach the HistoryModule!\n"); + setColor(TXTCOLOR_GREY); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't attach the HistoryModule because Sensor isn't mounted in %s (id: %03u)!\n", agent->get_name(), agent->get_id()); + setColor(TXTCOLOR_GREY); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't attach the HistoryModule because Agent, Channel, or HistoryModule is not valid!\n"); + setColor(TXTCOLOR_GREY); + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/attach_modules.h b/Version_Max_07_05_2018_CMake/src/attach_modules.h new file mode 100755 index 0000000..2233d4c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/attach_modules.h @@ -0,0 +1,9 @@ +#ifndef ATTACHMODULES_HEADERFILE +#define ATTACHMODULES_HEADERFILE + +#include "Agent.h" +#include "Sensor.h" + +bool attach_historyModuleToSensorSlotInAgent(Agent* agent, Sensor* sensor, Channel* inputPort, HistoryModule* historyModule); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp new file mode 100755 index 0000000..5ebe7f2 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp @@ -0,0 +1,50 @@ +#include "attach_modulesToTestbench.h" + +#include "rlutil.h" +#include "SensorSlotOfTestbench.h" + +using namespace rlutil; + +bool attach_csvReaderModuleToSensorSlotInAgent(Testbench* testbench, Sensor* sensor, CSVreaderModule* csvReaderModule) { + if(testbench != NULL && sensor != NULL && csvReaderModule != NULL) { + SensorSlotOfTestbench* sensorSlot = testbench->get_sensorSlotAddressOfTestbench(sensor); + if(sensorSlot != NULL) { + printf(" > CSV-Reader "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", csvReaderModule->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", csvReaderModule->get_id()); + if(sensorSlot->set_csvReaderModule(csvReaderModule)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("attached "); + setColor(TXTCOLOR_GREY); + printf("to Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) in Testbench ", sensor->get_id()); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", testbench->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", testbench->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("Couldn't attach the CSVreaderModule!\n"); + setColor(TXTCOLOR_GREY); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't attach the CSVreaderModule because Sensor isn't registered in %s (id: %03u)!\n", testbench->get_name(), testbench->get_id()); + setColor(TXTCOLOR_GREY); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't attach the CSVreaderModule because Testbench, Sensorm or CSVreaderModule is not valid!\n"); + setColor(TXTCOLOR_GREY); + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.h b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.h new file mode 100755 index 0000000..3229f5b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.h @@ -0,0 +1,10 @@ +#ifndef ATTACHMODULESTOTESTBENCH_HEADERFILE +#define ATTACHMODULESTOTESTBENCH_HEADERFILE + +#include "CSVreaderModule.h" +#include "Sensor.h" +#include "Testbench.h" + +bool attach_csvReaderModuleToSensorSlotInAgent(Testbench* testbench, Sensor* sensor, CSVreaderModule* csvReaderModule); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/boundary_check.cpp b/Version_Max_07_05_2018_CMake/src/boundary_check.cpp new file mode 100755 index 0000000..921af8c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/boundary_check.cpp @@ -0,0 +1,36 @@ +#include "boundary_check.h" + + +bool is_it_higher_than_learned_boundary(Sensor* sensor, int score, int boundary) { + return (sensor->get_sensorValue() > sensor->get_learned_threshold(score, boundary)); +} + +bool is_it_higher_than_hardcoded_boundary(Sensor* sensor, int score, int boundary) { + return (sensor->get_sensorValue() > sensor->get_hardcoded_threshold(score, boundary)); +} + +bool is_it_lower_than_learned_boundary(Sensor* sensor, int score, int boundary) { + return (sensor->get_sensorValue() < sensor->get_learned_threshold(score, boundary)); +} + +bool is_it_lower_than_hardcoded_boundary(Sensor* sensor, int score, int boundary) { + return (sensor->get_sensorValue() < sensor->get_hardcoded_threshold(score, boundary)); +} + +bool is_it_higher_than_boundary(Sensor* sensor, int score, int boundary) { + if(sensor->get_flag_learned_boundary_exist(score, boundary)) { + return is_it_higher_than_learned_boundary(sensor, score, boundary); + } + else { + return is_it_higher_than_hardcoded_boundary(sensor, score, boundary); + } +} + +bool is_it_lower_than_boundary(Sensor* sensor, int score, int boundary) { + if(sensor->get_flag_learned_boundary_exist(score, boundary)) { + return is_it_lower_than_learned_boundary(sensor, score, boundary); + } + else { + return is_it_lower_than_hardcoded_boundary(sensor, score, boundary); + } +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/boundary_check.h b/Version_Max_07_05_2018_CMake/src/boundary_check.h new file mode 100755 index 0000000..63113cb --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/boundary_check.h @@ -0,0 +1,15 @@ +#ifndef BOUNDARY_CHECK_HEADERFILE +#define BOUNDARY_CHECK_HEADERFILE + +#include "Sensor.h" + +bool is_it_higher_than_learned_boundary(Sensor* sensor, int score, int boundary); +bool is_it_higher_than_hardcoded_boundary(Sensor* sensor, int score, int boundary); + +bool is_it_lower_than_learned_boundary(Sensor* sensor, int score, int boundary); +bool is_it_lower_than_hardcoded_boundary(Sensor* sensor, int score, int boundary); + +bool is_it_higher_than_boundary(Sensor* sensor, int score, int boundary); +bool is_it_lower_than_boundary(Sensor* sensor, int score, int boundary); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/clock.cpp b/Version_Max_07_05_2018_CMake/src/clock.cpp new file mode 100755 index 0000000..564531b --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/clock.cpp @@ -0,0 +1,25 @@ +#include "clock.h" +//#include gibt es in Linux nicht +//for linux +#include +#include + +/* +typedef struct timeval { + long tv_sec; + long tv_usec; +} timeval; +*/ + +Clock :: Clock() { + +} + +void Clock :: initiate_clock() { + //SYSTEMTIME st; + time_t st; + st = time(NULL); + //GetSystemTime(&st); + + //printf("hour %i\n", st.wHour); +} diff --git a/Version_Max_07_05_2018_CMake/src/clock.h b/Version_Max_07_05_2018_CMake/src/clock.h new file mode 100755 index 0000000..14d57df --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/clock.h @@ -0,0 +1,30 @@ +#ifndef CLOCK_HEADERFILE +#define CLOCK_HEADERFILE + +class Clock { + + private: + int s_milisec, + s_sec, + s_min, + s_hour, + s_day, + s_year, + e_milisec, + e_sec, + e_min, + e_hour, + e_day, + e_year; + public: + Clock(); + + void initiate_clock(); + + void start_timing(); + unsigned int ent_timing(); + +}; + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/create_unit.cpp b/Version_Max_07_05_2018_CMake/src/create_unit.cpp new file mode 100755 index 0000000..14f1f6d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/create_unit.cpp @@ -0,0 +1,400 @@ +#include "create_unit.h" +#include +#include "errno.h" +#include "rlutil.h" + +using namespace rlutil; + +void print_agent(Agent agent) { + +} + +Agent* create_agent() { + return create_agent(NO_NAME); +} + +Agent* create_agent(char* name) { + Agent* agent = new Agent(name); + + printf(" > Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", agent->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + setColor(TXTCOLOR_GREY); + + return agent; +} + + +Sensor* create_sensor() { + return create_sensor(NO_NAME); +} + +Sensor* create_sensor(char* name) { + Sensor* sensor = new Sensor(name); + + printf(" > Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + setColor(TXTCOLOR_GREY); + + return sensor; +} + + +HistoryModule create_historyModule(unsigned int history_length, int delimitation_mode) { + return create_historyModule(NO_NAME, history_length, delimitation_mode); +} + +HistoryModule create_historyModule(char* name, unsigned int history_length, int delimitation_mode) { + + HistoryModule historyModule(name); + + printf(" > History "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", historyModule.get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", historyModule.get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + setColor(TXTCOLOR_GREY); + if(historyModule.set_maxHistoryLength(history_length)) { + printf(" > History length "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to %u\n", history_length); + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > historyLength could not set (out of allowed range)."); + setColor(TXTCOLOR_GREY); + } + if(historyModule.set_delimitationMode(delimitation_mode)) { + printf(" > Delimitation Mode "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to %u\n", delimitation_mode); + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Delimitation Mode could not set (out of allowed range)."); + setColor(TXTCOLOR_GREY); + } + + return historyModule; +} + +Channel* create_channel(unsigned int transfer_rate) { + return create_channel(NO_NAME, transfer_rate); +} + +Channel* create_channel(char* name, unsigned int transfer_rate) { + + Channel* channel = new Channel(name); + + printf(" > Channel "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", channel->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", channel->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + setColor(TXTCOLOR_GREY); + + if(channel->set_transferRate(transfer_rate)) { + if(transfer_rate != 0) { + printf(" > transfer rate "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to %i\n", transfer_rate); + } + else { + printf(" > transfer "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to immediately transportation\n"); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Transfer Rate out of allowed bounds!\n"); + setColor(TXTCOLOR_GREY); + } + + return channel; +} + + + + +Testbench* create_testbench() { + return create_testbench(NO_NAME); +} + +Testbench* create_testbench(char* name) { + Testbench* testbench = new Testbench(name); + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", testbench->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", testbench->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + testbench->init_testbench(); + return testbench; +} + +/* +Lookuptable create_lookuptable() { + Lookuptable lut; + + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", lut.get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", lut.get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + + return lut; +} + +Lookuptable create_lookuptable(char* name) { + Lookuptable lut(name); + + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", lut.get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", lut.get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + + return lut; +} + +void print_confidence_validator(Confidence_Validator conf_valid) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", conf_valid.get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", conf_valid.get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + + printf(" - range of validity "); + if(conf_valid.get_flag_lower_bound_exist()) + printf("[ %.3f, ", conf_valid.get_lower_bound()); + else + printf("] -inf, "); + if(conf_valid.get_flag_upper_bound_exist()) + printf("%.3f ] ", conf_valid.get_upper_bound()); + else + printf("+inf [ "); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + rlutil::setColor(TXTCOLOR_GREY); + + if(conf_valid.get_flag_rates_of_change_exist()) { + printf(" - validity for rates of change of "); + printf("%.3f ", conf_valid.get_rates_of_change()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + rlutil::setColor(TXTCOLOR_GREY); + } +} + +Confidence_Validator create_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) { + Confidence_Validator conf_valid(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist); + print_confidence_validator(conf_valid); + + return conf_valid; +} + +Confidence_Validator create_confidence_validator(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) { + Confidence_Validator conf_valid(name, lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist); + print_confidence_validator(conf_valid); + + return conf_valid; +} + +void print_abstraction_module(Abstraction abstraction) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", abstraction.get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", abstraction.get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + + //TODO: abstraction method printen + printf(" - abstraction method %u ", abstraction.get_abstraction_method()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + rlutil::setColor(TXTCOLOR_GREY); + + //TODO: auch das hier bissl sch�ner machen + if(abstraction.get_flag_lookuptable_exist(0)) { + printf(" - position 0 connected mit Look up Table "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", abstraction.get_lookuptable(0)->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", abstraction.get_lookuptable(0)->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + rlutil::setColor(TXTCOLOR_GREY); + } +} + +Abstraction create_abstraction_module(Lookuptable* lut, unsigned int abstraction_method) { + Abstraction abstraction(lut, abstraction_method); + print_abstraction_module(abstraction); + + return abstraction; +} + +Abstraction create_abstraction_module(char* name, Lookuptable* lut, unsigned int abstraction_method) { + Abstraction abstraction(name, lut, abstraction_method); + print_abstraction_module(abstraction); + + return abstraction; +} + +void print_bunch_module(Bunch_Module bunch_module) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", bunch_module.get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", bunch_module.get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); + + //TODO: abstraction method printen + printf(" - abstraction method %u ", bunch_module.get_bunch_method()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + rlutil::setColor(TXTCOLOR_GREY); +} + + +Bunch_Module create_bunch_module(unsigned int bunch_method) { + Bunch_Module bunch_module(bunch_method); + print_bunch_module(bunch_module); + + return bunch_module; +} + +Bunch_Module create_bunch_module(char* name, unsigned int bunch_method) { + Bunch_Module bunch_module(name, bunch_method); + print_bunch_module(bunch_module); + + return bunch_module; +} +*/ + +FILE* make_file_pointer(const char* filepath, int mode) { + + FILE* fpointer; + bool file_opened; + + if(mode == CSV_MODE_READ) { + // file_opened = fopen_s(&fpointer, filepath, "r"); //only windows compatible + fpointer = fopen(filepath, "r"); + } + else if(mode == CSV_MODE_WRITE) { + // file_opened = fopen_s(&fpointer, filepath, "w"); //only windows compatible + fpointer = fopen(filepath, "w"); + } + else { + printf("File pointer mode for \"%s\" ", filepath); + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("is not supported!\n"); + rlutil::setColor(TXTCOLOR_GREY); + + return NULL; + } + + //if(file_opened == 0) { + if(errno == 0) { + return fpointer; + } + + printf("File pointer \"%s\" ", filepath); + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("could not created!\n"); + rlutil::setColor(TXTCOLOR_GREY); + + return NULL; +} + +void print_csv_reader(CSVreaderModule* csvReaderModule,const char* filepath) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", csvReaderModule->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) for \"%s\" ", csvReaderModule->get_id(), filepath); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("created\n"); + rlutil::setColor(TXTCOLOR_GREY); +} + +CSVreaderModule* create_CSVreaderModule(const char* filepath, unsigned int column, unsigned int start_row) { + + FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ); + + if(fpointer) { + CSVreaderModule* csvr = new CSVreaderModule(fpointer, column, start_row); + print_csv_reader(csvr, filepath); + + return csvr; + } + else { + CSVreaderModule* csvr = new CSVreaderModule(); + + return csvr; + } +} + +CSVreaderModule* create_CSVreaderModule(char* name,const char* filepath, unsigned int column, unsigned int start_row) { + + FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ); + + if(fpointer) { + CSVreaderModule* csvr = new CSVreaderModule(name, fpointer, column, start_row); + print_csv_reader(csvr, filepath); + + return csvr; + } + else { + CSVreaderModule* csvr = new CSVreaderModule; + + return csvr; + } +} + + +StateHandler create_stateHandler() { + return create_stateHandler(NO_NAME); +} + +StateHandler create_stateHandler(char* name) { + StateHandler stateHandler(name); + return stateHandler; +} diff --git a/Version_Max_07_05_2018_CMake/src/create_unit.h b/Version_Max_07_05_2018_CMake/src/create_unit.h new file mode 100755 index 0000000..c9934e8 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/create_unit.h @@ -0,0 +1,62 @@ +#ifndef CREATE_UNIT_HEADERFILE +#define CREATE_UNIT_HEADERFILE + +#include +#include "Agent.h" +#include "CSVreaderModule.h" +#include "HistoryModule.h" +#include "Sensor.h" +#include "Testbench.h" + +/* +#include "Testbench.h" +#include "Lookuptable.h" +#include "ConfidenceModule.h" +#include "Bunch_Module.h" +*/ + +#define CSV_MODE_READ 0 +#define CSV_MODE_WRITE 1 + +Agent* create_agent(); +Agent* create_agent(char* name); + +/* +Agent create_agent(unsigned int abstraction_method); +Agent create_agent(char* name, unsigned int abstraction_method); +*/ + +Sensor* create_sensor(); +Sensor* create_sensor(char* name); + +HistoryModule create_historyModule(unsigned int history_length, int delimitation_mode); +HistoryModule create_historyModule(char* name, unsigned int history_length, int delimitation_mode); + +Channel* create_channel(unsigned int transfer_rate); +Channel* create_channel(char* name, unsigned int transfer_rate); + +Testbench* create_testbench(); +Testbench* create_testbench(char* name); + +/* +Lookuptable create_lookuptable(); +Lookuptable create_lookuptable(char* name); + +ConfidenceModule create_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist); +ConfidenceModule create_confidence_validator(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist); + +AbstractionModule create_abstraction_module(Lookuptable* lut, unsigned int abstraction_method); +AbstractionModule create_abstraction_module(char* name, Lookuptable* lut, unsigned int abstraction_method); + +Bunch_Module create_bunch_module(unsigned int bunch_method); +Bunch_Module create_bunch_module(char* name, unsigned int bunch_method); +*/ + +CSVreaderModule* create_CSVreaderModule(const char* filepath, unsigned int column, unsigned int start_row); +CSVreaderModule* create_CSVreaderModule(char* name,const char* filepath, unsigned int column, unsigned int start_row); + +StateHandler create_stateHandler(); +StateHandler create_stateHandler(char* name); + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/csvparser.c b/Version_Max_07_05_2018_CMake/src/csvparser.c new file mode 100755 index 0000000..4be5c91 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/csvparser.c @@ -0,0 +1,239 @@ +#include +#include +#include +#include + +#include "csvparser.h" + +#ifdef __cplusplus +extern "C" { +#endif + +CsvParser *CsvParser_new(const char *filePath, const char *delimiter, int firstLineIsHeader) { + CsvParser *csvParser = (CsvParser*)malloc(sizeof(CsvParser)); + if (filePath == NULL) { + csvParser->filePath_ = NULL; + } else { + int filePathLen = strlen(filePath); + csvParser->filePath_ = (char*)malloc((filePathLen + 1)); + strcpy(csvParser->filePath_, filePath); + } + csvParser->firstLineIsHeader_ = firstLineIsHeader; + csvParser->errMsg_ = NULL; + if (delimiter == NULL) { + csvParser->delimiter_ = ','; + } else if (_CsvParser_delimiterIsAccepted(delimiter)) { + csvParser->delimiter_ = *delimiter; + } else { + csvParser->delimiter_ = '\0'; + } + csvParser->header_ = NULL; + csvParser->fileHandler_ = NULL; + csvParser->fromString_ = 0; + csvParser->csvString_ = NULL; + csvParser->csvStringIter_ = 0; + + return csvParser; +} + +CsvParser *CsvParser_new_from_string(const char *csvString, const char *delimiter, int firstLineIsHeader) { + CsvParser *csvParser = CsvParser_new(NULL, delimiter, firstLineIsHeader); + csvParser->fromString_ = 1; + if (csvString != NULL) { + int csvStringLen = strlen(csvString); + csvParser->csvString_ = (char*)malloc(csvStringLen + 1); + strcpy(csvParser->csvString_, csvString); + } + return csvParser; +} + +void CsvParser_destroy(CsvParser *csvParser) { + if (csvParser == NULL) { + return; + } + if (csvParser->filePath_ != NULL) { + free(csvParser->filePath_); + } + if (csvParser->errMsg_ != NULL) { + free(csvParser->errMsg_); + } + if (csvParser->fileHandler_ != NULL) { + fclose(csvParser->fileHandler_); + } + if (csvParser->header_ != NULL) { + CsvParser_destroy_row(csvParser->header_); + } + if (csvParser->csvString_ != NULL) { + free(csvParser->csvString_); + } + free(csvParser); +} + +void CsvParser_destroy_row(CsvRow *csvRow) { + int i; + for (i = 0 ; i < csvRow->numOfFields_ ; i++) { + free(csvRow->fields_[i]); + } + free(csvRow->fields_); + free(csvRow); +} + +CsvRow *CsvParser_getHeader(CsvParser *csvParser) { + if (! csvParser->firstLineIsHeader_) { + _CsvParser_setErrorMessage(csvParser, "Cannot supply header, as current CsvParser object does not support header"); + return NULL; + } + if (csvParser->header_ == NULL) { + csvParser->header_ = _CsvParser_getRow(csvParser); + } + return csvParser->header_; +} + +CsvRow *CsvParser_getRow(CsvParser *csvParser) { + if (csvParser->firstLineIsHeader_ && csvParser->header_ == NULL) { + csvParser->header_ = _CsvParser_getRow(csvParser); + } + return _CsvParser_getRow(csvParser); +} + +int CsvParser_getNumFields(CsvRow *csvRow) { + return csvRow->numOfFields_; +} + +const char **CsvParser_getFields(CsvRow *csvRow) { + return (const char**)csvRow->fields_; +} + +CsvRow *_CsvParser_getRow(CsvParser *csvParser) { + int numRowRealloc = 0; + int acceptedFields = 64; + int acceptedCharsInField = 64; + if (csvParser->filePath_ == NULL && (! csvParser->fromString_)) { + _CsvParser_setErrorMessage(csvParser, "Supplied CSV file path is NULL"); + return NULL; + } + if (csvParser->csvString_ == NULL && csvParser->fromString_) { + _CsvParser_setErrorMessage(csvParser, "Supplied CSV string is NULL"); + return NULL; + } + if (csvParser->delimiter_ == '\0') { + _CsvParser_setErrorMessage(csvParser, "Supplied delimiter is not supported"); + return NULL; + } + if (! csvParser->fromString_) { + if (csvParser->fileHandler_ == NULL) { + csvParser->fileHandler_ = fopen(csvParser->filePath_, "r"); + if (csvParser->fileHandler_ == NULL) { + int errorNum = errno; + const char *errStr = strerror(errorNum); + char *errMsg = (char*)malloc(1024 + strlen(errStr)); + strcpy(errMsg, ""); + sprintf(errMsg, "Error opening CSV file for reading: %s : %s", csvParser->filePath_, errStr); + _CsvParser_setErrorMessage(csvParser, errMsg); + free(errMsg); + return NULL; + } + } + } + CsvRow *csvRow = (CsvRow*)malloc(sizeof(CsvRow)); + csvRow->fields_ = (char**)malloc(acceptedFields * sizeof(char*)); + csvRow->numOfFields_ = 0; + int fieldIter = 0; + char *currField = (char*)malloc(acceptedCharsInField); + int inside_complex_field = 0; + int currFieldCharIter = 0; + int seriesOfQuotesLength = 0; + int lastCharIsQuote = 0; + int isEndOfFile = 0; + while (1) { + char currChar = (csvParser->fromString_) ? csvParser->csvString_[csvParser->csvStringIter_] : fgetc(csvParser->fileHandler_); + csvParser->csvStringIter_++; + int endOfFileIndicator; + if (csvParser->fromString_) { + endOfFileIndicator = (currChar == '\0'); + } else { + endOfFileIndicator = feof(csvParser->fileHandler_); + } + if (endOfFileIndicator) { + if (currFieldCharIter == 0 && fieldIter == 0) { + _CsvParser_setErrorMessage(csvParser, "Reached EOF"); + free(currField); + CsvParser_destroy_row(csvRow); + return NULL; + } + currChar = '\n'; + isEndOfFile = 1; + } + if (currChar == '\r') { + continue; + } + if (currFieldCharIter == 0 && ! lastCharIsQuote) { + if (currChar == '\"') { + inside_complex_field = 1; + lastCharIsQuote = 1; + continue; + } + } else if (currChar == '\"') { + seriesOfQuotesLength++; + inside_complex_field = (seriesOfQuotesLength % 2 == 0); + if (inside_complex_field) { + currFieldCharIter--; + } + } else { + seriesOfQuotesLength = 0; + } + if (isEndOfFile || ((currChar == csvParser->delimiter_ || currChar == '\n') && ! inside_complex_field) ){ + currField[lastCharIsQuote ? currFieldCharIter - 1 : currFieldCharIter] = '\0'; + csvRow->fields_[fieldIter] = (char*)malloc(currFieldCharIter + 1); + strcpy(csvRow->fields_[fieldIter], currField); + free(currField); + csvRow->numOfFields_++; + if (currChar == '\n') { + return csvRow; + } + if (csvRow->numOfFields_ != 0 && csvRow->numOfFields_ % acceptedFields == 0) { + csvRow->fields_ = (char**)realloc(csvRow->fields_, ((numRowRealloc + 2) * acceptedFields) * sizeof(char*)); + numRowRealloc++; + } + acceptedCharsInField = 64; + currField = (char*)malloc(acceptedCharsInField); + currFieldCharIter = 0; + fieldIter++; + inside_complex_field = 0; + } else { + currField[currFieldCharIter] = currChar; + currFieldCharIter++; + if (currFieldCharIter == acceptedCharsInField - 1) { + acceptedCharsInField *= 2; + currField = (char*)realloc(currField, acceptedCharsInField); + } + } + lastCharIsQuote = (currChar == '\"') ? 1 : 0; + } +} + +int _CsvParser_delimiterIsAccepted(const char *delimiter) { + char actualDelimiter = *delimiter; + if (actualDelimiter == '\n' || actualDelimiter == '\r' || actualDelimiter == '\0' || + actualDelimiter == '\"') { + return 0; + } + return 1; +} + +void _CsvParser_setErrorMessage(CsvParser *csvParser, const char *errorMessage) { + if (csvParser->errMsg_ != NULL) { + free(csvParser->errMsg_); + } + int errMsgLen = strlen(errorMessage); + csvParser->errMsg_ = (char*)malloc(errMsgLen + 1); + strcpy(csvParser->errMsg_, errorMessage); +} + +const char *CsvParser_getErrorMessage(CsvParser *csvParser) { + return csvParser->errMsg_; +} + +#ifdef __cplusplus +} +#endif diff --git a/Version_Max_07_05_2018_CMake/src/csvparser.h b/Version_Max_07_05_2018_CMake/src/csvparser.h new file mode 100755 index 0000000..9d08966 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/csvparser.h @@ -0,0 +1,52 @@ +#ifndef CSVPARSER_H +#define CSVPARSER_H + +#include + +#define _CRT_SECURE_NO_WARNINGS + + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct CsvRow { + char **fields_; + int numOfFields_; +} CsvRow; + +typedef struct CsvParser { + char *filePath_; + char delimiter_; + int firstLineIsHeader_; + char *errMsg_; + CsvRow *header_; + FILE *fileHandler_; + int fromString_; + char *csvString_; + int csvStringIter_; +} CsvParser; + + +// Public +CsvParser *CsvParser_new(const char *filePath, const char *delimiter, int firstLineIsHeader); +CsvParser *CsvParser_new_from_string(const char *csvString, const char *delimiter, int firstLineIsHeader); +void CsvParser_destroy(CsvParser *csvParser); +void CsvParser_destroy_row(CsvRow *csvRow); +CsvRow *CsvParser_getHeader(CsvParser *csvParser); +CsvRow *CsvParser_getRow(CsvParser *csvParser); +int CsvParser_getNumFields(CsvRow *csvRow); +const char **CsvParser_getFields(CsvRow *csvRow); +const char* CsvParser_getErrorMessage(CsvParser *csvParser); + +// Private +CsvRow *_CsvParser_getRow(CsvParser *csvParser); +int _CsvParser_delimiterIsAccepted(const char *delimiter); +void _CsvParser_setErrorMessage(CsvParser *csvParser, const char *errorMessage); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/extremaValues.cpp b/Version_Max_07_05_2018_CMake/src/extremaValues.cpp new file mode 100755 index 0000000..e69de29 diff --git a/Version_Max_07_05_2018_CMake/src/extremaValues.h b/Version_Max_07_05_2018_CMake/src/extremaValues.h new file mode 100755 index 0000000..6c0fe8a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/extremaValues.h @@ -0,0 +1,17 @@ +#ifndef MAXIMUMVALUE_HEADERFILE +#define MAXIMUMVALUE_HEADERFILE + +class MaximumValue { + +private: + float maxValue; + bool flagMaxValueIsSet; + +public: + MaximumValue(); + + void calculateMaxValue(float value); + float get_maxValue(); +}; + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/file_util.h b/Version_Max_07_05_2018_CMake/src/file_util.h new file mode 100755 index 0000000..04818b7 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/file_util.h @@ -0,0 +1,70 @@ +/* + * file_util.h + * + * Created on: 22.05.2018 + * Author: edwin + * + * This file contains constant definitions for different file names, which are + * used as input files. + */ + +#ifndef FILE_UTIL_H_ +#define FILE_UTIL_H_ + +//defines to swtich the file-configurations applied in file file_util.h +//#define CASE_WR_NEUSTADT 1 +#define CASE_OMV 1 + +//#define CASE_OPEL 1 + +#ifdef CASE_WR_NEUSTADT +//information related to the csv data files +//definitions for measurements from Wr. Neustadt. +const std::string PATH_TO_CSV_DATA_FILES = "./data_csv/Messungen_Wr_Neustadt"; +const std::string PATH_TO_DATE_OF_MEASUREMENT = "/2018_05_23"; +const std::string PATH_TO_AN_MEASURMENT = "/20180523_normal_SS_closed_SB_open/"; +const std::string FILE_NAME_VOLTAGE = "Voltage.csv"; +const std::string FILE_NAME_TEMP_1 = "Temp1.csv"; +const std::string FILE_NAME_TEMP_2 = "Temp2.csv"; +const std::string FILE_NAME_SHARKY_S = "SharkyS.csv"; +const std::string FILE_NAME_SHARKY_B = "SharkyB.csv"; +const std::string FILE_NAME_RIELS = "Riels.csv"; +const std::string FILE_NAME_DYNA = "Dyna.csv"; + +#elif CASE_OMV +//information related to the csv data files +//definitions for measurements from Wr. Neustadt. +const std::string PATH_TO_CSV_DATA_FILES = "./data_csv/OMV"; +//settings for file B960428-Jun-2018 09-15-21.csv +//const std::string PATH_TO_DATE_OF_MEASUREMENT = "/2017_12_18"; +//const std::string PATH_TO_AN_MEASURMENT = "/"; +//extendend data with 30 minutes more than in file "B960425-Jun-2018 09-45-01.csv" +//const std::string FILE_NAME_OF_ENTIRE_DATA = "B960428-Jun-2018 09-15-21.csv"; +//const std::string FILE_NAME_OF_ENTIRE_DATA = "B960425-Jun-2018 09-45-01.csv"; +//settings for file 2017_01_07__05_46_fc6504.csv +const std::string PATH_TO_DATE_OF_MEASUREMENT = "/2017_01_07"; +const std::string PATH_TO_AN_MEASURMENT = "/"; +const std::string FILE_NAME_OF_ENTIRE_DATA = "2017_01_07__05_46_fc6504.csv"; + +//definitions for motor measurements +const std::string FOLDERNAME_NORMAL_OPERATION = "/Normal_operation-Tm0/"; + +#elif CASE_OPEL +const std::string PATH_TO_CSV_DATA_FILES = "./data_csv/Opel"; +const std::string PATH_TO_DATE_OF_MEASUREMENT = ""; +//for Draft Messergeb OP90_decimalPoint.csv +//const std::string PATH_TO_AN_MEASURMENT = "/"; +//for "GA_daten_200_samples.csv" +//const std::string PATH_TO_AN_MEASURMENT = "/Ga_daten/"; +//for "Ga_all_Symmetrie_Combined_25000_to_30000.csv" +const std::string PATH_TO_AN_MEASURMENT = "/Ga_daten_with_Symmetrie/"; + +//entire data set +//const std::string FILE_NAME_OF_ENTIRE_DATA = "Draft Messergeb OP90_decimalPoint.csv"; +//only 200 data points beginning of row 8450 and only Ga data for 200 values. +//const std::string FILE_NAME_OF_ENTIRE_DATA = "GA_daten_200_samples.csv"; +//for data combination o all ga data with the symmetrie column and from data point 25000 to 30000 +const std::string FILE_NAME_OF_ENTIRE_DATA = "Ga_all_Symmetrie_Combined_25000_to_30000.csv"; +#endif + +#endif /* FILE_UTIL_H_ */ diff --git a/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp new file mode 100755 index 0000000..0d48eb6 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp @@ -0,0 +1,87 @@ +#include "inAgentsRegistrations.h" + +#include "rlutil.h" + +using namespace rlutil; + +bool registerSlaveAgentAsInputVariableInStateHandler(Agent* masteragent, Channel* channel) { + if(masteragent != NULL, channel != NULL) { + SlaveAgentSlotOfAgent* slot = masteragent->get_slaveAgentHandlerOfAgent()->get_slaveAgentSlotAddress(channel); + if(slot != NULL) { + if(masteragent->get_stateHandler()->addInputVariable(slot)){ + printf(" > Channel "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", channel->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", channel->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("registered "); + setColor(TXTCOLOR_GREY); + printf("as "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("Input Variable "); + setColor(TXTCOLOR_GREY); + printf("in stateHandler of "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", masteragent->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Agent or Channel is not valid\n"); + } + return false; +} + +bool registerSlaveAgentAsOutputVariableInStateHandler(Agent* masteragent, Channel* channel) { + if (masteragent != NULL, channel != NULL) { + SlaveAgentSlotOfAgent* slot = masteragent->get_slaveAgentHandlerOfAgent()->get_slaveAgentSlotAddress(channel); + if (slot != NULL) { + if (masteragent->get_stateHandler()->addOutputVariable(slot)) { + printf(" > Channel "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", channel->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", channel->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("registered "); + setColor(TXTCOLOR_GREY); + printf("as "); + setColor(TXTCOLOR_LIGHTGREEN); + printf("Output Variable "); + setColor(TXTCOLOR_GREY); + printf("in stateHandler of "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", masteragent->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Agent or Channel is not valid\n"); + } + return false; +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.h b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.h new file mode 100755 index 0000000..c561b79 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.h @@ -0,0 +1,4 @@ +#include "Agent.h" + +bool registerSlaveAgentAsInputVariableInStateHandler(Agent* masteragent, Channel* channel); +bool registerSlaveAgentAsOutputVariableInStateHandler(Agent* masteragent, Channel* channel); \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/instruction_set_architecture.h b/Version_Max_07_05_2018_CMake/src/instruction_set_architecture.h new file mode 100755 index 0000000..a4d49fb --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/instruction_set_architecture.h @@ -0,0 +1,24 @@ +#ifndef INSTRUCTION_SET_HEADERFILE +#define INSTRUCTION_SET_HEADERFILE + + +#define ISA_NoInstruction 0x0000 + +#define ISA_SendYourId 0x0101 +#define ISA_ThisIsMyId 0x0102 + + + +#define ISA_SensoryData 0x0200 +#define ISA_SensoryData_SendersID 0x0201 +#define ISA_SensoryData_ReiceiversID 0x0202 +#define ISA_SensoryData_SendersID_ReiceiversID 0x0203 +#define ISA_SensoryData_BinaryConfidenceTag 0x0204 + +#define ISA_SlaveAgentData 0x0300 +#define ISA_SlaveAgentWithBinaryConfidenceTag 0x0301 + + + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/main.cpp b/Version_Max_07_05_2018_CMake/src/main.cpp new file mode 100755 index 0000000..9bdf415 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main.cpp @@ -0,0 +1,1128 @@ +/* + * main.cpp + * + * Created on: 25.05.2018 + * Author: edwin willegger, edwin.willegger@tuwien.ac.at + * This file is used to generate output data from measurements + * from OMV for SAVE project. + * In this case the data of the 18.12.2017 is analyzed. + * Based on the implementation of Maximilian Götzinger. + */ + +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include +#include +#include +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + +#include "Testbench_Config.h" + +using namespace std; + +/********************************************************************************************************************** + ************************************************begin of global definitions of variables and constants *************** + **********************************************************************************************************************/ + +//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files. +#define SAMPLING 1 + +//global vectors for the different elements +static vector vec_of_Agents; +static vector vec_of_Sensors; +static vector vec_of_Channels_for_Sensors; +static vector vec_of_Channels_for_Agents; +static vector vec_of_linear_Function_Blocks; +static vector vec_of_test_benches; +static vector vec_of_csv_readers; + +//names of the measured data +const string FIRST_MEASURED_DATA_NAME = "FC6504_Y"; //Input +const string SECOND_MEASURED_DATA_NAME = "FC6504"; //Output +const string THIRD_MEASURED_DATA_NAME = "FC6504_SP"; //Input +const string FOURTH_MEASURED_DATA_NAME = "PI6584"; //Input + + +//viability monitor +const string VIABILITY_MONITOR = "ViabilityMonitor"; +//index number of output +const int INDEX_OUTPUT = 1; + +//name for the channels of the sensors and agents +const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)"; +const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)"; +const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; + +#define TRANSFER_RATE_CHANNEL_SENSOR 0 +#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH + + +////////////////////////////////////////////// +/* +//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery. + inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx + outer_bound_xxx = / | \ + / | \ + 0=__________/ | \ = outer_bound_xxxx ______ = 0 +-------------------------------------------------------------------------- +*/ + +//parameters of boundary for similar function +#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06, +#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent + +//same way as above but shows drift. +#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3 +#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF + +//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu +//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat. +#define BOUND_BROKEN 2 + +//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery. +//history of the data depends of it, and should change, if it changes. +#define LENGTH 10 + + +//definitions for the testbench +const string TEST_BENCH = "testbench"; + +//defintions for the csv-reader-modules +const string APPENDIX_CSV_MODULES = " CSV-Reader"; +const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; + + +//to switch between different file configurations change the +//DEFINES in file_util.h + +/********************************************************************************************************************** + ************************************************end of global definitions of variables and constants ***************** + **********************************************************************************************************************/ + +/********************************************************************************************************************** + ************************************************begin of function prototypes ***************************************** + **********************************************************************************************************************/ +void create_and_register_all_Testbench_Configs(Testbench* current_tb); + +void create_and_register_All_Agents(); +void set_working_cycle_of_All_Agents(); + +void create_and_register_All_Sensors(); +void set_working_cycle_of_All_Sensors(); + +void create_and_register_channels(); +void create_and_register_channels_for_sensors(); +void create_and_register_channels_for_agents(); + +void mount_sensors_in_agents(); +void mount_agents_in_agents(); + +void register_data_agents_in_agent_state_Handler(); + +void create_linear_function_blocks(); +void create_same_state_deviation_function_block(); +void create_another_state_deviation_function_block(); +void create_state_time_function_block(); +void create_another_state_time_function_block(); +void create_valid_state_deviation_function_block(); +void create_invalid_state_deviation_function_block(); +void create_valid_state_time_function_block(); +void create_invalid_state_time_function_block(); +void create_confidence_state_drift_function_block(); +void create_confidence_broken_function_block(); +void mount_function_blocks_to_viability_monitor(); + +void create_all_testbenches(); + +void create_csvr_modules(); + +void register_agents_in_testbenches(); + +void register_sensors_in_testbenches(); + +void register_channels_in_testbenches(); +void register_channels_of_sensors_in_testbenches(); +void register_channels_of_actors_in_testbenches(); + +void set_config_values_in_linear_functions(Testbench* current_tb); +void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block); +void set_parameters_LinearFunction(vector vec_Lin_Func); + +void set_CSV_Writer_parameter(Testbench* current_tb); + +void run_simulation_of_all_testbenches(); + +void close_file_pointers(); + +void empty_static_vectors(); +void empty_vec_Agent(); +void empty_vec_Channel_Agent(); +void empty_vec_Channel_Sensor(); +void empty_vec_Sensors(); +void empty_vec_csv_raders(); +void empty_vec_linear_func_Blocks(); +void empty_vec_TestBench(); + + +/********************************************************************************************************************** + ************************************************end of function prototypes ******************************************* + **********************************************************************************************************************/ + +int main() +{ + cout << "This program processes test data from OMV Steam Cracker furnaces." << endl; + + create_and_register_All_Agents(); + set_working_cycle_of_All_Agents(); + + + create_and_register_All_Sensors(); + set_working_cycle_of_All_Sensors(); + + create_and_register_channels(); + + mount_sensors_in_agents(); + + mount_agents_in_agents(); + + register_data_agents_in_agent_state_Handler(); + + create_linear_function_blocks(); + + mount_function_blocks_to_viability_monitor(); + + create_all_testbenches(); + + create_csvr_modules(); + + register_agents_in_testbenches(); + + register_sensors_in_testbenches(); + + register_channels_in_testbenches(); + + + + run_simulation_of_all_testbenches(); + + //close_file_pointers(); + //TODO memory free of all objects. + empty_static_vectors(); + + cout << "Program finished successfully" << endl; + return 0; +} + +void create_and_register_all_Testbench_Configs(Testbench* current_tb) +{ + + One_Config_t one; + one.bound_broken = 2; + one.inner_bound_sim_dif = 0.02; + one.outter_bound_sim_dif = 0.08; + one.inner_bound_drift = 3 * one.outter_bound_sim_dif; + one.inner_bound_drift = one.outter_bound_sim_dif; + one.length = 10; + Testbench_Config* cfg = new Testbench_Config(one); + cfg->print(); + current_tb->register_testbench_config(cfg); +} + + + +/* + * creates all the agents used in the measurement + * and stores them into the global vector + */ +void create_and_register_All_Agents() +{ + cout << "Creating Agents" << endl; + char* c_name_of_current_agent = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6504_Y = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6504 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6504_SP = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str()); + Agent* a_PI6584 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str()); + Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent); + vec_of_Agents.push_back(a_FC6504_Y); + vec_of_Agents.push_back(a_FC6504); + vec_of_Agents.push_back(a_FC6504_SP); + vec_of_Agents.push_back(a_PI6584); + vec_of_Agents.push_back(a_viabilityMonitor); + cout << vec_of_Agents.size() << " agents were created" << endl; + delete c_name_of_current_agent; +} + +/* + * the working_cycle for all registered agents is set + */ +void set_working_cycle_of_All_Agents() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Agents = 0; + unsigned int index = 0; + Agent* current_Agent; + size_of_vec_of_Agents = vec_of_Agents.size(); + for(index = 0; index < size_of_vec_of_Agents; index++) { + current_Agent = vec_of_Agents[index]; + setWorkingCycleOfAgent(current_Agent, working_Cyle); + } +} + +/* + * all necessary sensors are created and registered + */ +void create_and_register_All_Sensors() +{ + cout << "Creating Sensors" << endl; + char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6504_Y = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6504 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6504_SP = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_PI6584 = create_sensor(c_name_of_current_sensor); + vec_of_Sensors.push_back(s_FC6504_Y); + vec_of_Sensors.push_back(s_FC6504); + vec_of_Sensors.push_back(s_FC6504_SP); + vec_of_Sensors.push_back(s_PI6584); + cout << vec_of_Sensors.size() << " sensors were created." << endl; + delete c_name_of_current_sensor; +} + +/* + * working cycle of all registered sensors is set + */ +void set_working_cycle_of_All_Sensors() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Sensors = 0; + unsigned int index = 0; + Sensor* current_Sensor; + + size_of_vec_of_Sensors = vec_of_Sensors.size(); + for(index = 0; index < size_of_vec_of_Sensors; index++) { + current_Sensor = vec_of_Sensors[index]; + setWorkingCycleOfSensor(current_Sensor, working_Cyle); + } +} + +/* + * creating and registering all channels + */ +void create_and_register_channels() +{ + create_and_register_channels_for_sensors(); + create_and_register_channels_for_agents(); +} + +/* + * creating and registering the channels for the sensors. + */ +void create_and_register_channels_for_sensors() +{ + cout << "Creating and registering channels for sensors" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6504_Y = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6504 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6504_SP = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_PI6584 = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_Y); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6504); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_SP); + vec_of_Channels_for_Sensors.push_back(c_sa_PI6584); + cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl; + + delete c_name_of_current_channel; +} + +/* + * creating and registering the channels for the agents + */ +void create_and_register_channels_for_agents() +{ + cout << "Creating and registering channels for agents" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6504_Y = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6504 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6504_SP = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_PI6584 = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Agents.push_back(c_aa_FC6504_Y); + vec_of_Channels_for_Agents.push_back(c_aa_FC6504); + vec_of_Channels_for_Agents.push_back(c_aa_FC6504_SP); + vec_of_Channels_for_Agents.push_back(c_aa_PI6584); + + cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl; + + delete c_name_of_current_channel; +} + +void mount_sensors_in_agents() +{ + Agent* current_agent; + Sensor* current_sensor; + Channel* current_sensor_channel; + unsigned int size_of_vec_sensor = 0; + unsigned int index = 0; + + size_of_vec_sensor = vec_of_Sensors.size(); + cout << "mounting sensors in agents." << endl; + //it is assumed that the corresponding sensors and agents and channels are always at the same + //position in the different vectors, if not then you have to add an search algorithm for it. + for(index = 0; index < size_of_vec_sensor; index++) + { + current_agent = vec_of_Agents[index]; + current_sensor = vec_of_Sensors[index]; + current_sensor_channel = vec_of_Channels_for_Sensors[index]; + mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel); + } + cout << size_of_vec_sensor << " sensors in agents were mounted" << endl; +} + +void mount_agents_in_agents() +{ + Agent* current_agent; + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_agents = 0; + unsigned int index = 0; + + size_of_vec_agents = vec_of_Agents.size(); + //it is assumed that the viability agent is at the last position in the vector + viability_Monitor = vec_of_Agents[size_of_vec_agents-1]; + //all agents and channels are registered to the viabilityMonitor agent + //so you have to subtract the viabilityMonitor from the number of elements to register + //it is assumed that all the corresponding channels and agents are placed at the same index + for(index = 0; index < size_of_vec_agents -1; index++) + { + current_agent = vec_of_Agents[index]; + current_agent_channel = vec_of_Channels_for_Agents[index]; + //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself. + if(current_agent != viability_Monitor) { + mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel); + } + } + cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl; +} + +/* + * registers the channels for the data agents to the viability monitor + */ +void register_data_agents_in_agent_state_Handler() + +{ + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_channel_agents = 0; + unsigned int index = 0; + + size_of_vec_channel_agents = vec_of_Channels_for_Agents.size(); + //get the agent for the viabilityMonitor, it is assumed that it is at the last position + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + //register all the channels to the viability monitor + for(index = 0; index < size_of_vec_channel_agents; index++) { + current_agent_channel = vec_of_Channels_for_Agents[index]; + if(index != INDEX_OUTPUT) { + registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel); + } + else{ + registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel); + } + } +} + +/* + * creates and register all the different linear function blocks + */ +void create_linear_function_blocks() +{ + //don't change the sequence, because later it is assumed that the functions are + //registered int the vector in this sequence + //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor + create_same_state_deviation_function_block(); + create_another_state_deviation_function_block(); + create_state_time_function_block(); + create_another_state_time_function_block(); + create_valid_state_deviation_function_block(); + create_invalid_state_deviation_function_block(); + create_valid_state_time_function_block(); + create_invalid_state_time_function_block(); + create_confidence_state_drift_function_block(); + create_confidence_broken_function_block(); +} + +/* + * creates and register the linear function block for same state deviation + */ +void create_same_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str()); + LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1); + funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev1->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev1); + LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2); + funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev2); + LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3); + funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfSim2StateDev3->setKandD((float)0, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev3); + LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4); + funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev4); + LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5); + funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfSim2StateDev5->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confSim2StateDev); + + delete c_name_of_current_func_block; +} + +/* + * creates and register another state deviation function block + */ +void create_another_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str()); + LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1); + funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev1->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev1); + LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2); + funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev2); + LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3); + funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfDif2StateDev3->setKandD((float)0, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev3); + LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4); + funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev4); + LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5); + funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfDif2StateDev5->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confDif2StateDev); + + delete c_name_of_current_func_block; +} + +void create_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str()); + LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1); + funcConfSim2StateTime1->setDomain(false, true, (float)0); + funcConfSim2StateTime1->setKandD((float)0, (float)0); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime1); + LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2); + funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime2); + LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3); + funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfSim2StateTime3->setKandD((float)0, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confSim2StateTime); + + delete c_name_of_current_func_block; +} + +void create_another_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str()); + LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1); + funcConfDif2StateTime1->setDomain(false, true, (float)0); + funcConfDif2StateTime1->setKandD((float)0, (float)1); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime1); + LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2); + funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime2); + LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3); + funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfDif2StateTime3->setKandD((float)0, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confDif2StateTime); + + delete c_name_of_current_func_block; +} + +void create_valid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str()); + LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1); + funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev1->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev1); + LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2); + funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev2); + LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3); + funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfValidStateDev3->setKandD((float)0, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev3); + LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4); + funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev4); + LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5); + funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfValidStateDev5->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confValidStateDev); + + delete c_name_of_current_func_block; +} + +void create_invalid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str()); + LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1); + funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev1->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1); + LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2); + funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2); + LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3); + funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev3->setKandD((float)0, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3); + LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4); + funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4); + LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5); + funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfInvalidStateDev5->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateDev); + + delete c_name_of_current_func_block; +} + +void create_valid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str()); + LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1); + funcConfValidStateTime1->setDomain(false, true, (float)0); + funcConfValidStateTime1->setKandD((float)0, (float)0); + confValidStateTime->addLinearFunction(funcConfValidStateTime1); + LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2); + funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10 + funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime2); + LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3); + funcConfValidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfValidStateTime3->setKandD((float)0, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confValidStateTime); + + delete c_name_of_current_func_block; +} +void create_invalid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str()); + LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1); + funcConfInvalidStateTime1->setDomain(false, true, (float)0); + funcConfInvalidStateTime1->setKandD((float)0, (float)1); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1); + LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2); + funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2); + LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3); + funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfInvalidStateTime3->setKandD((float)0, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateTime); + + delete c_name_of_current_func_block; +} + +void create_confidence_state_drift_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str()); + LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1); + functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation1->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1); + LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2); + functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2); + LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3); + functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation3->setKandD((float)0, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3); + LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4); + functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4); + LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5); + functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false); + functionConfidenceDriftDeviation5->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5); + + vec_of_linear_Function_Blocks.push_back(confStateDrifts); + + delete c_name_of_current_func_block; +} + +void create_confidence_broken_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str()); + LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1); + functionConfidenceBroken1->setDomain(false, true, (float)0); + functionConfidenceBroken1->setKandD((float)0, (float)0); + confBroken->addLinearFunction(functionConfidenceBroken1); + LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2); + functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN); + functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken2); + LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3); + functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false); + functionConfidenceBroken3->setKandD((float)0, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken3); + + vec_of_linear_Function_Blocks.push_back(confBroken); + + delete c_name_of_current_func_block; +} + +/* + * mount the different function blocks to the viability monitor agent + */ +void mount_function_blocks_to_viability_monitor() +{ + Agent* viability_Monitor; + LinearFunctionBlock* current_Linear_Function_Bock; + unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size(); + unsigned int index = 0; + + //it is assumed that the viability monitor is at the last position of the vector of agents + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + for(index = 0; index < size_of_vec_lin_func_block; index++) { + current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index]; + //it is assumed that the function blocks are added into the vector in the following sequence + switch(index) { + case 0: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock; + break; + case 1: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock; + break; + case 2: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock; + break; + case 3: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock; + break; + case 4: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock; + break; + case 5: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock; + break; + case 6: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock; + break; + case 7: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock; + break; + case 8: + viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock; + break; + case 9: + viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock; + break; + } + } +} + + +void create_all_testbenches() { + char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_testbench, TEST_BENCH.c_str()); + cout << "Creating test bench" << endl; + Testbench* tb = create_testbench(c_name_of_current_testbench); + create_and_register_all_Testbench_Configs(tb); + vec_of_test_benches.push_back(tb); + + delete c_name_of_current_testbench; +} + +void create_csvr_modules() +{ + //sets the row in which the data starts, maybe row one contains the headers + unsigned int row = 2; + char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME]; + string current_reader_path_and_file_name; + cout << "Creating CSV Reader Modules" << endl; + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6504_Y = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6504 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6504_SP = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),5,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_PI6584 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),6,row); + + vec_of_csv_readers.push_back(csvr_FC6504_Y); + vec_of_csv_readers.push_back(csvr_FC6504); + vec_of_csv_readers.push_back(csvr_FC6504_SP); + vec_of_csv_readers.push_back(csvr_PI6584); + + delete c_name_of_current_csv_module; +} + +/* + * all agents would be registered to all testbenches + */ +void register_agents_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Agent* current_ag; + unsigned int size_of_vec_agents = vec_of_Agents.size(); + unsigned int index_agents = 0; + + cout << "registering agents in testbenches" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) { + current_ag = vec_of_Agents[index_agents]; + register_agentInTestbench(current_tb, current_ag); + } + } + cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl; +} + +/* + * registering the sensors and the corresponding csv-readers in the testbenches + * it is assumed that the csv readers and the sensors are at the same index position + * in the vectors. + */ +void register_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Sensor* current_se; + unsigned int size_of_vec_sensors = vec_of_Sensors.size(); + unsigned int index_sensors = 0; + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + + if(size_of_vec_csv_reader != size_of_vec_sensors) { + cout << "Error, in sequence of data processing"; + cout << "Number of csv-readers should be equal to number of sensors" << endl; + } + else { + cout << "Registering sensors and their csv-readers in testbenches " << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) { + current_se = vec_of_Sensors[index_sensors]; + //it is assumed that the sensor and the corresponding csv-reader is stored + //at the same position in the two different vectors + current_csv_reader = vec_of_csv_readers[index_sensors]; + register_sensorInTestbench(current_tb, current_se, current_csv_reader); + } + } + cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to "; + cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl; + } +} + +void register_channels_in_testbenches() +{ + register_channels_of_sensors_in_testbenches(); + + register_channels_of_actors_in_testbenches(); +} + +void register_channels_of_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of sensors in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Sensors[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_se_channel << " channels of sensors were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; + +} + +void register_channels_of_actors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of agents in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Agents[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_ag_channel << " channels of agents were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; +} + +void run_simulation_of_all_testbenches() +{ + + string pressed_key; + Testbench* current_tb; + vector vec_tb_configs; + Testbench_Config* current_tb_config; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + unsigned int size_of_vec_test_bench_config; + unsigned int index_tb_cfg = 0; + unsigned int sim_rounds = -1; + const int start_row = 1; + if (FILE_NAME_OF_ENTIRE_DATA == "2017_01_07__05_46_fc6504.csv") { + sim_rounds = 720; + } + + cout << "Press any key to start the simulation of all testbenches." << endl; + getline(cin, pressed_key); + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + index_tb_cfg = 0; + vec_tb_configs = current_tb->get_all_registered_testbench_configs(); + size_of_vec_test_bench_config = vec_tb_configs.size(); + for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){ + current_tb_config = vec_tb_configs[index_tb_cfg]; + current_tb->set_current_tb_config_index(index_tb_cfg); + current_tb->set_CSV_Writer_parameter(); + current_tb->set_config_values_in_linear_functions(); + //have to open new file first! with the CSV-Writer, for every round > 0 + current_tb->simulate(sim_rounds); + if(index_tb_cfg < size_of_vec_test_bench_config - 1) { + current_tb->set_CSV_Reader_row(start_row); + current_tb->set_CSV_Reader_to_beginning(); + current_tb->reset_States(); + } + } + } + cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl; +} + +void close_file_pointers() +{ + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) { + current_csv_reader = vec_of_csv_readers[index_csv_reader]; + current_csv_reader->close_file(); + } +} + +void empty_static_vectors() +{ + + empty_vec_Agent(); + empty_vec_Channel_Agent(); + empty_vec_Channel_Sensor(); + empty_vec_Sensors(); + empty_vec_csv_raders(); + empty_vec_linear_func_Blocks(); + empty_vec_TestBench(); + + vec_of_Channels_for_Agents.clear(); + vec_of_Channels_for_Sensors.clear(); + vec_of_Sensors.clear(); + vec_of_csv_readers.clear(); + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_Agent() +{ + Agent* cur_Agent; + unsigned int size_of_vec_Agent = vec_of_Agents.size(); + unsigned int index_Agent; + for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){ + cur_Agent = vec_of_Agents[index_Agent]; + delete cur_Agent; + } + vec_of_Agents.clear(); +} + +void empty_vec_Channel_Agent() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){ + cur_Channel = vec_of_Channels_for_Agents[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Agents.clear(); +} + +void empty_vec_Channel_Sensor() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){ + cur_Channel = vec_of_Channels_for_Sensors[index_Channel]; + delete cur_Channel; + } + vec_of_Channels_for_Sensors.clear(); +} + +void empty_vec_Sensors() +{ + Sensor* cur_Sensor; + unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size(); + unsigned int index_Sensor; + for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){ + cur_Sensor = vec_of_Sensors[index_Sensor]; + delete cur_Sensor; + } + vec_of_Sensors.clear(); +} + +void empty_vec_csv_raders() +{ + CSVreaderModule* cur_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){ + cur_csv_reader = vec_of_csv_readers[index_csv_reader]; + delete cur_csv_reader; + } + vec_of_csv_readers.clear(); +} + +void empty_vec_linear_func_Blocks() +{ + LinearFunctionBlock* cur_lin_fun_block; + unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size(); + unsigned int index_lin_fun_block; + for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){ + cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block]; + delete cur_lin_fun_block; + } + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_TestBench() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + current_tb->free_resources(); + delete current_tb; + } + vec_of_test_benches.clear(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/main_OMV.cpp b/Version_Max_07_05_2018_CMake/src/main_OMV.cpp new file mode 100755 index 0000000..2988595 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main_OMV.cpp @@ -0,0 +1,1195 @@ +/* + * main.cpp + * + * Created on: 25.05.2018 + * Author: edwin willegger, edwin.willegger@tuwien.ac.at + * This file is used to generate output data from measurements + * from OMV for SAVE project. + * In this case the data of the 18.12.2017 is analyzed. + * Based on the implementation of Maximilian Götzinger. + */ + +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include +#include +#include +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + +#include "Testbench_Config.h" + +using namespace std; + +/********************************************************************************************************************** + ************************************************begin of global definitions of variables and constants *************** + **********************************************************************************************************************/ + +//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files. +#define SAMPLING 1 + +//global vectors for the different elements +static vector vec_of_Agents; +static vector vec_of_Sensors; +static vector vec_of_Channels_for_Sensors; +static vector vec_of_Channels_for_Agents; +static vector vec_of_linear_Function_Blocks; +static vector vec_of_test_benches; +static vector vec_of_csv_readers; + +//names of the measured data +const string FIRST_MEASURED_DATA_NAME = "PI6174"; //Input +const string SECOND_MEASURED_DATA_NAME = "PI6184"; //Input +const string THIRD_MEASURED_DATA_NAME = "FC6104"; //Output +const string FOURTH_MEASURED_DATA_NAME = "FC6104_SP"; //Input +const string FIFTH_MEASURED_DATA_NAME = "FC6104_Y"; //Input +const string SIXTH_MEASURED_DATA_NAME = "FC6114CO"; //Input +const string SEVENTH_MEASURED_DATA_NAME = "QI6154"; //Input +//viability monitor +const string VIABILITY_MONITOR = "ViabilityMonitor"; +//index number of output +const int INDEX_OUTPUT = 3; + +//name for the channels of the sensors and agents +const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)"; +const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FIFTH_MEASURED_CHANNEL_SENSOR_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SIXTH_MEASURED_CHANNEL_SENSOR_NAME = SIXTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SEVENTH_MEASURED_CHANNEL_SENSOR_NAME = SEVENTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)"; +const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FIFTH_MEASURED_CHANNEL_AGENT_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SIXTH_MEASURED_CHANNEL_AGENT_NAME = SIXTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SEVENTH_MEASURED_CHANNEL_AGENT_NAME = SEVENTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; + +#define TRANSFER_RATE_CHANNEL_SENSOR 0 +#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH + + +////////////////////////////////////////////// +/* +//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery. + inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx + outer_bound_xxx = / | \ + / | \ + 0=__________/ | \ = outer_bound_xxxx ______ = 0 +-------------------------------------------------------------------------- +*/ + +//parameters of boundary for similar function +#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06, +#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent + +//same way as above but shows drift. +#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3 +#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF + +//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu +//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat. +#define BOUND_BROKEN 2 + +//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery. +//history of the data depends of it, and should change, if it changes. +#define LENGTH 10 + + +//definitions for the testbench +const string TEST_BENCH = "testbench"; + +//defintions for the csv-reader-modules +const string APPENDIX_CSV_MODULES = " CSV-Reader"; +const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FIFTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SIXTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SEVENTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; + + +//to switch between different file configurations change the +//DEFINES in file_util.h + +/********************************************************************************************************************** + ************************************************end of global definitions of variables and constants ***************** + **********************************************************************************************************************/ + +/********************************************************************************************************************** + ************************************************begin of function prototypes ***************************************** + **********************************************************************************************************************/ +void create_and_register_all_Testbench_Configs(Testbench* current_tb); + +void create_and_register_All_Agents(); +void set_working_cycle_of_All_Agents(); + +void create_and_register_All_Sensors(); +void set_working_cycle_of_All_Sensors(); + +void create_and_register_channels(); +void create_and_register_channels_for_sensors(); +void create_and_register_channels_for_agents(); + +void mount_sensors_in_agents(); +void mount_agents_in_agents(); + +void register_data_agents_in_agent_state_Handler(); + +void create_linear_function_blocks(); +void create_same_state_deviation_function_block(); +void create_another_state_deviation_function_block(); +void create_state_time_function_block(); +void create_another_state_time_function_block(); +void create_valid_state_deviation_function_block(); +void create_invalid_state_deviation_function_block(); +void create_valid_state_time_function_block(); +void create_invalid_state_time_function_block(); +void create_confidence_state_drift_function_block(); +void create_confidence_broken_function_block(); +void mount_function_blocks_to_viability_monitor(); + +void create_all_testbenches(); + +void create_csvr_modules(); + +void register_agents_in_testbenches(); + +void register_sensors_in_testbenches(); + +void register_channels_in_testbenches(); +void register_channels_of_sensors_in_testbenches(); +void register_channels_of_actors_in_testbenches(); + +void set_config_values_in_linear_functions(Testbench* current_tb); +void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block); +void set_parameters_LinearFunction(vector vec_Lin_Func); + +void set_CSV_Writer_parameter(Testbench* current_tb); + +void run_simulation_of_all_testbenches(); + +void close_file_pointers(); + +void empty_static_vectors(); +void empty_vec_Agent(); +void empty_vec_Channel_Agent(); +void empty_vec_Channel_Sensor(); +void empty_vec_Sensors(); +void empty_vec_csv_raders(); +void empty_vec_linear_func_Blocks(); +void empty_vec_TestBench(); + + +/********************************************************************************************************************** + ************************************************end of function prototypes ******************************************* + **********************************************************************************************************************/ + +int main() +{ + cout << "This program processes test data from OMV Steam Cracker furnaces." << endl; + + create_and_register_All_Agents(); + set_working_cycle_of_All_Agents(); + + + create_and_register_All_Sensors(); + set_working_cycle_of_All_Sensors(); + + create_and_register_channels(); + + mount_sensors_in_agents(); + + mount_agents_in_agents(); + + register_data_agents_in_agent_state_Handler(); + + create_linear_function_blocks(); + + mount_function_blocks_to_viability_monitor(); + + create_all_testbenches(); + + create_csvr_modules(); + + register_agents_in_testbenches(); + + register_sensors_in_testbenches(); + + register_channels_in_testbenches(); + + + + run_simulation_of_all_testbenches(); + + //close_file_pointers(); + //TODO memory free of all objects. + empty_static_vectors(); + + cout << "Program finished successfully" << endl; + return 0; +} + +void create_and_register_all_Testbench_Configs(Testbench* current_tb) +{ + + One_Config_t one; + one.bound_broken = 2; + one.inner_bound_sim_dif = 0.02; + one.outter_bound_sim_dif = 0.15; + one.inner_bound_drift = 3 * one.outter_bound_sim_dif; + one.inner_bound_drift = one.outter_bound_sim_dif; + one.length = 10; + Testbench_Config* cfg = new Testbench_Config(); + Testbench_Config* cfg2 = new Testbench_Config(one); + Testbench_Config* cfg3 = new Testbench_Config(); + Testbench_Config* cfg4 = new Testbench_Config(); + cfg->print(); + cfg2->print(); + cfg3->print(); + cfg4->print(); + current_tb->register_testbench_config(cfg); + current_tb->register_testbench_config(cfg2); + current_tb->register_testbench_config(cfg3); + current_tb->register_testbench_config(cfg4); +} + + + +/* + * creates all the agents used in the measurement + * and stores them into the global vector + */ +void create_and_register_All_Agents() +{ + cout << "Creating Agents" << endl; + char* c_name_of_current_agent = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str()); + Agent* a_PI6174 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str()); + Agent* a_PI6184 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6104 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6104_SP = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FIFTH_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6104_Y = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SIXTH_MEASURED_DATA_NAME.c_str()); + Agent* a_FC6114CO = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SEVENTH_MEASURED_DATA_NAME.c_str()); + Agent* a_QI6154 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str()); + Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent); + vec_of_Agents.push_back(a_PI6174); + vec_of_Agents.push_back(a_PI6184); + vec_of_Agents.push_back(a_FC6104); + vec_of_Agents.push_back(a_FC6104_SP); + vec_of_Agents.push_back(a_FC6104_Y); + vec_of_Agents.push_back(a_FC6114CO); + vec_of_Agents.push_back(a_QI6154); + vec_of_Agents.push_back(a_viabilityMonitor); + cout << vec_of_Agents.size() << " agents were created" << endl; + delete c_name_of_current_agent; +} + +/* + * the working_cycle for all registered agents is set + */ +void set_working_cycle_of_All_Agents() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Agents = 0; + unsigned int index = 0; + Agent* current_Agent; + size_of_vec_of_Agents = vec_of_Agents.size(); + for(index = 0; index < size_of_vec_of_Agents; index++) { + current_Agent = vec_of_Agents[index]; + setWorkingCycleOfAgent(current_Agent, working_Cyle); + } +} + +/* + * all necessary sensors are created and registered + */ +void create_and_register_All_Sensors() +{ + cout << "Creating Sensors" << endl; + char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str()); + Sensor* s_PI6174 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str()); + Sensor* s_PI6184 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6104 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6104_SP = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FIFTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6104_Y = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SIXTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_FC6114CO = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SEVENTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_QI6154 = create_sensor(c_name_of_current_sensor); + vec_of_Sensors.push_back(s_PI6174); + vec_of_Sensors.push_back(s_PI6184); + vec_of_Sensors.push_back(s_FC6104); + vec_of_Sensors.push_back(s_FC6104_SP); + vec_of_Sensors.push_back(s_FC6104_Y); + vec_of_Sensors.push_back(s_FC6114CO); + vec_of_Sensors.push_back(s_QI6154); + cout << vec_of_Sensors.size() << " sensors were created." << endl; + delete c_name_of_current_sensor; +} + +/* + * working cycle of all registered sensors is set + */ +void set_working_cycle_of_All_Sensors() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Sensors = 0; + unsigned int index = 0; + Sensor* current_Sensor; + + size_of_vec_of_Sensors = vec_of_Sensors.size(); + for(index = 0; index < size_of_vec_of_Sensors; index++) { + current_Sensor = vec_of_Sensors[index]; + setWorkingCycleOfSensor(current_Sensor, working_Cyle); + } +} + +/* + * creating and registering all channels + */ +void create_and_register_channels() +{ + create_and_register_channels_for_sensors(); + create_and_register_channels_for_agents(); +} + +/* + * creating and registering the channels for the sensors. + */ +void create_and_register_channels_for_sensors() +{ + cout << "Creating and registering channels for sensors" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_PI6174 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_PI6184 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6104 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6104_SP = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6104_Y = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SIXTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_FC6114CO = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SEVENTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_QI6154 = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Sensors.push_back(c_sa_PI6174); + vec_of_Channels_for_Sensors.push_back(c_sa_PI6184); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6104); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6104_SP); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6104_Y); + vec_of_Channels_for_Sensors.push_back(c_sa_FC6114CO); + vec_of_Channels_for_Sensors.push_back(c_sa_QI6154); + cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl; + + delete c_name_of_current_channel; +} + +/* + * creating and registering the channels for the agents + */ +void create_and_register_channels_for_agents() +{ + cout << "Creating and registering channels for agents" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_PI6174 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_PI6184 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6104 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6104_SP = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6104_Y = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SIXTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_FC6114CO = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SEVENTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_QI6154 = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Agents.push_back(c_aa_PI6174); + vec_of_Channels_for_Agents.push_back(c_aa_PI6184); + vec_of_Channels_for_Agents.push_back(c_aa_FC6104); + vec_of_Channels_for_Agents.push_back(c_aa_FC6104_SP); + vec_of_Channels_for_Agents.push_back(c_aa_FC6104_Y); + vec_of_Channels_for_Agents.push_back(c_aa_FC6114CO); + vec_of_Channels_for_Agents.push_back(c_aa_QI6154); + + cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl; + + delete c_name_of_current_channel; +} + +void mount_sensors_in_agents() +{ + Agent* current_agent; + Sensor* current_sensor; + Channel* current_sensor_channel; + unsigned int size_of_vec_sensor = 0; + unsigned int index = 0; + + size_of_vec_sensor = vec_of_Sensors.size(); + cout << "mounting sensors in agents." << endl; + //it is assumed that the corresponding sensors and agents and channels are always at the same + //position in the different vectors, if not then you have to add an search algorithm for it. + for(index = 0; index < size_of_vec_sensor; index++) + { + current_agent = vec_of_Agents[index]; + current_sensor = vec_of_Sensors[index]; + current_sensor_channel = vec_of_Channels_for_Sensors[index]; + mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel); + } + cout << size_of_vec_sensor << " sensors in agents were mounted" << endl; +} + +void mount_agents_in_agents() +{ + Agent* current_agent; + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_agents = 0; + unsigned int index = 0; + + size_of_vec_agents = vec_of_Agents.size(); + //it is assumed that the viability agent is at the last position in the vector + viability_Monitor = vec_of_Agents[size_of_vec_agents-1]; + //all agents and channels are registered to the viabilityMonitor agent + //so you have to subtract the viabilityMonitor from the number of elements to register + //it is assumed that all the corresponding channels and agents are placed at the same index + for(index = 0; index < size_of_vec_agents -1; index++) + { + current_agent = vec_of_Agents[index]; + current_agent_channel = vec_of_Channels_for_Agents[index]; + //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself. + if(current_agent != viability_Monitor) { + mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel); + } + } + cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl; +} + +/* + * registers the channels for the data agents to the viability monitor + */ +void register_data_agents_in_agent_state_Handler() + +{ + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_channel_agents = 0; + unsigned int index = 0; + + size_of_vec_channel_agents = vec_of_Channels_for_Agents.size(); + //get the agent for the viabilityMonitor, it is assumed that it is at the last position + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + //register all the channels to the viability monitor + for(index = 0; index < size_of_vec_channel_agents; index++) { + current_agent_channel = vec_of_Channels_for_Agents[index]; + if(index != INDEX_OUTPUT) { + registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel); + } + else{ + registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel); + } + } +} + +/* + * creates and register all the different linear function blocks + */ +void create_linear_function_blocks() +{ + //don't change the sequence, because later it is assumed that the functions are + //registered int the vector in this sequence + //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor + create_same_state_deviation_function_block(); + create_another_state_deviation_function_block(); + create_state_time_function_block(); + create_another_state_time_function_block(); + create_valid_state_deviation_function_block(); + create_invalid_state_deviation_function_block(); + create_valid_state_time_function_block(); + create_invalid_state_time_function_block(); + create_confidence_state_drift_function_block(); + create_confidence_broken_function_block(); +} + +/* + * creates and register the linear function block for same state deviation + */ +void create_same_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str()); + LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1); + funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev1->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev1); + LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2); + funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev2); + LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3); + funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfSim2StateDev3->setKandD((float)0, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev3); + LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4); + funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev4); + LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5); + funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfSim2StateDev5->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confSim2StateDev); + + delete c_name_of_current_func_block; +} + +/* + * creates and register another state deviation function block + */ +void create_another_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str()); + LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1); + funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev1->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev1); + LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2); + funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev2); + LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3); + funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfDif2StateDev3->setKandD((float)0, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev3); + LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4); + funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev4); + LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5); + funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfDif2StateDev5->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confDif2StateDev); + + delete c_name_of_current_func_block; +} + +void create_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str()); + LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1); + funcConfSim2StateTime1->setDomain(false, true, (float)0); + funcConfSim2StateTime1->setKandD((float)0, (float)0); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime1); + LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2); + funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime2); + LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3); + funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfSim2StateTime3->setKandD((float)0, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confSim2StateTime); + + delete c_name_of_current_func_block; +} + +void create_another_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str()); + LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1); + funcConfDif2StateTime1->setDomain(false, true, (float)0); + funcConfDif2StateTime1->setKandD((float)0, (float)1); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime1); + LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2); + funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime2); + LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3); + funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfDif2StateTime3->setKandD((float)0, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confDif2StateTime); + + delete c_name_of_current_func_block; +} + +void create_valid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str()); + LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1); + funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev1->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev1); + LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2); + funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev2); + LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3); + funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfValidStateDev3->setKandD((float)0, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev3); + LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4); + funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev4); + LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5); + funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfValidStateDev5->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confValidStateDev); + + delete c_name_of_current_func_block; +} + +void create_invalid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str()); + LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1); + funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev1->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1); + LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2); + funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2); + LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3); + funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev3->setKandD((float)0, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3); + LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4); + funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4); + LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5); + funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfInvalidStateDev5->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateDev); + + delete c_name_of_current_func_block; +} + +void create_valid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str()); + LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1); + funcConfValidStateTime1->setDomain(false, true, (float)0); + funcConfValidStateTime1->setKandD((float)0, (float)0); + confValidStateTime->addLinearFunction(funcConfValidStateTime1); + LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2); + funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10 + funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime2); + LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3); + funcConfValidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfValidStateTime3->setKandD((float)0, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confValidStateTime); + + delete c_name_of_current_func_block; +} +void create_invalid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str()); + LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1); + funcConfInvalidStateTime1->setDomain(false, true, (float)0); + funcConfInvalidStateTime1->setKandD((float)0, (float)1); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1); + LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2); + funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2); + LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3); + funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfInvalidStateTime3->setKandD((float)0, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateTime); + + delete c_name_of_current_func_block; +} + +void create_confidence_state_drift_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str()); + LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1); + functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation1->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1); + LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2); + functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2); + LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3); + functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation3->setKandD((float)0, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3); + LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4); + functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4); + LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5); + functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false); + functionConfidenceDriftDeviation5->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5); + + vec_of_linear_Function_Blocks.push_back(confStateDrifts); + + delete c_name_of_current_func_block; +} + +void create_confidence_broken_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str()); + LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1); + functionConfidenceBroken1->setDomain(false, true, (float)0); + functionConfidenceBroken1->setKandD((float)0, (float)0); + confBroken->addLinearFunction(functionConfidenceBroken1); + LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2); + functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN); + functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken2); + LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3); + functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false); + functionConfidenceBroken3->setKandD((float)0, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken3); + + vec_of_linear_Function_Blocks.push_back(confBroken); + + delete c_name_of_current_func_block; +} + +/* + * mount the different function blocks to the viability monitor agent + */ +void mount_function_blocks_to_viability_monitor() +{ + Agent* viability_Monitor; + LinearFunctionBlock* current_Linear_Function_Bock; + unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size(); + unsigned int index = 0; + + //it is assumed that the viability monitor is at the last position of the vector of agents + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + for(index = 0; index < size_of_vec_lin_func_block; index++) { + current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index]; + //it is assumed that the function blocks are added into the vector in the following sequence + switch(index) { + case 0: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock; + break; + case 1: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock; + break; + case 2: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock; + break; + case 3: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock; + break; + case 4: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock; + break; + case 5: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock; + break; + case 6: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock; + break; + case 7: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock; + break; + case 8: + viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock; + break; + case 9: + viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock; + break; + } + } +} + + +void create_all_testbenches() { + char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_testbench, TEST_BENCH.c_str()); + cout << "Creating test bench" << endl; + Testbench* tb = create_testbench(c_name_of_current_testbench); + create_and_register_all_Testbench_Configs(tb); + vec_of_test_benches.push_back(tb); + + delete c_name_of_current_testbench; +} + +void create_csvr_modules() +{ + //sets the row in which the data starts, maybe row one contains the headers + unsigned int row = 2; + char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME]; + string current_reader_path_and_file_name; + cout << "Creating CSV Reader Modules" << endl; + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_PI6174 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_PI6184 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6104 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6104_SP = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),5,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIFTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6104_Y = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),6,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SIXTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_FC6114CO = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),7,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SEVENTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_QI6154 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),8,row); + + vec_of_csv_readers.push_back(csvr_PI6174); + vec_of_csv_readers.push_back(csvr_PI6184); + vec_of_csv_readers.push_back(csvr_FC6104); + vec_of_csv_readers.push_back(csvr_FC6104_SP); + vec_of_csv_readers.push_back(csvr_FC6104_Y); + vec_of_csv_readers.push_back(csvr_FC6114CO); + vec_of_csv_readers.push_back(csvr_QI6154); + + delete c_name_of_current_csv_module; +} + +/* + * all agents would be registered to all testbenches + */ +void register_agents_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Agent* current_ag; + unsigned int size_of_vec_agents = vec_of_Agents.size(); + unsigned int index_agents = 0; + + cout << "registering agents in testbenches" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) { + current_ag = vec_of_Agents[index_agents]; + register_agentInTestbench(current_tb, current_ag); + } + } + cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl; +} + +/* + * registering the sensors and the corresponding csv-readers in the testbenches + * it is assumed that the csv readers and the sensors are at the same index position + * in the vectors. + */ +void register_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Sensor* current_se; + unsigned int size_of_vec_sensors = vec_of_Sensors.size(); + unsigned int index_sensors = 0; + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + + if(size_of_vec_csv_reader != size_of_vec_sensors) { + cout << "Error, in sequence of data processing"; + cout << "Number of csv-readers should be equal to number of sensors" << endl; + } + else { + cout << "Registering sensors and their csv-readers in testbenches " << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) { + current_se = vec_of_Sensors[index_sensors]; + //it is assumed that the sensor and the corresponding csv-reader is stored + //at the same position in the two different vectors + current_csv_reader = vec_of_csv_readers[index_sensors]; + register_sensorInTestbench(current_tb, current_se, current_csv_reader); + } + } + cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to "; + cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl; + } +} + +void register_channels_in_testbenches() +{ + register_channels_of_sensors_in_testbenches(); + + register_channels_of_actors_in_testbenches(); +} + +void register_channels_of_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of sensors in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Sensors[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_se_channel << " channels of sensors were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; + +} + +void register_channels_of_actors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of agents in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Agents[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_ag_channel << " channels of agents were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; +} + +void run_simulation_of_all_testbenches() +{ + + string pressed_key; + Testbench* current_tb; + vector vec_tb_configs; + Testbench_Config* current_tb_config; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + unsigned int size_of_vec_test_bench_config; + unsigned int index_tb_cfg = 0; + unsigned int sim_rounds = 131; + const int start_row = 1; + + cout << "Press any key to start the simulation of all testbenches." << endl; + getline(cin, pressed_key); + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + index_tb_cfg = 0; + vec_tb_configs = current_tb->get_all_registered_testbench_configs(); + size_of_vec_test_bench_config = vec_tb_configs.size(); + for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){ + current_tb_config = vec_tb_configs[index_tb_cfg]; + current_tb->set_current_tb_config_index(index_tb_cfg); + current_tb->set_CSV_Writer_parameter(); + current_tb->set_config_values_in_linear_functions(); + //have to open new file first! with the CSV-Writer, for every round > 0 + current_tb->simulate(sim_rounds); + if(index_tb_cfg < size_of_vec_test_bench_config - 1) { + current_tb->set_CSV_Reader_row(start_row); + current_tb->set_CSV_Reader_to_beginning(); + current_tb->reset_States(); + } + } + } + cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl; +} + +void close_file_pointers() +{ + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) { + current_csv_reader = vec_of_csv_readers[index_csv_reader]; + current_csv_reader->close_file(); + } +} + +void empty_static_vectors() +{ + + empty_vec_Agent(); + empty_vec_Channel_Agent(); + empty_vec_Channel_Sensor(); + empty_vec_Sensors(); + empty_vec_csv_raders(); + empty_vec_linear_func_Blocks(); + empty_vec_TestBench(); + + vec_of_Channels_for_Agents.clear(); + vec_of_Channels_for_Sensors.clear(); + vec_of_Sensors.clear(); + vec_of_csv_readers.clear(); + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_Agent() +{ + Agent* cur_Agent; + unsigned int size_of_vec_Agent = vec_of_Agents.size(); + unsigned int index_Agent; + for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){ + cur_Agent = vec_of_Agents[index_Agent]; + delete cur_Agent; + } + vec_of_Agents.clear(); +} + +void empty_vec_Channel_Agent() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){ + cur_Channel = vec_of_Channels_for_Agents[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Agents.clear(); +} + +void empty_vec_Channel_Sensor() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){ + cur_Channel = vec_of_Channels_for_Sensors[index_Channel]; + delete cur_Channel; + } + vec_of_Channels_for_Sensors.clear(); +} + +void empty_vec_Sensors() +{ + Sensor* cur_Sensor; + unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size(); + unsigned int index_Sensor; + for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){ + cur_Sensor = vec_of_Sensors[index_Sensor]; + delete cur_Sensor; + } + vec_of_Sensors.clear(); +} + +void empty_vec_csv_raders() +{ + CSVreaderModule* cur_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){ + cur_csv_reader = vec_of_csv_readers[index_csv_reader]; + delete cur_csv_reader; + } + vec_of_csv_readers.clear(); +} + +void empty_vec_linear_func_Blocks() +{ + LinearFunctionBlock* cur_lin_fun_block; + unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size(); + unsigned int index_lin_fun_block; + for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){ + cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block]; + delete cur_lin_fun_block; + } + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_TestBench() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + current_tb->free_resources(); + delete current_tb; + } + vec_of_test_benches.clear(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/main_OPEL_GA_Data.cpp b/Version_Max_07_05_2018_CMake/src/main_OPEL_GA_Data.cpp new file mode 100755 index 0000000..1919c94 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main_OPEL_GA_Data.cpp @@ -0,0 +1,1184 @@ +/* + * main.cpp + * + * Created on: 25.05.2018 + * Author: edwin willegger, edwin.willegger@tuwien.ac.at + * This file is used to generate output data from measurements + * from Opel for SAVE project. + * In this case the data of the entire time frame is analysed. + * Based on the implementation of Maximilian Götzinger. + */ + +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include +#include +#include +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + +#include "Testbench_Config.h" + +using namespace std; + + +/* to switch between different file configurations change the + * selected DEFINE in file_util.h + * because the case of data analysis is selected in file_util.h + * current available, Wr. Neustsadt, OMV, Opel + * + * One run for the entire Opel data set needs around 5 minutes. + */ + +/********************************************************************************************************************** + ************************************************begin of global definitions of variables and constants *************** + **********************************************************************************************************************/ + +//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files. +#define SAMPLING 1 + +//global vectors for the different elements +static vector vec_of_Agents; +static vector vec_of_Sensors; +static vector vec_of_Channels_for_Sensors; +static vector vec_of_Channels_for_Agents; +static vector vec_of_linear_Function_Blocks; +static vector vec_of_test_benches; +static vector vec_of_csv_readers; + +/* + * it is not possible to have inputs and outputs, because all data are mesaruements at the end + * of the conrod line. + * Workaround: All parameters are as inputs and outputs used. + */ +//names of the measured data +const string FIRST_MEASURED_DATA_NAME = "GA_open_laengs"; //Input and Output +const string SECOND_MEASURED_DATA_NAME = "GA_oben_quer"; //Input and Output +const string THIRD_MEASURED_DATA_NAME = "GA_unten_laengs"; //Input and Output +const string FOURTH_MEASURED_DATA_NAME = "GA_unten_quer"; //Input and Output +//viability monitor +const string VIABILITY_MONITOR = "ViabilityMonitor"; +//index number of output, only used for data aquisition from OMV +//better implementation a const list, with the index of all outputs +//and another list for all input indices. +//const int INDEX_OUTPUT = 3; + +//name for the channels of the sensors and agents +const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)"; +const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)"; +const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; + +#define TRANSFER_RATE_CHANNEL_SENSOR 0 +#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH + + +////////////////////////////////////////////// +/* +//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery. + inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx + outer_bound_xxx = / | \ + / | \ + 0=__________/ | \ = outer_bound_xxxx ______ = 0 +-------------------------------------------------------------------------- +*/ + +//parameters of boundary for similar function +#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06, +#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent + +//same way as above but shows drift. +#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3 +#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF + +//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu +//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat. +#define BOUND_BROKEN 2 + +//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery. +//history of the data depends of it, and should change, if it changes. +#define LENGTH 2//10 + + +//definitions for the testbench +const string TEST_BENCH = "testbench"; + +//defintions for the csv-reader-modules +//every agent have a own-csv-reader +const string APPENDIX_CSV_MODULES = " CSV-Reader"; +const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; + + +/********************************************************************************************************************** + ************************************************end of global definitions of variables and constants ***************** + **********************************************************************************************************************/ + +/********************************************************************************************************************** + ************************************************begin of function prototypes ***************************************** + **********************************************************************************************************************/ +void create_and_register_all_Testbench_Configs(Testbench* current_tb); + +void create_and_register_All_Agents(); +void set_working_cycle_of_All_Agents(); + +void create_and_register_All_Sensors(); +void set_working_cycle_of_All_Sensors(); + +void create_and_register_channels(); +void create_and_register_channels_for_sensors(); +void create_and_register_channels_for_agents(); + +void mount_sensors_in_agents(); +void mount_agents_in_agents(); + +void register_data_agents_in_agent_state_Handler(); + +void create_linear_function_blocks(); +void create_same_state_deviation_function_block(); +void create_another_state_deviation_function_block(); +void create_state_time_function_block(); +void create_another_state_time_function_block(); +void create_valid_state_deviation_function_block(); +void create_invalid_state_deviation_function_block(); +void create_valid_state_time_function_block(); +void create_invalid_state_time_function_block(); +void create_confidence_state_drift_function_block(); +void create_confidence_broken_function_block(); +void mount_function_blocks_to_viability_monitor(); + +void create_all_testbenches(); + +void create_csvr_modules(); + +void register_agents_in_testbenches(); + +void register_sensors_in_testbenches(); + +void register_channels_in_testbenches(); +void register_channels_of_sensors_in_testbenches(); +void register_channels_of_actors_in_testbenches(); + +void set_config_values_in_linear_functions(Testbench* current_tb); +void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block); +void set_parameters_LinearFunction(vector vec_Lin_Func); + +void set_CSV_Writer_parameter(Testbench* current_tb); + +void run_simulation_of_all_testbenches(); + +void close_file_pointers(); + +void empty_static_vectors(); +void empty_vec_Agent(); +void empty_vec_Channel_Agent(); +void empty_vec_Channel_Sensor(); +void empty_vec_Sensors(); +void empty_vec_csv_raders(); +void empty_vec_linear_func_Blocks(); +void empty_vec_TestBench(); + + +/********************************************************************************************************************** + ************************************************end of function prototypes ******************************************* + **********************************************************************************************************************/ + +int main() +{ + cout << "This program processes test data from Opel conrod production." << endl; + + create_and_register_All_Agents(); + set_working_cycle_of_All_Agents(); + + + create_and_register_All_Sensors(); + set_working_cycle_of_All_Sensors(); + + create_and_register_channels(); + + mount_sensors_in_agents(); + + mount_agents_in_agents(); + + register_data_agents_in_agent_state_Handler(); + + create_linear_function_blocks(); + + mount_function_blocks_to_viability_monitor(); + + create_all_testbenches(); + + create_csvr_modules(); + + register_agents_in_testbenches(); + + register_sensors_in_testbenches(); + + register_channels_in_testbenches(); + + + + run_simulation_of_all_testbenches(); + + //close_file_pointers(); + //TODO memory free of all objects. + empty_static_vectors(); + + cout << "Program finished successfully" << endl; + return 0; +} + +void create_and_register_all_Testbench_Configs(Testbench* current_tb) +{ + + One_Config_t configuration; + //setting of parameters, which will the same for all configurations + configuration.bound_broken = 2; + configuration.length = 1;//10; + + //the individual settings are set before a new Testbench_Config is created. + configuration.inner_bound_sim_dif = 1 * 0.000120; + configuration.outter_bound_sim_dif = 2 * configuration.inner_bound_sim_dif; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg = new Testbench_Config(configuration); + + /*configuration.inner_bound_sim_dif = 0.0005; + configuration.outter_bound_sim_dif = 0.002; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg2 = new Testbench_Config(configuration); + + configuration.inner_bound_sim_dif = 0.002; + configuration.outter_bound_sim_dif = 0.01; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg3 = new Testbench_Config(configuration); + + configuration.inner_bound_sim_dif = 0.005; + configuration.outter_bound_sim_dif = 0.01; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg4 = new Testbench_Config(configuration); + cfg->print(); + cfg2->print(); + cfg3->print(); + cfg4->print(); */ + current_tb->register_testbench_config(cfg); /* + current_tb->register_testbench_config(cfg2); + current_tb->register_testbench_config(cfg3); + current_tb->register_testbench_config(cfg4); */ +} + + + +/* + * creates all the agents used in the measurement + * and stores them into the global vector + */ +void create_and_register_All_Agents() +{ + cout << "Creating Agents" << endl; + char* c_name_of_current_agent = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_oben_laengs = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_oben_quer = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_unten_laengs = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_unten_quer = create_agent(c_name_of_current_agent); + + strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str()); + Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent); + vec_of_Agents.push_back(a_GA_oben_laengs); + vec_of_Agents.push_back(a_GA_oben_quer); + vec_of_Agents.push_back(a_GA_unten_laengs); + vec_of_Agents.push_back(a_GA_unten_quer); + vec_of_Agents.push_back(a_viabilityMonitor); + cout << vec_of_Agents.size() << " agents were created" << endl; + delete c_name_of_current_agent; +} + +/* + * the working_cycle for all registered agents is set + */ +void set_working_cycle_of_All_Agents() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Agents = 0; + unsigned int index = 0; + Agent* current_Agent; + size_of_vec_of_Agents = vec_of_Agents.size(); + for(index = 0; index < size_of_vec_of_Agents; index++) { + current_Agent = vec_of_Agents[index]; + setWorkingCycleOfAgent(current_Agent, working_Cyle); + } +} + +/* + * all necessary sensors are created and registered + */ +void create_and_register_All_Sensors() +{ + cout << "Creating Sensors" << endl; + char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_oben_laengs = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_oben_quer = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_unten_laengs = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_unten_quer = create_sensor(c_name_of_current_sensor); + + vec_of_Sensors.push_back(s_GA_oben_laengs); + vec_of_Sensors.push_back(s_GA_oben_quer); + vec_of_Sensors.push_back(s_GA_unten_laengs); + vec_of_Sensors.push_back(s_GA_unten_quer); + + cout << vec_of_Sensors.size() << " sensors were created." << endl; + delete c_name_of_current_sensor; +} + +/* + * working cycle of all registered sensors is set + */ +void set_working_cycle_of_All_Sensors() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Sensors = 0; + unsigned int index = 0; + Sensor* current_Sensor; + + size_of_vec_of_Sensors = vec_of_Sensors.size(); + for(index = 0; index < size_of_vec_of_Sensors; index++) { + current_Sensor = vec_of_Sensors[index]; + setWorkingCycleOfSensor(current_Sensor, working_Cyle); + } +} + +/* + * creating and registering all channels + */ +void create_and_register_channels() +{ + create_and_register_channels_for_sensors(); + create_and_register_channels_for_agents(); +} + +/* + * creating and registering the channels for the sensors. + */ +void create_and_register_channels_for_sensors() +{ + cout << "Creating and registering channels for sensors" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_oben_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_oben_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_unten_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_unten_quer = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Sensors.push_back(c_sa_GA_oben_laengs); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_oben_quer); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_unten_laengs); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_unten_quer); + + cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl; + + delete c_name_of_current_channel; +} + +/* + * creating and registering the channels for the agents + */ +void create_and_register_channels_for_agents() +{ + cout << "Creating and registering channels for agents" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_oben_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_oben_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_unten_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_unten_quer = create_channel(c_name_of_current_channel, 0); + + + vec_of_Channels_for_Agents.push_back(c_aa_GA_oben_laengs); + vec_of_Channels_for_Agents.push_back(c_aa_GA_oben_quer); + vec_of_Channels_for_Agents.push_back(c_aa_GA_unten_laengs); + vec_of_Channels_for_Agents.push_back(c_aa_GA_unten_quer); + + + cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl; + + delete c_name_of_current_channel; +} + +void mount_sensors_in_agents() +{ + Agent* current_agent; + Sensor* current_sensor; + Channel* current_sensor_channel; + unsigned int size_of_vec_sensor = 0; + unsigned int index = 0; + + size_of_vec_sensor = vec_of_Sensors.size(); + cout << "mounting sensors in agents." << endl; + //it is assumed that the corresponding sensors and agents and channels are always at the same + //position in the different vectors, if not then you have to add an search algorithm for it. + for(index = 0; index < size_of_vec_sensor; index++) + { + current_agent = vec_of_Agents[index]; + current_sensor = vec_of_Sensors[index]; + current_sensor_channel = vec_of_Channels_for_Sensors[index]; + mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel); + } + cout << size_of_vec_sensor << " sensors in agents were mounted" << endl; +} + +void mount_agents_in_agents() +{ + Agent* current_agent; + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_agents = 0; + unsigned int index = 0; + + size_of_vec_agents = vec_of_Agents.size(); + //it is assumed that the viability agent is at the last postition in the vector + viability_Monitor = vec_of_Agents[size_of_vec_agents-1]; + //all agents and channels are registered to the viabilityMonitor agent + //so you have to subtract the viabilityMonitor from the number of elements to register + //it is assumed that all the corresponding channels and agents are placed at the same index + for(index = 0; index < size_of_vec_agents -1; index++) + { + current_agent = vec_of_Agents[index]; + current_agent_channel = vec_of_Channels_for_Agents[index]; + //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself. + if(current_agent != viability_Monitor) { + mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel); + } + } + cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl; +} + +/* + * registers the channels for the data agents to the viability monitor + */ +void register_data_agents_in_agent_state_Handler() + +{ + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_channel_agents = 0; + unsigned int index = 0; + + size_of_vec_channel_agents = vec_of_Channels_for_Agents.size(); + //get the agent for the viabilityMonitor, it is assumed that it is at the last position + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + //register all the channels to the viability monitor + for(index = 0; index < size_of_vec_channel_agents; index++) { + current_agent_channel = vec_of_Channels_for_Agents[index]; + registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel); + registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel); + } +} + +/* + * creates and register all the different linear function blocks + */ +void create_linear_function_blocks() +{ + //don't change the sequence, because later it is assumed that the functions are + //registered int the vector in this sequence + //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor + create_same_state_deviation_function_block(); + create_another_state_deviation_function_block(); + create_state_time_function_block(); + create_another_state_time_function_block(); + create_valid_state_deviation_function_block(); + create_invalid_state_deviation_function_block(); + create_valid_state_time_function_block(); + create_invalid_state_time_function_block(); + create_confidence_state_drift_function_block(); + create_confidence_broken_function_block(); +} + +/* + * creates and register the linear function block for same state deviation + */ +void create_same_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str()); + LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1); + funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev1->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev1); + LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2); + funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev2); + LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3); + funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfSim2StateDev3->setKandD((float)0, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev3); + LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4); + funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev4); + LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5); + funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfSim2StateDev5->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confSim2StateDev); + + delete c_name_of_current_func_block; +} + +/* + * creates and register another state deviation function block + */ +void create_another_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str()); + LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1); + funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev1->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev1); + LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2); + funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev2); + LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3); + funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfDif2StateDev3->setKandD((float)0, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev3); + LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4); + funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev4); + LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5); + funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfDif2StateDev5->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confDif2StateDev); + + delete c_name_of_current_func_block; +} + +void create_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str()); + LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1); + funcConfSim2StateTime1->setDomain(false, true, (float)0); + funcConfSim2StateTime1->setKandD((float)0, (float)0); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime1); + LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2); + funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime2); + LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3); + funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfSim2StateTime3->setKandD((float)0, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confSim2StateTime); + + delete c_name_of_current_func_block; +} + +void create_another_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str()); + LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1); + funcConfDif2StateTime1->setDomain(false, true, (float)0); + funcConfDif2StateTime1->setKandD((float)0, (float)1); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime1); + LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2); + funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime2); + LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3); + funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfDif2StateTime3->setKandD((float)0, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confDif2StateTime); + + delete c_name_of_current_func_block; +} + +void create_valid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str()); + LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1); + funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev1->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev1); + LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2); + funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev2); + LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3); + funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfValidStateDev3->setKandD((float)0, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev3); + LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4); + funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev4); + LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5); + funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfValidStateDev5->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confValidStateDev); + + delete c_name_of_current_func_block; +} + +void create_invalid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str()); + LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1); + funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev1->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1); + LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2); + funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2); + LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3); + funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev3->setKandD((float)0, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3); + LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4); + funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4); + LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5); + funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfInvalidStateDev5->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateDev); + + delete c_name_of_current_func_block; +} + +void create_valid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str()); + LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1); + funcConfValidStateTime1->setDomain(false, true, (float)0); + funcConfValidStateTime1->setKandD((float)0, (float)0); + confValidStateTime->addLinearFunction(funcConfValidStateTime1); + LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2); + funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10 + funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime2); + LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3); + funcConfValidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfValidStateTime3->setKandD((float)0, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confValidStateTime); + + delete c_name_of_current_func_block; +} +void create_invalid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str()); + LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1); + funcConfInvalidStateTime1->setDomain(false, true, (float)0); + funcConfInvalidStateTime1->setKandD((float)0, (float)1); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1); + LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2); + funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2); + LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3); + funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfInvalidStateTime3->setKandD((float)0, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateTime); + + delete c_name_of_current_func_block; +} + +void create_confidence_state_drift_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str()); + LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1); + functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation1->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1); + LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2); + functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2); + LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3); + functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation3->setKandD((float)0, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3); + LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4); + functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4); + LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5); + functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false); + functionConfidenceDriftDeviation5->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5); + + vec_of_linear_Function_Blocks.push_back(confStateDrifts); + + delete c_name_of_current_func_block; +} + +void create_confidence_broken_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str()); + LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1); + functionConfidenceBroken1->setDomain(false, true, (float)0); + functionConfidenceBroken1->setKandD((float)0, (float)0); + confBroken->addLinearFunction(functionConfidenceBroken1); + LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2); + functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN); + functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken2); + LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3); + functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false); + functionConfidenceBroken3->setKandD((float)0, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken3); + + vec_of_linear_Function_Blocks.push_back(confBroken); + + delete c_name_of_current_func_block; +} + +/* + * mount the different function blocks to the viability monitor agent + */ +void mount_function_blocks_to_viability_monitor() +{ + Agent* viability_Monitor; + LinearFunctionBlock* current_Linear_Function_Bock; + unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size(); + unsigned int index = 0; + + //it is assumed that the viability monitor is at the last position of the vector of agents + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + for(index = 0; index < size_of_vec_lin_func_block; index++) { + current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index]; + //it is assumed that the function blocks are added into the vector in the following sequence + switch(index) { + case 0: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock; + break; + case 1: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock; + break; + case 2: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock; + break; + case 3: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock; + break; + case 4: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock; + break; + case 5: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock; + break; + case 6: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock; + break; + case 7: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock; + break; + case 8: + viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock; + break; + case 9: + viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock; + break; + } + } +} + + +void create_all_testbenches() { + char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_testbench, TEST_BENCH.c_str()); + cout << "Creating test bench" << endl; + Testbench* tb = create_testbench(c_name_of_current_testbench); + create_and_register_all_Testbench_Configs(tb); + vec_of_test_benches.push_back(tb); + + delete c_name_of_current_testbench; +} + +void create_csvr_modules() +{ + //sets the row in which the data starts, maybe row one contains the headers + unsigned int row = 2; + char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME]; + string current_reader_path_and_file_name; + //for entire data set offset has to be 1 + int data_offset = -1; + if (FILE_NAME_OF_ENTIRE_DATA == "GA_daten_200_samples.csv"){ + data_offset = 0; + } else if(FILE_NAME_OF_ENTIRE_DATA == "Draft Messergeb OP90_decimalPoint.csv"){ + data_offset = 1; + } + + cout << "Creating CSV Reader Modules" << endl; + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_oben_laengs = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),1 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_oben_quer = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_unten_laengs = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_unten_quer = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4 + data_offset,row); + + vec_of_csv_readers.push_back(csvr_GA_oben_laengs); + vec_of_csv_readers.push_back(csvr_GA_oben_quer); + vec_of_csv_readers.push_back(csvr_GA_unten_laengs); + vec_of_csv_readers.push_back(csvr_GA_unten_quer); + + + delete c_name_of_current_csv_module; +} + +/* + * all agents would be registered to all testbenches + */ +void register_agents_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Agent* current_ag; + unsigned int size_of_vec_agents = vec_of_Agents.size(); + unsigned int index_agents = 0; + + cout << "registering agents in testbenches" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) { + current_ag = vec_of_Agents[index_agents]; + register_agentInTestbench(current_tb, current_ag); + } + } + cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl; +} + +/* + * registering the sensors and the corresponding csv-readers in the testbenches + * it is assumed that the csv readers and the sensors are at the same index position + * in the vectors. + */ +void register_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Sensor* current_se; + unsigned int size_of_vec_sensors = vec_of_Sensors.size(); + unsigned int index_sensors = 0; + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + + if(size_of_vec_csv_reader != size_of_vec_sensors) { + cout << "Error, in sequence of data processing"; + cout << "Number of csv-readers should be equal to number of sensors" << endl; + } + else { + cout << "Registering sensors and their csv-readers in testbenches " << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) { + current_se = vec_of_Sensors[index_sensors]; + //it is assumed that the sensor and the corresponding csv-reader is stored + //at the same position in the two different vectors + current_csv_reader = vec_of_csv_readers[index_sensors]; + register_sensorInTestbench(current_tb, current_se, current_csv_reader); + } + } + cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to "; + cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl; + } +} + +void register_channels_in_testbenches() +{ + register_channels_of_sensors_in_testbenches(); + + register_channels_of_actors_in_testbenches(); +} + +void register_channels_of_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of sensors in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Sensors[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_se_channel << " channels of sensors were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; + +} + +void register_channels_of_actors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of agents in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Agents[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_ag_channel << " channels of agents were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; +} + +void run_simulation_of_all_testbenches() +{ + + string pressed_key; + Testbench* current_tb; + vector vec_tb_configs; + Testbench_Config* current_tb_config; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + unsigned int size_of_vec_test_bench_config; + unsigned int index_tb_cfg = 0; + //the number of rows which will be read in from the files. + unsigned int sim_rounds = 0; + const int start_row = 1; + + if(FILE_NAME_OF_ENTIRE_DATA == "GA_daten_200_samples.csv"){ + sim_rounds = 200; + }else if(FILE_NAME_OF_ENTIRE_DATA == "Draft Messergeb OP90_decimalPoint.csv"){ + sim_rounds = 198145; + }else if(FILE_NAME_OF_ENTIRE_DATA == "Ga_all_Symmetrie_Combined_25000_to_30000.csv"){ + sim_rounds = 5000; + } + + cout << "Press any key to start the simulation of all testbenches." << endl; + getline(cin, pressed_key); + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + index_tb_cfg = 0; + vec_tb_configs = current_tb->get_all_registered_testbench_configs(); + size_of_vec_test_bench_config = vec_tb_configs.size(); + for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){ + current_tb_config = vec_tb_configs[index_tb_cfg]; + current_tb->set_current_tb_config_index(index_tb_cfg); + current_tb->set_CSV_Writer_parameter(); + current_tb->set_config_values_in_linear_functions(); + //have to open new file first! with the CSV-Writer, for every round > 0 + current_tb->simulate(sim_rounds); + if(index_tb_cfg < size_of_vec_test_bench_config - 1) { + current_tb->set_CSV_Reader_row(start_row); + current_tb->set_CSV_Reader_to_beginning(); + current_tb->reset_States(); + } + } + } + cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl; +} + +void close_file_pointers() +{ + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) { + current_csv_reader = vec_of_csv_readers[index_csv_reader]; + current_csv_reader->close_file(); + } +} + +void empty_static_vectors() +{ + + empty_vec_Agent(); + empty_vec_Channel_Agent(); + empty_vec_Channel_Sensor(); + empty_vec_Sensors(); + empty_vec_csv_raders(); + empty_vec_linear_func_Blocks(); + empty_vec_TestBench(); + + vec_of_Channels_for_Agents.clear(); + vec_of_Channels_for_Sensors.clear(); + vec_of_Sensors.clear(); + vec_of_csv_readers.clear(); + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_Agent() +{ + Agent* cur_Agent; + unsigned int size_of_vec_Agent = vec_of_Agents.size(); + unsigned int index_Agent; + for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){ + cur_Agent = vec_of_Agents[index_Agent]; + //delete cur_Agent; + } + vec_of_Agents.clear(); +} + +void empty_vec_Channel_Agent() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){ + cur_Channel = vec_of_Channels_for_Agents[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Agents.clear(); +} + +void empty_vec_Channel_Sensor() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){ + cur_Channel = vec_of_Channels_for_Sensors[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Sensors.clear(); +} + +void empty_vec_Sensors() +{ + Sensor* cur_Sensor; + unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size(); + unsigned int index_Sensor; + for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){ + cur_Sensor = vec_of_Sensors[index_Sensor]; + //delete cur_Sensor; + } + vec_of_Sensors.clear(); +} + +void empty_vec_csv_raders() +{ + CSVreaderModule* cur_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){ + cur_csv_reader = vec_of_csv_readers[index_csv_reader]; + //delete cur_csv_reader; + } + vec_of_csv_readers.clear(); +} + +void empty_vec_linear_func_Blocks() +{ + LinearFunctionBlock* cur_lin_fun_block; + unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size(); + unsigned int index_lin_fun_block; + for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){ + cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block]; + //delete cur_lin_fun_block; + } + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_TestBench() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + current_tb->free_resources(); + delete current_tb; + } + vec_of_test_benches.clear(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/main_Opel_GA_Data_Symmetrie.cpp b/Version_Max_07_05_2018_CMake/src/main_Opel_GA_Data_Symmetrie.cpp new file mode 100755 index 0000000..41998d5 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main_Opel_GA_Data_Symmetrie.cpp @@ -0,0 +1,1204 @@ +/* + * main.cpp + * + * Created on: 09.08.2018 + * Author: edwin willegger, edwin.willegger@tuwien.ac.at + * This file is used to generate output data from measurements + * from Opel for SAVE project. + * In this case the data of the entire time frame is analysed. + * Based on the implementation of Maximilian Götzinger. + * + * WITH this main you can analyse data of all four GA and the Symmetrie column. + */ + + + +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include +#include +#include +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + +#include "Testbench_Config.h" + +using namespace std; + + +/* to switch between different file configurations change the + * selected DEFINE in file_util.h + * because the case of data analysis is selected in file_util.h + * current available, Wr. Neustsadt, OMV, Opel + * + * One run for the entire Opel data set needs around 5 minutes. + */ + +/********************************************************************************************************************** + ************************************************begin of global definitions of variables and constants *************** + **********************************************************************************************************************/ + +//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files. +#define SAMPLING 1 + +//global vectors for the different elements +static vector vec_of_Agents; +static vector vec_of_Sensors; +static vector vec_of_Channels_for_Sensors; +static vector vec_of_Channels_for_Agents; +static vector vec_of_linear_Function_Blocks; +static vector vec_of_test_benches; +static vector vec_of_csv_readers; + +/* + * it is not possible to have inputs and outputs, because all data are mesaruements at the end + * of the conrod line. + * Workaround: All parameters are as inputs and outputs used. + */ +//names of the measured data +const string FIRST_MEASURED_DATA_NAME = "GA_open_laengs"; //Input and Output +const string SECOND_MEASURED_DATA_NAME = "GA_oben_quer"; //Input and Output +const string THIRD_MEASURED_DATA_NAME = "GA_unten_laengs"; //Input and Output +const string FOURTH_MEASURED_DATA_NAME = "GA_unten_quer"; //Input and Output +const string FIFTH_MEASURED_DATA_NAME = "Symmetrie"; //Input and Output +//viability monitor +const string VIABILITY_MONITOR = "ViabilityMonitor"; +//index number of output, only used for data aquisition from OMV +//better implementation a const list, with the index of all outputs +//and another list for all input indices. +//const int INDEX_OUTPUT = 3; + +//name for the channels of the sensors and agents +const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)"; +const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FIFTH_MEASURED_CHANNEL_SENSOR_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; + +const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)"; +const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FIFTH_MEASURED_CHANNEL_AGENT_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; + +#define TRANSFER_RATE_CHANNEL_SENSOR 0 +#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH + + +////////////////////////////////////////////// +/* +//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery. + inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx + outer_bound_xxx = / | \ + / | \ + 0=__________/ | \ = outer_bound_xxxx ______ = 0 +-------------------------------------------------------------------------- +*/ + +//parameters of boundary for similar function +#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06, +#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent + +//same way as above but shows drift. +#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3 +#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF + +//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu +//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat. +#define BOUND_BROKEN 2 + +//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery. +//history of the data depends of it, and should change, if it changes. +#define LENGTH 10//2//10 + + +//definitions for the testbench +const string TEST_BENCH = "testbench"; + +//defintions for the csv-reader-modules +//every agent have a own-csv-reader +const string APPENDIX_CSV_MODULES = " CSV-Reader"; +const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; +const string FIFTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES; + + +/********************************************************************************************************************** + ************************************************end of global definitions of variables and constants ***************** + **********************************************************************************************************************/ + +/********************************************************************************************************************** + ************************************************begin of function prototypes ***************************************** + **********************************************************************************************************************/ +void create_and_register_all_Testbench_Configs(Testbench* current_tb); + +void create_and_register_All_Agents(); +void set_working_cycle_of_All_Agents(); + +void create_and_register_All_Sensors(); +void set_working_cycle_of_All_Sensors(); + +void create_and_register_channels(); +void create_and_register_channels_for_sensors(); +void create_and_register_channels_for_agents(); + +void mount_sensors_in_agents(); +void mount_agents_in_agents(); + +void register_data_agents_in_agent_state_Handler(); + +void create_linear_function_blocks(); +void create_same_state_deviation_function_block(); +void create_another_state_deviation_function_block(); +void create_state_time_function_block(); +void create_another_state_time_function_block(); +void create_valid_state_deviation_function_block(); +void create_invalid_state_deviation_function_block(); +void create_valid_state_time_function_block(); +void create_invalid_state_time_function_block(); +void create_confidence_state_drift_function_block(); +void create_confidence_broken_function_block(); +void mount_function_blocks_to_viability_monitor(); + +void create_all_testbenches(); + +void create_csvr_modules(); + +void register_agents_in_testbenches(); + +void register_sensors_in_testbenches(); + +void register_channels_in_testbenches(); +void register_channels_of_sensors_in_testbenches(); +void register_channels_of_actors_in_testbenches(); + +void set_config_values_in_linear_functions(Testbench* current_tb); +void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block); +void set_parameters_LinearFunction(vector vec_Lin_Func); + +void set_CSV_Writer_parameter(Testbench* current_tb); + +void run_simulation_of_all_testbenches(); + +void close_file_pointers(); + +void empty_static_vectors(); +void empty_vec_Agent(); +void empty_vec_Channel_Agent(); +void empty_vec_Channel_Sensor(); +void empty_vec_Sensors(); +void empty_vec_csv_raders(); +void empty_vec_linear_func_Blocks(); +void empty_vec_TestBench(); + + +/********************************************************************************************************************** + ************************************************end of function prototypes ******************************************* + **********************************************************************************************************************/ + +int main() +{ + cout << "This program processes test data from Opel conrod production." << endl; + + create_and_register_All_Agents(); + set_working_cycle_of_All_Agents(); + + + create_and_register_All_Sensors(); + set_working_cycle_of_All_Sensors(); + + create_and_register_channels(); + + mount_sensors_in_agents(); + + mount_agents_in_agents(); + + register_data_agents_in_agent_state_Handler(); + + create_linear_function_blocks(); + + mount_function_blocks_to_viability_monitor(); + + create_all_testbenches(); + + create_csvr_modules(); + + register_agents_in_testbenches(); + + register_sensors_in_testbenches(); + + register_channels_in_testbenches(); + + + + run_simulation_of_all_testbenches(); + + //close_file_pointers(); + //TODO memory free of all objects. + empty_static_vectors(); + + cout << "Program finished successfully" << endl; + return 0; +} + +void create_and_register_all_Testbench_Configs(Testbench* current_tb) +{ + + One_Config_t configuration; + //setting of parameters, which will the same for all configurations + configuration.bound_broken = 2; + configuration.length = 10;//10; + + //the individual settings are set before a new Testbench_Config is created. + configuration.inner_bound_sim_dif = 1 * 0.906241; + configuration.outter_bound_sim_dif = 2 * configuration.inner_bound_sim_dif; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg = new Testbench_Config(configuration); + + /*configuration.inner_bound_sim_dif = 0.0005; + configuration.outter_bound_sim_dif = 0.002; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg2 = new Testbench_Config(configuration); + + configuration.inner_bound_sim_dif = 0.002; + configuration.outter_bound_sim_dif = 0.01; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg3 = new Testbench_Config(configuration); + + configuration.inner_bound_sim_dif = 0.005; + configuration.outter_bound_sim_dif = 0.01; + configuration.outter_bound_drift = float(3) * configuration.outter_bound_sim_dif; + configuration.inner_bound_drift = configuration.outter_bound_sim_dif; + Testbench_Config* cfg4 = new Testbench_Config(configuration); + cfg->print(); + cfg2->print(); + cfg3->print(); + cfg4->print(); */ + current_tb->register_testbench_config(cfg); /* + current_tb->register_testbench_config(cfg2); + current_tb->register_testbench_config(cfg3); + current_tb->register_testbench_config(cfg4); */ +} + + + +/* + * creates all the agents used in the measurement + * and stores them into the global vector + */ +void create_and_register_All_Agents() +{ + cout << "Creating Agents" << endl; + char* c_name_of_current_agent = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_oben_laengs = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_oben_quer = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_unten_laengs = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str()); + Agent* a_GA_unten_quer = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FIFTH_MEASURED_DATA_NAME.c_str()); + Agent* a_Symmetrie = create_agent(c_name_of_current_agent); + + strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str()); + Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent); + vec_of_Agents.push_back(a_GA_oben_laengs); + vec_of_Agents.push_back(a_GA_oben_quer); + vec_of_Agents.push_back(a_GA_unten_laengs); + vec_of_Agents.push_back(a_GA_unten_quer); + vec_of_Agents.push_back(a_Symmetrie); + vec_of_Agents.push_back(a_viabilityMonitor); + cout << vec_of_Agents.size() << " agents were created" << endl; + delete c_name_of_current_agent; +} + +/* + * the working_cycle for all registered agents is set + */ +void set_working_cycle_of_All_Agents() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Agents = 0; + unsigned int index = 0; + Agent* current_Agent; + size_of_vec_of_Agents = vec_of_Agents.size(); + for(index = 0; index < size_of_vec_of_Agents; index++) { + current_Agent = vec_of_Agents[index]; + setWorkingCycleOfAgent(current_Agent, working_Cyle); + } +} + +/* + * all necessary sensors are created and registered + */ +void create_and_register_All_Sensors() +{ + cout << "Creating Sensors" << endl; + char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_oben_laengs = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_oben_quer = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_unten_laengs = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_GA_unten_quer = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FIFTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_Symmetrie = create_sensor(c_name_of_current_sensor); + + vec_of_Sensors.push_back(s_GA_oben_laengs); + vec_of_Sensors.push_back(s_GA_oben_quer); + vec_of_Sensors.push_back(s_GA_unten_laengs); + vec_of_Sensors.push_back(s_GA_unten_quer); + vec_of_Sensors.push_back(s_Symmetrie); + + cout << vec_of_Sensors.size() << " sensors were created." << endl; + delete c_name_of_current_sensor; +} + +/* + * working cycle of all registered sensors is set + */ +void set_working_cycle_of_All_Sensors() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Sensors = 0; + unsigned int index = 0; + Sensor* current_Sensor; + + size_of_vec_of_Sensors = vec_of_Sensors.size(); + for(index = 0; index < size_of_vec_of_Sensors; index++) { + current_Sensor = vec_of_Sensors[index]; + setWorkingCycleOfSensor(current_Sensor, working_Cyle); + } +} + +/* + * creating and registering all channels + */ +void create_and_register_channels() +{ + create_and_register_channels_for_sensors(); + create_and_register_channels_for_agents(); +} + +/* + * creating and registering the channels for the sensors. + */ +void create_and_register_channels_for_sensors() +{ + cout << "Creating and registering channels for sensors" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_oben_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_oben_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_unten_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_GA_unten_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Symmetrie = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Sensors.push_back(c_sa_GA_oben_laengs); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_oben_quer); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_unten_laengs); + vec_of_Channels_for_Sensors.push_back(c_sa_GA_unten_quer); + vec_of_Channels_for_Sensors.push_back(c_sa_Symmetrie); + + cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl; + + delete c_name_of_current_channel; +} + +/* + * creating and registering the channels for the agents + */ +void create_and_register_channels_for_agents() +{ + cout << "Creating and registering channels for agents" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_oben_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_oben_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_unten_laengs = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_GA_unten_quer = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Symmetrie = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Agents.push_back(c_aa_GA_oben_laengs); + vec_of_Channels_for_Agents.push_back(c_aa_GA_oben_quer); + vec_of_Channels_for_Agents.push_back(c_aa_GA_unten_laengs); + vec_of_Channels_for_Agents.push_back(c_aa_GA_unten_quer); + vec_of_Channels_for_Agents.push_back(c_aa_Symmetrie); + + + cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl; + + delete c_name_of_current_channel; +} + +void mount_sensors_in_agents() +{ + Agent* current_agent; + Sensor* current_sensor; + Channel* current_sensor_channel; + unsigned int size_of_vec_sensor = 0; + unsigned int index = 0; + + size_of_vec_sensor = vec_of_Sensors.size(); + cout << "mounting sensors in agents." << endl; + //it is assumed that the corresponding sensors and agents and channels are always at the same + //position in the different vectors, if not then you have to add an search algorithm for it. + for(index = 0; index < size_of_vec_sensor; index++) + { + current_agent = vec_of_Agents[index]; + current_sensor = vec_of_Sensors[index]; + current_sensor_channel = vec_of_Channels_for_Sensors[index]; + mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel); + } + cout << size_of_vec_sensor << " sensors in agents were mounted" << endl; +} + +void mount_agents_in_agents() +{ + Agent* current_agent; + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_agents = 0; + unsigned int index = 0; + + size_of_vec_agents = vec_of_Agents.size(); + //it is assumed that the viability agent is at the last postition in the vector + viability_Monitor = vec_of_Agents[size_of_vec_agents-1]; + //all agents and channels are registered to the viabilityMonitor agent + //so you have to subtract the viabilityMonitor from the number of elements to register + //it is assumed that all the corresponding channels and agents are placed at the same index + for(index = 0; index < size_of_vec_agents -1; index++) + { + current_agent = vec_of_Agents[index]; + current_agent_channel = vec_of_Channels_for_Agents[index]; + //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself. + if(current_agent != viability_Monitor) { + mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel); + } + } + cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl; +} + +/* + * registers the channels for the data agents to the viability monitor + */ +void register_data_agents_in_agent_state_Handler() + +{ + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_channel_agents = 0; + unsigned int index = 0; + + size_of_vec_channel_agents = vec_of_Channels_for_Agents.size(); + //get the agent for the viabilityMonitor, it is assumed that it is at the last position + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + //register all the channels to the viability monitor + for(index = 0; index < size_of_vec_channel_agents; index++) { + current_agent_channel = vec_of_Channels_for_Agents[index]; + registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel); + registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel); + } +} + +/* + * creates and register all the different linear function blocks + */ +void create_linear_function_blocks() +{ + //don't change the sequence, because later it is assumed that the functions are + //registered int the vector in this sequence + //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor + create_same_state_deviation_function_block(); + create_another_state_deviation_function_block(); + create_state_time_function_block(); + create_another_state_time_function_block(); + create_valid_state_deviation_function_block(); + create_invalid_state_deviation_function_block(); + create_valid_state_time_function_block(); + create_invalid_state_time_function_block(); + create_confidence_state_drift_function_block(); + create_confidence_broken_function_block(); +} + +/* + * creates and register the linear function block for same state deviation + */ +void create_same_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str()); + LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1); + funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev1->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev1); + LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2); + funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev2); + LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3); + funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfSim2StateDev3->setKandD((float)0, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev3); + LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4); + funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev4); + LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5); + funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfSim2StateDev5->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confSim2StateDev); + + delete c_name_of_current_func_block; +} + +/* + * creates and register another state deviation function block + */ +void create_another_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str()); + LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1); + funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev1->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev1); + LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2); + funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev2); + LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3); + funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfDif2StateDev3->setKandD((float)0, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev3); + LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4); + funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev4); + LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5); + funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfDif2StateDev5->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confDif2StateDev); + + delete c_name_of_current_func_block; +} + +void create_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str()); + LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1); + funcConfSim2StateTime1->setDomain(false, true, (float)0); + funcConfSim2StateTime1->setKandD((float)0, (float)0); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime1); + LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2); + funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime2); + LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3); + funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfSim2StateTime3->setKandD((float)0, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confSim2StateTime); + + delete c_name_of_current_func_block; +} + +void create_another_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str()); + LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1); + funcConfDif2StateTime1->setDomain(false, true, (float)0); + funcConfDif2StateTime1->setKandD((float)0, (float)1); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime1); + LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2); + funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime2); + LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3); + funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfDif2StateTime3->setKandD((float)0, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confDif2StateTime); + + delete c_name_of_current_func_block; +} + +void create_valid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str()); + LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1); + funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev1->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev1); + LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2); + funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev2); + LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3); + funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfValidStateDev3->setKandD((float)0, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev3); + LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4); + funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev4); + LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5); + funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfValidStateDev5->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confValidStateDev); + + delete c_name_of_current_func_block; +} + +void create_invalid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str()); + LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1); + funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev1->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1); + LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2); + funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2); + LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3); + funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev3->setKandD((float)0, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3); + LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4); + funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4); + LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5); + funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfInvalidStateDev5->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateDev); + + delete c_name_of_current_func_block; +} + +void create_valid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str()); + LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1); + funcConfValidStateTime1->setDomain(false, true, (float)0); + funcConfValidStateTime1->setKandD((float)0, (float)0); + confValidStateTime->addLinearFunction(funcConfValidStateTime1); + LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2); + funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10 + funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime2); + LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3); + funcConfValidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfValidStateTime3->setKandD((float)0, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confValidStateTime); + + delete c_name_of_current_func_block; +} +void create_invalid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str()); + LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1); + funcConfInvalidStateTime1->setDomain(false, true, (float)0); + funcConfInvalidStateTime1->setKandD((float)0, (float)1); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1); + LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2); + funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2); + LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3); + funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfInvalidStateTime3->setKandD((float)0, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateTime); + + delete c_name_of_current_func_block; +} + +void create_confidence_state_drift_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str()); + LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1); + functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation1->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1); + LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2); + functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2); + LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3); + functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation3->setKandD((float)0, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3); + LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4); + functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4); + LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5); + functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false); + functionConfidenceDriftDeviation5->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5); + + vec_of_linear_Function_Blocks.push_back(confStateDrifts); + + delete c_name_of_current_func_block; +} + +void create_confidence_broken_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str()); + LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1); + functionConfidenceBroken1->setDomain(false, true, (float)0); + functionConfidenceBroken1->setKandD((float)0, (float)0); + confBroken->addLinearFunction(functionConfidenceBroken1); + LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2); + functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN); + functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken2); + LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3); + functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false); + functionConfidenceBroken3->setKandD((float)0, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken3); + + vec_of_linear_Function_Blocks.push_back(confBroken); + + delete c_name_of_current_func_block; +} + +/* + * mount the different function blocks to the viability monitor agent + */ +void mount_function_blocks_to_viability_monitor() +{ + Agent* viability_Monitor; + LinearFunctionBlock* current_Linear_Function_Bock; + unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size(); + unsigned int index = 0; + + //it is assumed that the viability monitor is at the last position of the vector of agents + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + for(index = 0; index < size_of_vec_lin_func_block; index++) { + current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index]; + //it is assumed that the function blocks are added into the vector in the following sequence + switch(index) { + case 0: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock; + break; + case 1: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock; + break; + case 2: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock; + break; + case 3: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock; + break; + case 4: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock; + break; + case 5: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock; + break; + case 6: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock; + break; + case 7: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock; + break; + case 8: + viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock; + break; + case 9: + viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock; + break; + } + } +} + + +void create_all_testbenches() { + char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_testbench, TEST_BENCH.c_str()); + cout << "Creating test bench" << endl; + Testbench* tb = create_testbench(c_name_of_current_testbench); + create_and_register_all_Testbench_Configs(tb); + vec_of_test_benches.push_back(tb); + + delete c_name_of_current_testbench; +} + +void create_csvr_modules() +{ + //sets the row in which the data starts, maybe row one contains the headers + unsigned int row = 2; + char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME]; + string current_reader_path_and_file_name; + //for entire data set offset has to be 1 + int data_offset = -1; + if (FILE_NAME_OF_ENTIRE_DATA == "Ga_all_Symmetrie_Combined_25000_to_30000.csv"){ + data_offset = 2; + } + + cout << "Creating CSV Reader Modules" << endl; + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_oben_laengs = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),1 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_oben_quer = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_unten_laengs = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_GA_unten_quer = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4 + data_offset,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA; + strcpy(c_name_of_current_csv_module, FIFTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Symmetrie = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),5 + data_offset,row); + + + vec_of_csv_readers.push_back(csvr_GA_oben_laengs); + vec_of_csv_readers.push_back(csvr_GA_oben_quer); + vec_of_csv_readers.push_back(csvr_GA_unten_laengs); + vec_of_csv_readers.push_back(csvr_GA_unten_quer); + vec_of_csv_readers.push_back(csvr_Symmetrie); + + + delete c_name_of_current_csv_module; +} + +/* + * all agents would be registered to all testbenches + */ +void register_agents_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Agent* current_ag; + unsigned int size_of_vec_agents = vec_of_Agents.size(); + unsigned int index_agents = 0; + + cout << "registering agents in testbenches" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) { + current_ag = vec_of_Agents[index_agents]; + register_agentInTestbench(current_tb, current_ag); + } + } + cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl; +} + +/* + * registering the sensors and the corresponding csv-readers in the testbenches + * it is assumed that the csv readers and the sensors are at the same index position + * in the vectors. + */ +void register_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Sensor* current_se; + unsigned int size_of_vec_sensors = vec_of_Sensors.size(); + unsigned int index_sensors = 0; + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + + if(size_of_vec_csv_reader != size_of_vec_sensors) { + cout << "Error, in sequence of data processing"; + cout << "Number of csv-readers should be equal to number of sensors" << endl; + } + else { + cout << "Registering sensors and their csv-readers in testbenches " << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) { + current_se = vec_of_Sensors[index_sensors]; + //it is assumed that the sensor and the corresponding csv-reader is stored + //at the same position in the two different vectors + current_csv_reader = vec_of_csv_readers[index_sensors]; + register_sensorInTestbench(current_tb, current_se, current_csv_reader); + } + } + cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to "; + cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl; + } +} + +void register_channels_in_testbenches() +{ + register_channels_of_sensors_in_testbenches(); + + register_channels_of_actors_in_testbenches(); +} + +void register_channels_of_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of sensors in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Sensors[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_se_channel << " channels of sensors were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; + +} + +void register_channels_of_actors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of agents in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Agents[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_ag_channel << " channels of agents were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; +} + +void run_simulation_of_all_testbenches() +{ + + string pressed_key; + Testbench* current_tb; + vector vec_tb_configs; + Testbench_Config* current_tb_config; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + unsigned int size_of_vec_test_bench_config; + unsigned int index_tb_cfg = 0; + //the number of rows which will be read in from the files. + unsigned int sim_rounds = 0; + const int start_row = 1; + + if(FILE_NAME_OF_ENTIRE_DATA == "Ga_all_Symmetrie_Combined_25000_to_30000.csv"){ + sim_rounds = 5000; + } + + cout << "Press any key to start the simulation of all testbenches." << endl; + getline(cin, pressed_key); + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + index_tb_cfg = 0; + vec_tb_configs = current_tb->get_all_registered_testbench_configs(); + size_of_vec_test_bench_config = vec_tb_configs.size(); + for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){ + current_tb_config = vec_tb_configs[index_tb_cfg]; + current_tb->set_current_tb_config_index(index_tb_cfg); + current_tb->set_CSV_Writer_parameter(); + current_tb->set_config_values_in_linear_functions(); + //have to open new file first! with the CSV-Writer, for every round > 0 + current_tb->simulate(sim_rounds); + if(index_tb_cfg < size_of_vec_test_bench_config - 1) { + current_tb->set_CSV_Reader_row(start_row); + current_tb->set_CSV_Reader_to_beginning(); + current_tb->reset_States(); + } + } + } + cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl; +} + +void close_file_pointers() +{ + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) { + current_csv_reader = vec_of_csv_readers[index_csv_reader]; + current_csv_reader->close_file(); + } +} + +void empty_static_vectors() +{ + + empty_vec_Agent(); + empty_vec_Channel_Agent(); + empty_vec_Channel_Sensor(); + empty_vec_Sensors(); + empty_vec_csv_raders(); + empty_vec_linear_func_Blocks(); + empty_vec_TestBench(); + + vec_of_Channels_for_Agents.clear(); + vec_of_Channels_for_Sensors.clear(); + vec_of_Sensors.clear(); + vec_of_csv_readers.clear(); + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_Agent() +{ + Agent* cur_Agent; + unsigned int size_of_vec_Agent = vec_of_Agents.size(); + unsigned int index_Agent; + for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){ + cur_Agent = vec_of_Agents[index_Agent]; + //delete cur_Agent; + } + vec_of_Agents.clear(); +} + +void empty_vec_Channel_Agent() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){ + cur_Channel = vec_of_Channels_for_Agents[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Agents.clear(); +} + +void empty_vec_Channel_Sensor() +{ + Channel* cur_Channel; + unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size(); + unsigned int index_Channel; + for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){ + cur_Channel = vec_of_Channels_for_Sensors[index_Channel]; + //delete cur_Channel; + } + vec_of_Channels_for_Sensors.clear(); +} + +void empty_vec_Sensors() +{ + Sensor* cur_Sensor; + unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size(); + unsigned int index_Sensor; + for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){ + cur_Sensor = vec_of_Sensors[index_Sensor]; + //delete cur_Sensor; + } + vec_of_Sensors.clear(); +} + +void empty_vec_csv_raders() +{ + CSVreaderModule* cur_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + unsigned int index_csv_reader; + for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){ + cur_csv_reader = vec_of_csv_readers[index_csv_reader]; + //delete cur_csv_reader; + } + vec_of_csv_readers.clear(); +} + +void empty_vec_linear_func_Blocks() +{ + LinearFunctionBlock* cur_lin_fun_block; + unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size(); + unsigned int index_lin_fun_block; + for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){ + cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block]; + //delete cur_lin_fun_block; + } + vec_of_linear_Function_Blocks.clear(); +} + +void empty_vec_TestBench() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + current_tb->free_resources(); + delete current_tb; + } + vec_of_test_benches.clear(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/main_Wr_Neustadt.cpp b/Version_Max_07_05_2018_CMake/src/main_Wr_Neustadt.cpp new file mode 100755 index 0000000..453b03a --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main_Wr_Neustadt.cpp @@ -0,0 +1,964 @@ +/* + * main.cpp + * + * Created on: 25.05.2018 + * Author: edwin willegger, edwin.willegger@tuwien.ac.at + * This file is used to generate output data from the + * flow measurements conducted in Wr. Neustadt for the project SAVE. + * based on the implementation of Maximilian Götzinger. + */ + +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include +#include +#include +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + +using namespace std; + +/********************************************************************************************************************** + ************************************************begin of global definitions of variables and constants *************** + **********************************************************************************************************************/ + +#define SAMPLING 50 + +//global vectors for the different elements +static vector vec_of_Agents; +static vector vec_of_Sensors; +static vector vec_of_Channels_for_Sensors; +static vector vec_of_Channels_for_Agents; +static vector vec_of_linear_Function_Blocks; +static vector vec_of_test_benches; +static vector vec_of_csv_readers; + +//names of the measured data +const string FIRST_MEASURED_DATA_NAME = "Pump_Voltage"; +const string SECOND_MEASURED_DATA_NAME = "Temp_1"; +const string THIRD_MEASURED_DATA_NAME = "Temp_2"; +const string FOURTH_MEASURED_DATA_NAME = "Sharky_S"; +const string FIFTH_MEASURED_DATA_NAME = "Sharky_B"; +const string SIXTH_MEASURED_DATA_NAME = "Riels"; +const string SEVENTH_MEASURED_DATA_NAME = "Dyna"; +//viability monitor +const string VIABILITY_MONITOR = "ViabilityMonitor"; + +//name for the channels of the sensors and agents +const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)"; +const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string FIFTH_MEASURED_CHANNEL_SENSOR_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SIXTH_MEASURED_CHANNEL_SENSOR_NAME = SIXTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string SEVENTH_MEASURED_CHANNEL_SENSOR_NAME = SEVENTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME; +const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)"; +const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string FIFTH_MEASURED_CHANNEL_AGENT_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SIXTH_MEASURED_CHANNEL_AGENT_NAME = SIXTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; +const string SEVENTH_MEASURED_CHANNEL_AGENT_NAME = SEVENTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME; + +#define TRANSFER_RATE_CHANNEL_SENSOR 0 +#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH + +//defintions for the linear function blocks +const string FUNC_BLOCK_NAME_SAME_STATE_DEV = "funcBlock:confSim2StateDev"; +const string FUNC_BLOCK_NAME_ANOTHER_STATE_DEV = "funcBlock:confDif2StateDev"; +const string FUNC_BLOCK_NAME_SAME_TIME = "funcBlock:confSim2StateTime"; +const string FUNC_BLOCK_NAME_ANOTHER_STATE_TIME = "funcBlock:confDif2StateTime"; +const string FUNC_BLOCK_NAME_VAILD_STATE_DEV = "funcBlock:confValidStateDev"; +const string FUNC_BLOCK_NAME_INVALID_STATE_DEV = "funcBlock:confInvalidStateDev"; +const string FUNC_BLOCK_NAME_VALID_STATE_TIME = "funcBlock:confValidStateTime"; +const string FUNC_BLOCK_NAME_INVALID_STATE_TIME = "funcBlock:confInvalidStateTime"; +const string FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS = "confidence:confStateDrifts"; +const string FUNC_BLOCK_NAME_CONFIDENCE_BROKEN = "confidence:broken"; + +#define OUTTER_BOUND_SIM_DIF 0.14 +#define INNER_BOUND_SIM_DIF 0.01 + +#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3 +#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF + +#define BOUND_BROKEN 2 + +#define LENGTH 10 + + +//definitions for the testbench +const string TEST_BENCH = "testbench"; + +//defintions for the csv-reader-modules +const string APPENDIX_CSV_MODULES = " CSV-Reader"; +const string FIRST_MEASURED_DATA_CSV_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string SECOND_MEASURED_DATA_CSV_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string THIRD_MEASURED_DATA_CSV_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string FOURTH_MEASURED_DATA_CSV_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string FIFTH_MEASURED_DATA_CSV_NAME = FIFTH_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string SIXTH_MEASURED_DATA_CSV_NAME = SIXTH_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; +const string SEVENTH_MEASURED_DATA_CSV_NAME = SEVENTH_MEASURED_DATA_NAME + APPENDIX_CSV_MODULES; + + + +/********************************************************************************************************************** + ************************************************end of global definitions of variables and constants ***************** + **********************************************************************************************************************/ + +/********************************************************************************************************************** + ************************************************begin of function prototypes ***************************************** + **********************************************************************************************************************/ + +void create_and_register_All_Agents(); +void set_working_cycle_of_All_Agents(); + +void create_and_register_All_Sensors(); +void set_working_cycle_of_All_Sensors(); + +void create_and_register_channels(); +void create_and_register_channels_for_sensors(); +void create_and_register_channels_for_agents(); + +void mount_sensors_in_agents(); +void mount_agents_in_agents(); + +void register_data_agents_in_agent_state_Handler(); + +void create_linear_function_blocks(); +void create_same_state_deviation_function_block(); +void create_another_state_deviation_function_block(); +void create_state_time_function_block(); +void create_another_state_time_function_block(); +void create_valid_state_deviation_function_block(); +void create_invalid_state_deviation_function_block(); +void create_valid_state_time_function_block(); +void create_invalid_state_time_function_block(); +void create_confidence_state_drift_function_block(); +void create_confidence_broken_function_block(); +void mount_function_blocks_to_viability_monitor(); + +void create_all_testbenches(); + +void create_csvr_modules(); + +void register_agents_in_testbenches(); + +void register_sensors_in_testbenches(); + +void register_channels_in_testbenches(); +void register_channels_of_sensors_in_testbenches(); +void register_channels_of_actors_in_testbenches(); + +void run_simulation_of_all_testbenches(); + + +/********************************************************************************************************************** + ************************************************end of function prototypes ******************************************* + **********************************************************************************************************************/ + +int main() +{ + cout << "This program processes test data from flow measurements in Wr. Neustadt " << endl; + + create_and_register_All_Agents(); + set_working_cycle_of_All_Agents(); + + + create_and_register_All_Sensors(); + set_working_cycle_of_All_Sensors(); + + create_and_register_channels(); + + mount_sensors_in_agents(); + + mount_agents_in_agents(); + + register_data_agents_in_agent_state_Handler(); + + create_linear_function_blocks(); + + mount_function_blocks_to_viability_monitor(); + + create_all_testbenches(); + + create_csvr_modules(); + + register_agents_in_testbenches(); + + register_sensors_in_testbenches(); + + register_channels_in_testbenches(); + + run_simulation_of_all_testbenches(); + + //TODO memory free of all objects. + + + cout << "Program finished successfully" << endl; + return 0; +} + + + +/* + * creates all the agents used in the measurment + * and stores them into the global vector + */ +void create_and_register_All_Agents() +{ + cout << "Creating Agents" << endl; + char* c_name_of_current_agent = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str()); + Agent* a_Pump_Voltage = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str()); + Agent* a_Temp_1 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str()); + Agent* a_Temp_2 = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str()); + Agent* a_Sharky_S = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, FIFTH_MEASURED_DATA_NAME.c_str()); + Agent* a_Sharky_B = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SIXTH_MEASURED_DATA_NAME.c_str()); + Agent* a_Riels = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, SEVENTH_MEASURED_DATA_NAME.c_str()); + Agent* a_Dyna = create_agent(c_name_of_current_agent); + strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str()); + Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent); + vec_of_Agents.push_back(a_Pump_Voltage); + vec_of_Agents.push_back(a_Temp_1); + vec_of_Agents.push_back(a_Temp_2); + vec_of_Agents.push_back(a_Sharky_S); + vec_of_Agents.push_back(a_Sharky_B); + vec_of_Agents.push_back(a_Riels); + vec_of_Agents.push_back(a_Dyna); + vec_of_Agents.push_back(a_viabilityMonitor); + cout << vec_of_Agents.size() << " agents were created" << endl; +} + +/* + * the working_cycle for all registered agents is set + */ +void set_working_cycle_of_All_Agents() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Agents = 0; + unsigned int index = 0; + Agent* current_Agent; + size_of_vec_of_Agents = vec_of_Agents.size(); + for(index = 0; index < size_of_vec_of_Agents; index++) { + current_Agent = vec_of_Agents[index]; + setWorkingCycleOfAgent(current_Agent, working_Cyle); + } +} + +/* + * all necessary sensors are created and registered + */ +void create_and_register_All_Sensors() +{ + cout << "Creating Sensors" << endl; + char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str()); + Sensor* s_Pump_Voltage = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str()); + Sensor* s_Temp_1 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str()); + Sensor* s_Temp_2 = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_Sharky_S = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, FIFTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_Sharky_B = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SIXTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_Riels = create_sensor(c_name_of_current_sensor); + strcpy(c_name_of_current_sensor, SEVENTH_MEASURED_DATA_NAME.c_str()); + Sensor* s_Dyna = create_sensor(c_name_of_current_sensor); + vec_of_Sensors.push_back(s_Pump_Voltage); + vec_of_Sensors.push_back(s_Temp_1); + vec_of_Sensors.push_back(s_Temp_2); + vec_of_Sensors.push_back(s_Sharky_S); + vec_of_Sensors.push_back(s_Sharky_B); + vec_of_Sensors.push_back(s_Riels); + vec_of_Sensors.push_back(s_Dyna); + cout << vec_of_Sensors.size() << " sensors were created." << endl; +} + +/* + * working cycle of all registered sensors is set + */ +void set_working_cycle_of_All_Sensors() +{ + unsigned int working_Cyle = SAMPLING; + unsigned int size_of_vec_of_Sensors = 0; + unsigned int index = 0; + Sensor* current_Sensor; + + size_of_vec_of_Sensors = vec_of_Sensors.size(); + for(index = 0; index < size_of_vec_of_Sensors; index++) { + current_Sensor = vec_of_Sensors[index]; + setWorkingCycleOfSensor(current_Sensor, working_Cyle); + } +} + +/* + * creating and registering all channels + */ +void create_and_register_channels() +{ + create_and_register_channels_for_sensors(); + create_and_register_channels_for_agents(); +} + +/* + * creating and registering the channels for the sensors. + */ +void create_and_register_channels_for_sensors() +{ + cout << "Creating and registering channels for sensors" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Pump_Voltage = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Temp_1 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Temp_2 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Sharky_S = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Sharky_B = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SIXTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Riels = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SEVENTH_MEASURED_CHANNEL_SENSOR_NAME.c_str()); + Channel* c_sa_Dyna = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Sensors.push_back(c_sa_Pump_Voltage); + vec_of_Channels_for_Sensors.push_back(c_sa_Temp_1); + vec_of_Channels_for_Sensors.push_back(c_sa_Temp_2); + vec_of_Channels_for_Sensors.push_back(c_sa_Sharky_S); + vec_of_Channels_for_Sensors.push_back(c_sa_Sharky_B); + vec_of_Channels_for_Sensors.push_back(c_sa_Riels); + vec_of_Channels_for_Sensors.push_back(c_sa_Dyna); + cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl; +} + +/* + * creating and registering the channels for the agents + */ +void create_and_register_channels_for_agents() +{ + cout << "Creating and registering channels for agents" << endl; + char* c_name_of_current_channel = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Pump_Voltage = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Temp_1 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Temp_2 = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Sharky_S = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, FIFTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Sharky_B = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SIXTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Riels = create_channel(c_name_of_current_channel, 0); + strcpy(c_name_of_current_channel, SEVENTH_MEASURED_CHANNEL_AGENT_NAME.c_str()); + Channel* c_aa_Dyna = create_channel(c_name_of_current_channel, 0); + + vec_of_Channels_for_Agents.push_back(c_aa_Pump_Voltage); + vec_of_Channels_for_Agents.push_back(c_aa_Temp_1); + vec_of_Channels_for_Agents.push_back(c_aa_Temp_2); + vec_of_Channels_for_Agents.push_back(c_aa_Sharky_S); + vec_of_Channels_for_Agents.push_back(c_aa_Sharky_B); + vec_of_Channels_for_Agents.push_back(c_aa_Riels); + vec_of_Channels_for_Agents.push_back(c_aa_Dyna); + + cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl; +} + +void mount_sensors_in_agents() +{ + Agent* current_agent; + Sensor* current_sensor; + Channel* current_sensor_channel; + unsigned int size_of_vec_sensor = 0; + unsigned int index = 0; + + size_of_vec_sensor = vec_of_Sensors.size(); + cout << "mounting sensors in agents." << endl; + //it is assumed that the corresponding sensors and agents and channels are always at the same + //position in the different vectors, if not then you have to add an search algorithm for it. + for(index = 0; index < size_of_vec_sensor; index++) + { + current_agent = vec_of_Agents[index]; + current_sensor = vec_of_Sensors[index]; + current_sensor_channel = vec_of_Channels_for_Sensors[index]; + mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel); + } + cout << size_of_vec_sensor << " sensors in agents were mounted" << endl; +} + +void mount_agents_in_agents() +{ + Agent* current_agent; + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_agents = 0; + unsigned int index = 0; + + size_of_vec_agents = vec_of_Agents.size(); + //it is assumed that the viability agent is at the last postition in the vector + viability_Monitor = vec_of_Agents[size_of_vec_agents-1]; + //all agents and channels are registered to the viabilityMonitor agent + //so you have to subtract the viabilityMonitor from the number of elements to register + //it is assumed that all the corresponding channels and agents are placed at the same index + for(index = 0; index < size_of_vec_agents -1; index++) + { + current_agent = vec_of_Agents[index]; + current_agent_channel = vec_of_Channels_for_Agents[index]; + //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself. + if(current_agent != viability_Monitor) { + mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel); + } + } + cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl; +} + +/* + * registers the channels for the data agents to the viability monitor + */ +void register_data_agents_in_agent_state_Handler() + +{ + Agent* viability_Monitor; + Channel* current_agent_channel; + unsigned int size_of_vec_channel_agents = 0; + unsigned int index = 0; + + size_of_vec_channel_agents = vec_of_Channels_for_Agents.size(); + //get the agent for the viabilityMonitor, it is assumed that it is at the last position + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + //register all the channels to the viability monitor + for(index = 0; index < size_of_vec_channel_agents; index++) { + current_agent_channel = vec_of_Channels_for_Agents[index]; + registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel); + } +} + +/* + * creates and register all the different linear function blocks + */ +void create_linear_function_blocks() +{ + //don't change the sequence, because later it is assumed that the functions are + //registered int the vector in this sequence + //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor + create_same_state_deviation_function_block(); + create_another_state_deviation_function_block(); + create_state_time_function_block(); + create_another_state_time_function_block(); + create_valid_state_deviation_function_block(); + create_invalid_state_deviation_function_block(); + create_valid_state_time_function_block(); + create_invalid_state_time_function_block(); + create_confidence_state_drift_function_block(); + create_confidence_broken_function_block(); +} + +/* + * creates and register the linear function block for same state deviation + */ +void create_same_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str()); + LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateDev1 = new LinearFunction(); + funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev1->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev1); + LinearFunction* funcConfSim2StateDev2 = new LinearFunction(); + funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev2); + LinearFunction* funcConfSim2StateDev3 = new LinearFunction(); + funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfSim2StateDev3->setKandD((float)0, (float)1); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev3); + LinearFunction* funcConfSim2StateDev4 = new LinearFunction(); + funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev4); + LinearFunction* funcConfSim2StateDev5 = new LinearFunction(); + funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfSim2StateDev5->setKandD((float)0, (float)0); + confSim2StateDev->addLinearFunction(funcConfSim2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confSim2StateDev); +} + +/* + * creates and register another state deviation function block + */ +void create_another_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str()); + LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateDev1 = new LinearFunction(); + funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev1->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev1); + LinearFunction* funcConfDif2StateDev2 = new LinearFunction(); + funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev2); + LinearFunction* funcConfDif2StateDev3 = new LinearFunction(); + funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfDif2StateDev3->setKandD((float)0, (float)0); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev3); + LinearFunction* funcConfDif2StateDev4 = new LinearFunction(); + funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev4); + LinearFunction* funcConfDif2StateDev5 = new LinearFunction(); + funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfDif2StateDev5->setKandD((float)0, (float)1); + confDif2StateDev->addLinearFunction(funcConfDif2StateDev5); + + vec_of_linear_Function_Blocks.push_back(confDif2StateDev); +} + +void create_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str()); + LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfSim2StateTime1 = new LinearFunction(); + funcConfSim2StateTime1->setDomain(false, true, (float)0); + funcConfSim2StateTime1->setKandD((float)0, (float)0); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime1); + LinearFunction* funcConfSim2StateTime2 = new LinearFunction(); + funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime2); + LinearFunction* funcConfSim2StateTime3 = new LinearFunction(); + funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfSim2StateTime3->setKandD((float)0, (float)1); + confSim2StateTime->addLinearFunction(funcConfSim2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confSim2StateTime); +} + +void create_another_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str()); + LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfDif2StateTime1 = new LinearFunction(); + funcConfDif2StateTime1->setDomain(false, true, (float)0); + funcConfDif2StateTime1->setKandD((float)0, (float)1); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime1); + LinearFunction* funcConfDif2StateTime2 = new LinearFunction(); + funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime2); + LinearFunction* funcConfDif2StateTime3 = new LinearFunction(); + funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false); + funcConfDif2StateTime3->setKandD((float)0, (float)0); + confDif2StateTime->addLinearFunction(funcConfDif2StateTime3); + + vec_of_linear_Function_Blocks.push_back(confDif2StateTime); +} + +void create_valid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str()); + LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfValidStateDev1 = new LinearFunction(); + funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev1->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev1); + LinearFunction* funcConfValidStateDev2 = new LinearFunction(); + funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev2); + LinearFunction* funcConfValidStateDev3 = new LinearFunction(); + funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfValidStateDev3->setKandD((float)0, (float)1); + confValidStateDev->addLinearFunction(funcConfValidStateDev3); + LinearFunction* funcConfValidStateDev4 = new LinearFunction(); + funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev4); + LinearFunction* funcConfValidStateDev5 = new LinearFunction(); + funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfValidStateDev5->setKandD((float)0, (float)0); + confValidStateDev->addLinearFunction(funcConfValidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confValidStateDev); +} + +void create_invalid_state_deviation_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str()); + LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(); + funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev1->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1); + LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(); + funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2); + LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(); + funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF); + funcConfInvalidStateDev3->setKandD((float)0, (float)0); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3); + LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(); + funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF); + funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4); + LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(); + funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false); + funcConfInvalidStateDev5->setKandD((float)0, (float)1); + confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateDev); +} + +void create_valid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str()); + LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock("funcBlock:confValidStateTime"); + LinearFunction* funcConfValidStateTime1 = new LinearFunction(); + funcConfValidStateTime1->setDomain(false, true, (float)0); + funcConfValidStateTime1->setKandD((float)0, (float)0); + confValidStateTime->addLinearFunction(funcConfValidStateTime1); + LinearFunction* funcConfValidStateTime2 = new LinearFunction(); + funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10 + funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime2); + LinearFunction* funcConfValidStateTime3 = new LinearFunction(); + funcConfValidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfValidStateTime3->setKandD((float)0, (float)1); + confValidStateTime->addLinearFunction(funcConfValidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confValidStateTime); +} +void create_invalid_state_time_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str()); + LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(); + funcConfInvalidStateTime1->setDomain(false, true, (float)0); + funcConfInvalidStateTime1->setKandD((float)0, (float)1); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1); + LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(); + funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); + funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2); + LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(); + funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false); + funcConfInvalidStateTime3->setKandD((float)0, (float)0); + confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3); + + vec_of_linear_Function_Blocks.push_back(confInvalidStateTime); +} + +void create_confidence_state_drift_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str()); + LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(); + functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation1->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1); + LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(); + functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2); + LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(); + functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT); + functionConfidenceDriftDeviation3->setKandD((float)0, (float)0); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3); + LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(); + functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT); + functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4); + LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(); + functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false); + functionConfidenceDriftDeviation5->setKandD((float)0, (float)1); + confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5); + + vec_of_linear_Function_Blocks.push_back(confStateDrifts); +} + +void create_confidence_broken_function_block() +{ + char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str()); + LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block); + LinearFunction* functionConfidenceBroken1 = new LinearFunction(); + functionConfidenceBroken1->setDomain(false, true, (float)0); + functionConfidenceBroken1->setKandD((float)0, (float)0); + confBroken->addLinearFunction(functionConfidenceBroken1); + LinearFunction* functionConfidenceBroken2 = new LinearFunction(); + functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN); + functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken2); + LinearFunction* functionConfidenceBroken3 = new LinearFunction(); + functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false); + functionConfidenceBroken3->setKandD((float)0, (float)1); + confBroken->addLinearFunction(functionConfidenceBroken3); + + vec_of_linear_Function_Blocks.push_back(confBroken); +} + +/* + * mount the different function blocks to the viability monitior agent + */ +void mount_function_blocks_to_viability_monitor() +{ + Agent* viability_Monitor; + LinearFunctionBlock* current_Linear_Function_Bock; + unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size(); + unsigned int index = 0; + + //it is assumed that the viability monitor is at the last position of the vector of agents + viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1]; + for(index = 0; index < size_of_vec_lin_func_block; index++) { + current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index]; + //it is assumed that the function blocks are added into the vector in the following sequence + switch(index) { + case 0: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock; + break; + case 1: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock; + break; + case 2: + viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock; + break; + case 3: + viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock; + break; + case 4: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock; + break; + case 5: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock; + break; + case 6: + viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock; + break; + case 7: + viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock; + break; + case 8: + viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock; + break; + case 9: + viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock; + break; + } + } +} + + +void create_all_testbenches() { + char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME]; + strcpy(c_name_of_current_testbench, TEST_BENCH.c_str()); + cout << "Creating testbench" << endl; + Testbench* tb = create_testbench(c_name_of_current_testbench); + vec_of_test_benches.push_back(tb); +} + +void create_csvr_modules() +{ + //sets the row in which the data is available + unsigned int row = 2; + char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME]; + string current_reader_path_and_file_name; + cout << "Creating CSV Reader Modules" << endl; + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_VOLTAGE; + strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Pump_Voltage = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_TEMP_1; + strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Temp_1 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_TEMP_2; + strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Temp_2 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_SHARKY_S; + strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Sharky_S = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_SHARKY_B; + strcpy(c_name_of_current_csv_module, FIFTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Sharky_B = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_RIELS; + strcpy(c_name_of_current_csv_module, SIXTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_RIELS = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_DYNA; + strcpy(c_name_of_current_csv_module, SEVENTH_MEASURED_DATA_CSV_NAME.c_str()); + CSVreaderModule* csvr_Dyna = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),2,row); + + vec_of_csv_readers.push_back(csvr_Pump_Voltage); + vec_of_csv_readers.push_back(csvr_Temp_1); + vec_of_csv_readers.push_back(csvr_Temp_2); + vec_of_csv_readers.push_back(csvr_Sharky_S); + vec_of_csv_readers.push_back(csvr_Sharky_B); + vec_of_csv_readers.push_back(csvr_RIELS); + vec_of_csv_readers.push_back(csvr_Dyna); +} + +/* + * all agents would be registered to all testbenches + */ +void register_agents_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Agent* current_ag; + unsigned int size_of_vec_agents = vec_of_Agents.size(); + unsigned int index_agents = 0; + + cout << "registering agents in testbenches" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) { + current_ag = vec_of_Agents[index_agents]; + register_agentInTestbench(current_tb, current_ag); + } + } + cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl; +} + +/* + * registering the sensors and the corresponding csv-readers in the testbenches + * it is assumed that the csv readers and the sensors are at the same index position + * in the vectors. + */ +void register_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Sensor* current_se; + unsigned int size_of_vec_sensors = vec_of_Sensors.size(); + unsigned int index_sensors = 0; + CSVreaderModule* current_csv_reader; + unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size(); + + if(size_of_vec_csv_reader != size_of_vec_sensors) { + cout << "Error, in sequence of data processing"; + cout << "Number of csv-readers should be equal to number of sensors" << endl; + } + else { + cout << "Registering sensors and their csv-readers in testbenches " << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) { + current_se = vec_of_Sensors[index_sensors]; + //it is assumed that the sensor and the corresponding csv-reader is stored + //at the same position in the two different vectors + current_csv_reader = vec_of_csv_readers[index_sensors]; + register_sensorInTestbench(current_tb, current_se, current_csv_reader); + } + } + cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to "; + cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl; + } +} + +void register_channels_in_testbenches() +{ + register_channels_of_sensors_in_testbenches(); + + register_channels_of_actors_in_testbenches(); +} + +void register_channels_of_sensors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of sensors in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Sensors[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_se_channel << " channels of sensors were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; + +} + +void register_channels_of_actors_in_testbenches() +{ + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + Channel* current_se_ch; + unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size(); + unsigned int index_se_ch = 0; + + cout << "Registering channels of agents in testbench" << endl; + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) { + current_tb = vec_of_test_benches[index_tb]; + for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) { + current_se_ch = vec_of_Channels_for_Agents[index_se_ch]; + register_channelInTestbench(current_tb, current_se_ch); + } + } + cout << size_of_vec_ag_channel << " channels of agents were registered in "; + cout << size_of_vec_test_benches << " testbenches." << endl; +} + +void run_simulation_of_all_testbenches() +{ + + string pressed_key; + Testbench* current_tb; + unsigned int size_of_vec_test_benches = vec_of_test_benches.size(); + unsigned int index_tb = 0; + unsigned int sim_rounds = 1000; + + cout << "Press any key to start the simulation of all testbenches." << endl; + getline(cin, pressed_key); + for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){ + current_tb = vec_of_test_benches[index_tb]; + current_tb->simulate(sim_rounds); + } + cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl; +} diff --git a/Version_Max_07_05_2018_CMake/src/main_motor_old.cpp b/Version_Max_07_05_2018_CMake/src/main_motor_old.cpp new file mode 100755 index 0000000..70e88d5 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/main_motor_old.cpp @@ -0,0 +1,829 @@ +#include "Agent.h" +#include "Channel.h" +#include "create_unit.h" +#include "CSVreaderModule.h" +#include "inAgentsRegistrations.h" +#include "mount_nodes.h" +#include "register_in_testbench.h" +#include "Sensor.h" +#include "setupNode.h" +#include +#include "Testbench.h" +#include "file_util.h" + +#include "LinearFunction.h" +#include "LinearFunctionBlock.h" + + +//#include "Lookuptable.h" +//#include "Clock.h" +//#include "setup_lookuptable.h" +//#include "setup_agent.h" +//#include "Cross_Confidence_Validator.h" +//#include "Continuous_Average.h" +//#include "rlutil.h" + + + +//#define outterBoundSimDif 0.08 //0.12 //0.08 //0.04 //0.04 +//#define innerBoundSimDif 0.03 //0.04 //0.01 //0.005 //0.001 + +#define outterBoundSimDif 0.14 //0.14 +#define innerBoundSimDif 0.01 //0.01 + +#define outterBoundDRIFT outterBoundSimDif*3 //0.12 +#define innerBoundDRIFT outterBoundSimDif //0.04 + +#define boundBroken 2 //2 //8 + +//NOTE: auch in StateHandler �ndern!!!! +#define length 10 //10 + +#define SAMPLING 50 + +//#define MODE_BROKEN +//#define MODE_HEALTHY +//#define MODE_DRIFT +#define MODE_NORMAL_UNCHANGED +//#define MODE_NORMAL_LOADCHANGE +//#define MODE_NORMAL_SPEEDCHANGE + +#define CSV_FILTERED + + + + +int main(int argc, char* argv[]) +{ + //unsigned int workingCycle = 300; //sonst schafft er die unstetigkeit beim change load nicht (geht aber nur beim ungefilterten + //auch bei speed change (geht bei filtered & unfiltered) + unsigned int workingCycle = SAMPLING; + //unsigned int workingCycle = 60; + //unsigned int workingCycle = 1; + +#if defined(MODE_BROKEN) || defined(MODE_HEALTHY) + // --- Bearing Defect --- + //create agents + printf("Create Agents\n"); + Agent a_statorVoltage = create_agent("StatorVoltage"); + setWorkingCycleOfAgent(&a_statorVoltage, workingCycle); + Agent a_statorCurrent_1 = create_agent("StatorCurrent1"); + setWorkingCycleOfAgent(&a_statorCurrent_1, workingCycle); + Agent a_statorCurrent_2 = create_agent("StatorCurrent2"); + setWorkingCycleOfAgent(&a_statorCurrent_2, workingCycle); + Agent a_statorCurrent_3 = create_agent("StatorCurrent3"); + setWorkingCycleOfAgent(&a_statorCurrent_3, workingCycle); + Agent a_electromagneticTorque = create_agent("ElectromagneticTorque"); + setWorkingCycleOfAgent(&a_electromagneticTorque, workingCycle); + Agent a_vibration_1 = create_agent("Vibration1"); + setWorkingCycleOfAgent(&a_vibration_1, workingCycle); + Agent a_vibration_2 = create_agent("Vibration2"); + setWorkingCycleOfAgent(&a_vibration_2, workingCycle); + Agent a_vibration_3 = create_agent("Vibration3"); + setWorkingCycleOfAgent(&a_vibration_3, workingCycle); + Agent a_viabilityMonitor = create_agent("ViabilityMonitor"); + setWorkingCycleOfAgent(&a_viabilityMonitor, workingCycle); + + //create sensors + printf("\nCreate Sensors\n"); + Sensor s_statorVoltage = create_sensor("Stator Voltage"); + setWorkingCycleOfSensor(&s_statorVoltage, workingCycle); + Sensor s_statorCurrent_1 = create_sensor("Stator Current1"); + setWorkingCycleOfSensor(&s_statorCurrent_1, workingCycle); + Sensor s_statorCurrent_2 = create_sensor("Stator Current2"); + setWorkingCycleOfSensor(&s_statorCurrent_2, workingCycle); + Sensor s_statorCurrent_3 = create_sensor("Stator Current3"); + setWorkingCycleOfSensor(&s_statorCurrent_3, workingCycle); + Sensor s_electromagneticTorque = create_sensor("Electromagnetic Torque"); + setWorkingCycleOfSensor(&s_electromagneticTorque, workingCycle); + Sensor s_vibration_1 = create_sensor("Vibration1"); + setWorkingCycleOfSensor(&s_vibration_1, workingCycle); + Sensor s_vibration_2 = create_sensor("Vibration2"); + setWorkingCycleOfSensor(&s_vibration_2, workingCycle); + Sensor s_vibration_3 = create_sensor("Vibration3"); + setWorkingCycleOfSensor(&s_vibration_3, workingCycle); + + //create channels for sensors + printf("\nCreate Channels for Sensors\n"); + Channel c_sa_statorVoltage = create_channel("Stator Voltage (SA)", 0); + Channel c_sa_statorCurrent_1 = create_channel("Stator Current 1 (SA)", 0); + Channel c_sa_statorCurrent_2 = create_channel("Stator Current 2 (SA)", 0); + Channel c_sa_statorCurrent_3 = create_channel("Stator Current 3 (SA)", 0); + Channel c_sa_electromagneticTorque = create_channel("Electromagnetic Torque (SA)", 0); + Channel c_sa_vibration_1 = create_channel("Vibration 1 (SA)", 0); + Channel c_sa_vibration_2 = create_channel("Vibration 2 (SA)", 0); + Channel c_sa_vibration_3 = create_channel("Vibration 3 (SA)", 0); + + //create channels for sensors + printf("\nCreate Channels for Agents\n"); + Channel c_aa_statorVoltage = create_channel("Stator Voltage (AA)", 0); + Channel c_aa_statorCurrent_1 = create_channel("Stator Current 1 (AA)", 0); + Channel c_aa_statorCurrent_2 = create_channel("Stator Current 2 (AA)", 0); + Channel c_aa_statorCurrent_3 = create_channel("Stator Current 3 (AA)", 0); + Channel c_aa_electromagneticTorque = create_channel("Electromagnetic Torque (AA)", 0); + Channel c_aa_vibration_1 = create_channel("Vibration 1 (AA)", 0); + Channel c_aa_vibration_2 = create_channel("Vibration 2 (AA)", 0); + Channel c_aa_vibration_3 = create_channel("Vibration 3 (AA)", 0); + + //mount sensors in agents + printf("\nMount Sensors in Agents\n"); + mount_sensorInAgent(&a_statorVoltage, &s_statorVoltage, &c_sa_statorVoltage); + mount_sensorInAgent(&a_statorCurrent_1, &s_statorCurrent_1, &c_sa_statorCurrent_1); + mount_sensorInAgent(&a_statorCurrent_2, &s_statorCurrent_2, &c_sa_statorCurrent_2); + mount_sensorInAgent(&a_statorCurrent_3, &s_statorCurrent_3, &c_sa_statorCurrent_3); + mount_sensorInAgent(&a_electromagneticTorque, &s_electromagneticTorque, &c_sa_electromagneticTorque); + mount_sensorInAgent(&a_vibration_1, &s_vibration_1, &c_sa_vibration_1); + mount_sensorInAgent(&a_vibration_2, &s_vibration_2, &c_sa_vibration_2); + mount_sensorInAgent(&a_vibration_3, &s_vibration_3, &c_sa_vibration_3); + + //mount agents in agent(s) + printf("\nMount Agents in Agents\n"); + mount_agentInAgent(&a_viabilityMonitor, &a_statorVoltage, &c_aa_statorVoltage); + mount_agentInAgent(&a_viabilityMonitor, &a_statorCurrent_1, &c_aa_statorCurrent_1); + mount_agentInAgent(&a_viabilityMonitor, &a_statorCurrent_2, &c_aa_statorCurrent_2); + mount_agentInAgent(&a_viabilityMonitor, &a_statorCurrent_3, &c_aa_statorCurrent_3); + mount_agentInAgent(&a_viabilityMonitor, &a_electromagneticTorque, &c_aa_electromagneticTorque); + mount_agentInAgent(&a_viabilityMonitor, &a_vibration_1, &c_aa_vibration_1); + mount_agentInAgent(&a_viabilityMonitor, &a_vibration_2, &c_aa_vibration_2); + mount_agentInAgent(&a_viabilityMonitor, &a_vibration_3, &c_aa_vibration_3); + + //register agents in agents' stateHandler + printf("\nRegister agents in agents' stateHandler\n"); + registerSlaveAgentAsInputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorVoltage); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorCurrent_1); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorCurrent_2); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorCurrent_3); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_electromagneticTorque); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_vibration_1); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_vibration_2); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_vibration_3); +#else + // --- Other Modes --- + //create agents + printf("Create Agents\n"); + Agent a_statorVoltage = create_agent("StatorVoltage"); + setWorkingCycleOfAgent(&a_statorVoltage, workingCycle); + Agent a_statorCurrent = create_agent("StatorCurrent"); + setWorkingCycleOfAgent(&a_statorCurrent, workingCycle); + Agent a_speed = create_agent("Speed"); + setWorkingCycleOfAgent(&a_speed, workingCycle); + Agent a_electromagneticTorque = create_agent("ElectromagneticTorque"); + setWorkingCycleOfAgent(&a_electromagneticTorque, workingCycle); + Agent a_mechanicalTorque = create_agent("MechanicalTorque"); + setWorkingCycleOfAgent(&a_mechanicalTorque, workingCycle); + Agent a_viabilityMonitor = create_agent("ViabilityMonitor"); + setWorkingCycleOfAgent(&a_viabilityMonitor, workingCycle); + + //create sensors + printf("\nCreate Sensors\n"); + Sensor s_statorVoltage = create_sensor("Stator Voltage"); + setWorkingCycleOfSensor(&s_statorVoltage, workingCycle); + Sensor s_statorCurrent = create_sensor("Stator Current"); + setWorkingCycleOfSensor(&s_statorCurrent, workingCycle); + Sensor s_speed = create_sensor("Speed"); + setWorkingCycleOfSensor(&s_speed, workingCycle); + Sensor s_electromagneticTorque = create_sensor("Electromagnetic Torque"); + setWorkingCycleOfSensor(&s_electromagneticTorque, workingCycle); + Sensor s_mechanicalTorque = create_sensor("Mechanical Torque"); + setWorkingCycleOfSensor(&s_mechanicalTorque, workingCycle); + + //create channels for sensors + printf("\nCreate Channels for Sensors\n"); + Channel c_sa_statorVoltage = create_channel("Stator Voltage (SA)", 0); + Channel c_sa_statorCurrent = create_channel("Stator Current (SA)", 0); + Channel c_sa_speed = create_channel("Speed Sensor (SA)", 0); + Channel c_sa_electromagneticTorque = create_channel("Electromagnetic Torque (SA)", 0); + Channel c_sa_mechanicalTorque = create_channel("Mechanical Torque (SA)", 0); + + //create channels for sensors + printf("\nCreate Channels for Agents\n"); + Channel c_aa_statorVoltage = create_channel("Stator Voltage (AA-UP)", MAX_BUFFER_LENGTH); + Channel c_aa_statorCurrent = create_channel("Stator Current (AA-UP)", MAX_BUFFER_LENGTH); + Channel c_aa_speed = create_channel("Speed Sensor (AA-UP)", MAX_BUFFER_LENGTH); + Channel c_aa_electromagneticTorque = create_channel("Electromagnetic Torque (AA-UP)", MAX_BUFFER_LENGTH); + Channel c_aa_mechanicalTorque = create_channel("Mechanical Torque (AA-UP)", MAX_BUFFER_LENGTH); + + //mount sensors in agents + printf("\nMount Sensors in Agents\n"); + mount_sensorInAgent(&a_statorVoltage, &s_statorVoltage, &c_sa_statorVoltage); + mount_sensorInAgent(&a_statorCurrent, &s_statorCurrent, &c_sa_statorCurrent); + mount_sensorInAgent(&a_speed, &s_speed, &c_sa_speed); + mount_sensorInAgent(&a_electromagneticTorque, &s_electromagneticTorque, &c_sa_electromagneticTorque); + mount_sensorInAgent(&a_mechanicalTorque, &s_mechanicalTorque, &c_sa_mechanicalTorque); + + //mount agents in agent(s) + printf("\nMount Agents in Agents\n"); + mount_agentInAgent(&a_viabilityMonitor, &a_statorVoltage, &c_aa_statorVoltage); + mount_agentInAgent(&a_viabilityMonitor, &a_statorCurrent, &c_aa_statorCurrent); + mount_agentInAgent(&a_viabilityMonitor, &a_speed, &c_aa_speed); + mount_agentInAgent(&a_viabilityMonitor, &a_electromagneticTorque, &c_aa_electromagneticTorque); + mount_agentInAgent(&a_viabilityMonitor, &a_mechanicalTorque, &c_aa_mechanicalTorque); + + //register agents in agents' stateHandler + printf("\nRegister agents in agents' stateHandler\n"); + registerSlaveAgentAsInputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorVoltage); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_statorCurrent); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_speed); + registerSlaveAgentAsOutputVariableInStateHandler(&a_viabilityMonitor, &c_aa_electromagneticTorque); + registerSlaveAgentAsInputVariableInStateHandler(&a_viabilityMonitor, &c_aa_mechanicalTorque); +#endif // defined(MODE_BROKEN) || defined(MODE_HEALTHY) + + + + + + /************************ FunctionBlocks Sim/Dif to State (NEU) ************************/ + + //SAME STATE DEVIATION + LinearFunctionBlock confSim2StateDev("funcBlock:confSim2StateDev"); + LinearFunction funcConfSim2StateDev1; + funcConfSim2StateDev1.setDomain(false, true, (float)-outterBoundSimDif); + funcConfSim2StateDev1.setKandD((float)0, (float)0); + confSim2StateDev.addLinearFunction(&funcConfSim2StateDev1); + LinearFunction funcConfSim2StateDev2; + funcConfSim2StateDev2.setDomain(true, (float)-outterBoundSimDif, true, (float)-innerBoundSimDif); + funcConfSim2StateDev2.setKandD((float)-outterBoundSimDif, (float)0, (float)-innerBoundSimDif, (float)1); + confSim2StateDev.addLinearFunction(&funcConfSim2StateDev2); + LinearFunction funcConfSim2StateDev3; + funcConfSim2StateDev3.setDomain(true, (float)-innerBoundSimDif, true, (float)innerBoundSimDif); + funcConfSim2StateDev3.setKandD((float)0, (float)1); + confSim2StateDev.addLinearFunction(&funcConfSim2StateDev3); + LinearFunction funcConfSim2StateDev4; + funcConfSim2StateDev4.setDomain(true, (float)innerBoundSimDif, true, (float)outterBoundSimDif); + funcConfSim2StateDev4.setKandD((float)innerBoundSimDif, (float)1, (float)outterBoundSimDif, (float)0); + confSim2StateDev.addLinearFunction(&funcConfSim2StateDev4); + LinearFunction funcConfSim2StateDev5; + funcConfSim2StateDev5.setDomain(true, (float)outterBoundSimDif, false); + funcConfSim2StateDev5.setKandD((float)0, (float)0); + confSim2StateDev.addLinearFunction(&funcConfSim2StateDev5); + + //ANOTHER STATE DEVIATION + LinearFunctionBlock confDif2StateDev("funcBlock:confDif2StateDev"); + LinearFunction funcConfDif2StateDev1; + funcConfDif2StateDev1.setDomain(false, true, (float)-outterBoundSimDif); + funcConfDif2StateDev1.setKandD((float)0, (float)1); + confDif2StateDev.addLinearFunction(&funcConfDif2StateDev1); + LinearFunction funcConfDif2StateDev2; + funcConfDif2StateDev2.setDomain(true, (float)-outterBoundSimDif, true, (float)-innerBoundSimDif); + funcConfDif2StateDev2.setKandD((float)-outterBoundSimDif, (float)1, (float)-innerBoundSimDif, (float)0); + confDif2StateDev.addLinearFunction(&funcConfDif2StateDev2); + LinearFunction funcConfDif2StateDev3; + funcConfDif2StateDev3.setDomain(true, (float)-innerBoundSimDif, true, (float)innerBoundSimDif); + funcConfDif2StateDev3.setKandD((float)0, (float)0); + confDif2StateDev.addLinearFunction(&funcConfDif2StateDev3); + LinearFunction funcConfDif2StateDev4; + funcConfDif2StateDev4.setDomain(true, (float)innerBoundSimDif, true, (float)outterBoundSimDif); + funcConfDif2StateDev4.setKandD((float)innerBoundSimDif, (float)0, (float)outterBoundSimDif, (float)1); + confDif2StateDev.addLinearFunction(&funcConfDif2StateDev4); + LinearFunction funcConfDif2StateDev5; + funcConfDif2StateDev5.setDomain(true, (float)outterBoundSimDif, false); + funcConfDif2StateDev5.setKandD((float)0, (float)1); + confDif2StateDev.addLinearFunction(&funcConfDif2StateDev5); + + //SAME STATE TIME + LinearFunctionBlock confSim2StateTime("funcBlock:confSim2StateTime"); + LinearFunction funcConfSim2StateTime1; + funcConfSim2StateTime1.setDomain(false, true, (float)0); + funcConfSim2StateTime1.setKandD((float)0, (float)0); + confSim2StateTime.addLinearFunction(&funcConfSim2StateTime1); + LinearFunction funcConfSim2StateTime2; + funcConfSim2StateTime2.setDomain(true, (float)0, true, (float)length); + funcConfSim2StateTime2.setKandD((float)0, (float)0, (float)length, (float)1); + confSim2StateTime.addLinearFunction(&funcConfSim2StateTime2); + LinearFunction funcConfSim2StateTime3; + funcConfSim2StateTime3.setDomain(true, (float)length, false); + funcConfSim2StateTime3.setKandD((float)0, (float)1); + confSim2StateTime.addLinearFunction(&funcConfSim2StateTime3); + + //ANOTHER STATE TIME + LinearFunctionBlock confDif2StateTime("funcBlock:confDif2StateTime"); + LinearFunction funcConfDif2StateTime1; + funcConfDif2StateTime1.setDomain(false, true, (float)0); + funcConfDif2StateTime1.setKandD((float)0, (float)1); + confDif2StateTime.addLinearFunction(&funcConfDif2StateTime1); + LinearFunction funcConfDif2StateTime2; + funcConfDif2StateTime2.setDomain(true, (float)0, true, (float)length); + funcConfDif2StateTime2.setKandD((float)0, (float)1, (float)length, (float)0); + confDif2StateTime.addLinearFunction(&funcConfDif2StateTime2); + LinearFunction funcConfDif2StateTime3; + funcConfDif2StateTime3.setDomain(true, (float)length, false); + funcConfDif2StateTime3.setKandD((float)0, (float)0); + confDif2StateTime.addLinearFunction(&funcConfDif2StateTime3); + + /************************ FunctionBlocks Val/Inv State (NEU) ************************/ + + //VALID STATE DEVIATION + LinearFunctionBlock confValidStateDev("funcBlock:confValidStateDev"); + LinearFunction funcConfValidStateDev1; + funcConfValidStateDev1.setDomain(false, true, (float)-outterBoundSimDif); + funcConfValidStateDev1.setKandD((float)0, (float)0); + confValidStateDev.addLinearFunction(&funcConfValidStateDev1); + LinearFunction funcConfValidStateDev2; + funcConfValidStateDev2.setDomain(true, (float)-outterBoundSimDif, true, (float)-innerBoundSimDif); + funcConfValidStateDev2.setKandD((float)-outterBoundSimDif, (float)0, (float)-innerBoundSimDif, (float)1); + confValidStateDev.addLinearFunction(&funcConfValidStateDev2); + LinearFunction funcConfValidStateDev3; + funcConfValidStateDev3.setDomain(true, (float)-innerBoundSimDif, true, (float)innerBoundSimDif); + funcConfValidStateDev3.setKandD((float)0, (float)1); + confValidStateDev.addLinearFunction(&funcConfValidStateDev3); + LinearFunction funcConfValidStateDev4; + funcConfValidStateDev4.setDomain(true, (float)innerBoundSimDif, true, (float)outterBoundSimDif); + funcConfValidStateDev4.setKandD((float)innerBoundSimDif, (float)1, (float)outterBoundSimDif, (float)0); + confValidStateDev.addLinearFunction(&funcConfValidStateDev4); + LinearFunction funcConfValidStateDev5; + funcConfValidStateDev5.setDomain(true, (float)outterBoundSimDif, false); + funcConfValidStateDev5.setKandD((float)0, (float)0); + confValidStateDev.addLinearFunction(&funcConfValidStateDev5); + + //INVALID STATE DEVIATION + LinearFunctionBlock confInvalidStateDev("funcBlock:confInvalidStateDev"); + LinearFunction funcConfInvalidStateDev1; + funcConfInvalidStateDev1.setDomain(false, true, (float)-outterBoundSimDif); + funcConfInvalidStateDev1.setKandD((float)0, (float)1); + confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev1); + LinearFunction funcConfInvalidStateDev2; + funcConfInvalidStateDev2.setDomain(true, (float)-outterBoundSimDif, true, (float)-innerBoundSimDif); + funcConfInvalidStateDev2.setKandD((float)-outterBoundSimDif, (float)1, (float)-innerBoundSimDif, (float)0); + confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev2); + LinearFunction funcConfInvalidStateDev3; + funcConfInvalidStateDev3.setDomain(true, (float)-innerBoundSimDif, true, (float)innerBoundSimDif); + funcConfInvalidStateDev3.setKandD((float)0, (float)0); + confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev3); + LinearFunction funcConfInvalidStateDev4; + funcConfInvalidStateDev4.setDomain(true, (float)innerBoundSimDif, true, (float)outterBoundSimDif); + funcConfInvalidStateDev4.setKandD((float)innerBoundSimDif, (float)0, (float)outterBoundSimDif, (float)1); + confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev4); + LinearFunction funcConfInvalidStateDev5; + funcConfInvalidStateDev5.setDomain(true, (float)outterBoundSimDif, false); + funcConfInvalidStateDev5.setKandD((float)0, (float)1); + confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev5); + + //VALID STATE TIME + LinearFunctionBlock confValidStateTime("funcBlock:confValidStateTime"); + LinearFunction funcConfValidStateTime1; + funcConfValidStateTime1.setDomain(false, true, (float)0); + funcConfValidStateTime1.setKandD((float)0, (float)0); + confValidStateTime.addLinearFunction(&funcConfValidStateTime1); + LinearFunction funcConfValidStateTime2; + funcConfValidStateTime2.setDomain(true, (float)0, true, (float)length); //10 + funcConfValidStateTime2.setKandD((float)0, (float)0, (float)length, (float)1); + confValidStateTime.addLinearFunction(&funcConfValidStateTime2); + LinearFunction funcConfValidStateTime3; + funcConfValidStateTime3.setDomain(true, (float)length, false); + funcConfValidStateTime3.setKandD((float)0, (float)1); + confValidStateTime.addLinearFunction(&funcConfValidStateTime3); + + //INVALID STATE TIME + LinearFunctionBlock confInvalidStateTime("funcBlock:confInvalidStateTime"); + LinearFunction funcConfInvalidStateTime1; + funcConfInvalidStateTime1.setDomain(false, true, (float)0); + funcConfInvalidStateTime1.setKandD((float)0, (float)1); + confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime1); + LinearFunction funcConfInvalidStateTime2; + funcConfInvalidStateTime2.setDomain(true, (float)0, true, (float)length); + funcConfInvalidStateTime2.setKandD((float)0, (float)1, (float)length, (float)0); + confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime2); + LinearFunction funcConfInvalidStateTime3; + funcConfInvalidStateTime3.setDomain(true, (float)length, false); + funcConfInvalidStateTime3.setKandD((float)0, (float)0); + confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime3); + + + /********************************** Functions NOT OK **********************************/ + + LinearFunctionBlock confStateDrifts("confidence:confStateDrifts"); + LinearFunction functionConfidenceDriftDeviation1; + functionConfidenceDriftDeviation1.setDomain(false, true, (float)-outterBoundDRIFT); + functionConfidenceDriftDeviation1.setKandD((float)0, (float)1); + confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation1); + LinearFunction functionConfidenceDriftDeviation2; + functionConfidenceDriftDeviation2.setDomain(true, (float)-outterBoundDRIFT, true, (float)-innerBoundDRIFT); + functionConfidenceDriftDeviation2.setKandD((float)-outterBoundDRIFT, (float)1, (float)-innerBoundDRIFT, (float)0); + confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation2); + LinearFunction functionConfidenceDriftDeviation3; + functionConfidenceDriftDeviation3.setDomain(true, (float)-innerBoundDRIFT, true, (float)innerBoundDRIFT); + functionConfidenceDriftDeviation3.setKandD((float)0, (float)0); + confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation3); + LinearFunction functionConfidenceDriftDeviation4; + functionConfidenceDriftDeviation4.setDomain(true, (float)innerBoundDRIFT, true, (float)outterBoundDRIFT); + functionConfidenceDriftDeviation4.setKandD((float)innerBoundDRIFT, (float)0, (float)outterBoundDRIFT, (float)1); + confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation4); + LinearFunction functionConfidenceDriftDeviation5; + functionConfidenceDriftDeviation5.setDomain(true, (float)outterBoundDRIFT, false); + functionConfidenceDriftDeviation5.setKandD((float)0, (float)1); + confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation5); + + LinearFunctionBlock confBroken("confidence:broken"); + LinearFunction functionConfidenceBroken1; + functionConfidenceBroken1.setDomain(false, true, (float)0); + functionConfidenceBroken1.setKandD((float)0, (float)0); + confBroken.addLinearFunction(&functionConfidenceBroken1); + LinearFunction functionConfidenceBroken2; + functionConfidenceBroken2.setDomain(true, (float)0, true, (float)boundBroken); + functionConfidenceBroken2.setKandD((float)0, (float)0, (float)boundBroken, (float)1); + confBroken.addLinearFunction(&functionConfidenceBroken2); + LinearFunction functionConfidenceBroken3; + functionConfidenceBroken3.setDomain(true, (float)boundBroken, false); + functionConfidenceBroken3.setKandD((float)0, (float)1); + confBroken.addLinearFunction(&functionConfidenceBroken3); + + + /********************************** Mount Functions **********************************/ + + a_viabilityMonitor.get_stateHandler()->FuncBlockConfSim2StateDev = &confSim2StateDev; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfDif2StateDev = &confDif2StateDev; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfSim2StateTime = &confSim2StateTime; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfDif2StateTime = &confDif2StateTime; + + a_viabilityMonitor.get_stateHandler()->FuncBlockConfValStateDev = &confValidStateDev; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfInvStateDev = &confInvalidStateDev; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfValStateTime = &confValidStateTime; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfInvStateTime = &confInvalidStateTime; + + // HIIIIIIIIIIIIIIERRRRRRRRRRRR SCH�������������������NER MACHEN + a_viabilityMonitor.get_stateHandler()->DriftDeviation = &confStateDrifts; + a_viabilityMonitor.get_stateHandler()->FuncBlockConfBrokenSamples = &confBroken; + + + + //create testbench + printf("\nCreate Testbench\n"); + Testbench tb = create_testbench("testbench"); + + //at 1% threshold - stable at ~6061 + //unsigned int ROW = 6040; + unsigned int ROW = 2; + + + //csv-data + //TODO: (1) simplify constructor, (2) check CSV for number of rows and columns, (3) redesign create_CSVreaderModule function + printf("\nCreate CSV Reader Modules\n"); + std::string filepath_stator_voltage; + std::string filepath_stator_current; + std::string filepath_speed; + std::string filepath_electric_torque; + std::string filepath_mechanical_torque; + filepath_stator_voltage = PATH_TO_CSV_DATA_FILES + FOLDERNAME_NORMAL_OPERATION + FILENAME_STATOR_VOLTAGE_ABSTRACTED; + filepath_stator_current = PATH_TO_CSV_DATA_FILES + FOLDERNAME_NORMAL_OPERATION + FILENAME_STATOR_CURRENT_ABSTRACTED; + filepath_speed = PATH_TO_CSV_DATA_FILES + FOLDERNAME_NORMAL_OPERATION + FILENAME_SPEED; + filepath_electric_torque = PATH_TO_CSV_DATA_FILES + FOLDERNAME_NORMAL_OPERATION + FILENAME_ELECTROMACNTEIC_TORQUE; + filepath_mechanical_torque = PATH_TO_CSV_DATA_FILES + FOLDERNAME_NORMAL_OPERATION + FILENAME_MECHANICAL_TORQUE; + char* name_volt_csv_reader = "Stator Voltage CSV-Reader"; + char* name_curr_csv_reader = "Stator Current CSV-Reader"; + char* name_speed_csv_reader = "Speed CSV-Reader"; + char* name_el_torque_csv_reader = "Electromagnetic Torque CSV-Reader"; + char* name_me_torque_csv_reader = "Mechanical Torque CSV-Reader"; +#ifdef MODE_NORMAL_UNCHANGED +#ifdef CSV_FILTERED + //Normal_operation-Tm0 (filtered) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule(name_volt_csv_reader, filepath_stator_voltage.c_str(), 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule(name_curr_csv_reader, filepath_stator_current.c_str(), 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule(name_speed_csv_reader, filepath_speed.c_str(), 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule(name_el_torque_csv_reader, filepath_electric_torque.c_str(), 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule(name_me_torque_csv_reader, filepath_mechanical_torque.c_str(), 2, ROW); +#else + //Normal_operation-Tm0 + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-Tm0\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-Tm0\\statorCurrent_abstracted.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-Tm0\\speed.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-Tm0\\electromagneticTorque.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-Tm0\\mechanicalTorque.csv", 2, ROW); +#endif // CSV_FILTERED +#endif // MODE_NORMAL_UNCHANGED + + + +#ifdef MODE_NORMAL_LOADCHANGE +#ifdef CSV_FILTERED + /* + //Normal_operation-changing load (filteredTwice) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque.csv", 2, ROW); + */ + //Normal_operation-changing load (filteredOnce) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorCurrent_abs_fil_once.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\speed_filtered_once.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\te_filtered_once.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque.csv", 2, ROW); +#else + //Normal_operation-Tm0 + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\statorCurrent_abstracted.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\speed.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\electromagneticTorque.csv", 2, ROW); + //CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque_fil_quad.csv", 2, ROW); + //CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque_fil_triple.csv", 2, ROW); + //CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque_fil_twice.csv", 2, ROW); + //CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque_fil_once.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Normal_operation-changing load\\mechanicalTorque.csv", 2, ROW); +#endif // CSV_FILTERED +#endif // MODE_NORMAL_UNCHANGED + +#ifdef MODE_NORMAL_SPEEDCHANGE +#ifdef CSV_FILTERED + //Change_of_speed (filtered) + //CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\vsa_amp_abs_fil_twice.csv", 2, ROW); + //CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\vsa_amp_abs_fil_once.csv", 2, ROW); + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\mechanicalTorque.csv", 2, ROW); + CSVreaderModule csvr_frequency = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\frequency.csv", 2, ROW); +#else + //Change_of_speed + //CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\vsa_amp_abs_fil_twice.csv", 2, ROW); + //CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\vsa_amp_abs_fil_once.csv", 2, ROW); + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\statorCurrent_abstracted.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\speed.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\electromagneticTorque.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\mechanicalTorque.csv", 2, ROW); + CSVreaderModule csvr_frequency = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Change_of_speed\\frequency.csv", 2, ROW); +#endif // CSV_FILTERED +#endif // MODE_NORMAL_UNCHANGED + + +#ifdef MODE_DRIFT +#ifdef CSV_FILTERED + /* + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\mechanicalTorque.csv", 2, ROW); + + + //Wear-out 10% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-10pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-10pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-10pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-10pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-10pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 20% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-20pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-20pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-20pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-20pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-20pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 4% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-4pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-4pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-4pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-4pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-4pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 5% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-5pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-5pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-5pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-5pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-5pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 6% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-6pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-6pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-6pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-6pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-6pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 7% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-7pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-7pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-7pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-7pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-7pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 8% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-8pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-8pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-8pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-8pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-8pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 9% + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-9pc\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-9pc\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-9pc\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-9pc\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-9pc\\mechanicalTorque.csv", 2, ROW); + + //Wear-out HedyehNew (original with less friction) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-HedyehNew\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-HedyehNew\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-HedyehNew\\speed_filtered.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-HedyehNew\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\zusaetzlich\\Wearing-out-HedyehNew\\mechanicalTorque.csv", 2, ROW); + + + //Wear-out 001 (DataSet_2) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-001\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-001\\statorCurrent_abs_fil_twice.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-001\\speed_filtered_twice.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-001\\te_filtered_twice.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-001\\mechanicalTorque.csv", 2, ROW); + + //Wear-out 005 (DataSet_2) + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-005\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-005\\statorCurrent_abs_fil_twice.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-005\\speed_filtered_twice.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-005\\te_filtered_twice.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Samba_Dataset_2\\Wearing out-005\\mechanicalTorque.csv", 2, ROW); + */ +#else + + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\statorCurrent_abstracted.csv", 2, ROW); + CSVreaderModule csvr_speed = create_CSVreaderModule("Speed CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\speed.csv", 2, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\electromagneticTorque.csv", 2, ROW); + CSVreaderModule csvr_mechanicalTorque = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Wear-out\\mechanicalTorque.csv", 2, ROW); +#endif // CSV_FILTERED +#endif // MODE_NORMAL_UNCHANGED + +#ifdef MODE_BROKEN +#ifdef CSV_FILTERED + //Bearing-defect 0nm + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_1 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_2 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abs_fil.csv", 3, ROW); + CSVreaderModule csvr_statorCurrent_3 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abs_fil.csv", 4, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_1 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\vib1_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_2 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\vib2_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_3 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\vib3_filtered.csv", 2, ROW); +#else + + //Bearing-defect 0nm + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_1 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_2 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abstracted.csv", 3, ROW); + CSVreaderModule csvr_statorCurrent_3 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\OR_0nm_2\\statorCurrent_abstracted.csv", 4, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\source\\OR_0nm_2.csv", 5, ROW); + CSVreaderModule csvr_vibration_1 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\source\\OR_0nm_2.csv", 6, ROW); + CSVreaderModule csvr_vibration_2 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\source\\OR_0nm_2.csv", 7, ROW); + CSVreaderModule csvr_vibration_3 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\source\\OR_0nm_2.csv", 8, ROW); + +#endif // CSV_FILTERED +#endif // MODE_NORMAL_UNCHANGED + + +#ifdef MODE_HEALTHY +#ifdef CSV_FILTERED + //Bearing-defect 0nm + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_1 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_2 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 3, ROW); + CSVreaderModule csvr_statorCurrent_3 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 4, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_1 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib1_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_2 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib2_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_3 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib3_filtered.csv", 2, ROW); +#else + + printf("DATASET NOT AVAILABLE -> therefore filteres data loaded\n"); + getchar(); + + //Bearing-defect 0nm + CSVreaderModule csvr_statorVoltage = create_CSVreaderModule("Stator Voltage CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorVoltage_abstracted.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_1 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 2, ROW); + CSVreaderModule csvr_statorCurrent_2 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 3, ROW); + CSVreaderModule csvr_statorCurrent_3 = create_CSVreaderModule("Stator Current CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\statorCurrent_abs_fil.csv", 4, ROW); + CSVreaderModule csvr_electromagneticTorque = create_CSVreaderModule("Electromagnetic Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\te_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_1 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib1_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_2 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib2_filtered.csv", 2, ROW); + CSVreaderModule csvr_vibration_3 = create_CSVreaderModule("Mechanical Torque CSV-Reader", "C:\\csv-data\\sambamotor\\Anomaly-bearing_defect\\Healthy_0nm_2\\vib3_filtered.csv", 2, ROW); + + +#endif // CSV_FILTERED +#endif // MODE_HEALTHY + + + + +#ifdef MODE_NORMAL_SPEEDCHANGE + Agent a_frequency = create_agent("Frequency"); + setWorkingCycleOfAgent(&a_frequency, workingCycle); + Sensor s_frequency = create_sensor("Frequency"); + setWorkingCycleOfSensor(&s_frequency, workingCycle); + Channel c_sa_frequency = create_channel("Frequency (SA)", 0); + Channel c_aa_frequency = create_channel("Frequency (AA-UP)", MAX_BUFFER_LENGTH); + mount_sensorInAgent(&a_frequency, &s_frequency, &c_sa_frequency); + mount_agentInAgent(&a_viabilityMonitor, &a_frequency, &c_aa_frequency); + registerSlaveAgentAsInputVariableInStateHandler(&a_viabilityMonitor, &c_aa_frequency); + register_agentInTestbench(&tb, &a_frequency); + register_sensorInTestbench(&tb, &s_frequency, &csvr_frequency); + register_channelInTestbench(&tb, &c_sa_frequency); + register_channelInTestbench(&tb, &c_aa_frequency); +#endif // MODE_NORMAL_SPEEDCHANGE + + +#if defined(MODE_BROKEN) || defined(MODE_HEALTHY) + //register agents + printf("\nRegister Agents in Testbench\n"); + //TODO: "Test Bench" not "Testbench" + register_agentInTestbench(&tb, &a_statorVoltage); + register_agentInTestbench(&tb, &a_statorCurrent_1); + register_agentInTestbench(&tb, &a_statorCurrent_2); + register_agentInTestbench(&tb, &a_statorCurrent_3); + register_agentInTestbench(&tb, &a_electromagneticTorque); + register_agentInTestbench(&tb, &a_vibration_1); + register_agentInTestbench(&tb, &a_vibration_2); + register_agentInTestbench(&tb, &a_vibration_3); + register_agentInTestbench(&tb, &a_viabilityMonitor); + + //register sensors with their csv-readers + printf("\nRegister Sensors in Testbench\n"); + register_sensorInTestbench(&tb, &s_statorVoltage, &csvr_statorVoltage); + register_sensorInTestbench(&tb, &s_statorCurrent_1, &csvr_statorCurrent_1); + register_sensorInTestbench(&tb, &s_statorCurrent_2, &csvr_statorCurrent_2); + register_sensorInTestbench(&tb, &s_statorCurrent_3, &csvr_statorCurrent_3); + register_sensorInTestbench(&tb, &s_electromagneticTorque, &csvr_electromagneticTorque); + register_sensorInTestbench(&tb, &s_vibration_1, &csvr_vibration_1); + register_sensorInTestbench(&tb, &s_vibration_2, &csvr_vibration_2); + register_sensorInTestbench(&tb, &s_vibration_3, &csvr_vibration_3); + + //register sensor channels + printf("\nRegister Channels in Testbench\n"); + register_channelInTestbench(&tb, &c_sa_statorVoltage); + register_channelInTestbench(&tb, &c_sa_statorCurrent_1); + register_channelInTestbench(&tb, &c_sa_statorCurrent_2); + register_channelInTestbench(&tb, &c_sa_statorCurrent_3); + register_channelInTestbench(&tb, &c_sa_electromagneticTorque); + register_channelInTestbench(&tb, &c_sa_vibration_1); + register_channelInTestbench(&tb, &c_sa_vibration_2); + register_channelInTestbench(&tb, &c_sa_vibration_3); + register_channelInTestbench(&tb, &c_aa_statorVoltage); + register_channelInTestbench(&tb, &c_aa_statorCurrent_1); + register_channelInTestbench(&tb, &c_aa_statorCurrent_2); + register_channelInTestbench(&tb, &c_aa_statorCurrent_3); + register_channelInTestbench(&tb, &c_aa_electromagneticTorque); + register_channelInTestbench(&tb, &c_aa_vibration_1); + register_channelInTestbench(&tb, &c_aa_vibration_2); + register_channelInTestbench(&tb, &c_aa_vibration_3); +#else + //No bearing defect + //register agents + printf("\nRegister Agents in Testbench\n"); + //TODO: "Test Bench" not "Testbench" + register_agentInTestbench(&tb, &a_statorVoltage); + register_agentInTestbench(&tb, &a_statorCurrent); + register_agentInTestbench(&tb, &a_speed); + register_agentInTestbench(&tb, &a_electromagneticTorque); + register_agentInTestbench(&tb, &a_mechanicalTorque); + register_agentInTestbench(&tb, &a_viabilityMonitor); + + //register sensors with their csv-readers + printf("\nRegister Sensors in Testbench\n"); + register_sensorInTestbench(&tb, &s_statorVoltage, &csvr_statorVoltage); + register_sensorInTestbench(&tb, &s_statorCurrent, &csvr_statorCurrent); + register_sensorInTestbench(&tb, &s_speed, &csvr_speed); + register_sensorInTestbench(&tb, &s_electromagneticTorque, &csvr_electromagneticTorque); + register_sensorInTestbench(&tb, &s_mechanicalTorque, &csvr_mechanicalTorque); + + //register sensor channels + printf("\nRegister Channels in Testbench\n"); + register_channelInTestbench(&tb, &c_sa_statorVoltage); + register_channelInTestbench(&tb, &c_sa_statorCurrent); + register_channelInTestbench(&tb, &c_sa_speed); + register_channelInTestbench(&tb, &c_sa_electromagneticTorque); + register_channelInTestbench(&tb, &c_sa_mechanicalTorque); + register_channelInTestbench(&tb, &c_aa_statorVoltage); + register_channelInTestbench(&tb, &c_aa_statorCurrent); + register_channelInTestbench(&tb, &c_aa_speed); + register_channelInTestbench(&tb, &c_aa_electromagneticTorque); + register_channelInTestbench(&tb, &c_aa_mechanicalTorque); +#endif // !MODE_BROKEN + + printf("\n\nPress any key to start simulation...\n"); + getchar(); + + + //Start + //TODO: read lenght of CSV-Files and pass this number to tb.simulate +#if defined (MODE_NORMAL_UNCHANGED) || defined(MODE_NORMAL_LOADCHANGE) + tb.simulate(60000); +#endif // NORMAL_OPERATION_UNCHANGED || NORMAL_OPERATION_LOADCHANGE + +#ifdef MODE_NORMAL_SPEEDCHANGE + tb.simulate(20001); //change speed +#endif // NORMAL_OERATION_SPEEDCHANGE + +#ifdef MODE_DRIFT + tb.simulate(100000); //drift + load change (new) +#endif // MODE_DRIFT + +#if defined(MODE_BROKEN) || defined(MODE_HEALTHY) + tb.simulate(128000); //bearingDefect +#endif // defined(MODE_BROKEN) || defined(MODE_HEALTHY) + + + printf("\nSimulation has finished\n"); + getchar(); +} + diff --git a/Version_Max_07_05_2018_CMake/src/minmaxzeug.cpp b/Version_Max_07_05_2018_CMake/src/minmaxzeug.cpp new file mode 100755 index 0000000..a3f2418 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/minmaxzeug.cpp @@ -0,0 +1,26 @@ +#include "minmaxzeug.h" + +//DATE18 +float maxValueOf2Values(float value1, float value2) { + if (value1 > value2) + return value1; + else + return value2; +} + +//DATE18 +float minValueOf2Values(float value1, float value2) { + if (value1 < value2) + return value1; + else + return value2; +} + + +float fuzzyOR(float value1, float value2) { + return maxValueOf2Values(value1, value2); +} + +float fuzzyAND(float value1, float value2) { + return minValueOf2Values(value1, value2); +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/minmaxzeug.h b/Version_Max_07_05_2018_CMake/src/minmaxzeug.h new file mode 100755 index 0000000..6d17b6c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/minmaxzeug.h @@ -0,0 +1,10 @@ +#ifndef header_minmaxzeug +#define header_minmaxzeug + +float maxValueOf2Values(float value1, float value2); +float minValueOf2Values(float value1, float value2); + +float fuzzyOR(float value1, float value2); +float fuzzyAND(float value1, float value2); + +#endif // !header_minmaxzeug diff --git a/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp b/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp new file mode 100755 index 0000000..b29da68 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp @@ -0,0 +1,390 @@ +#include "attach_modules.h" +#include "mount_nodes.h" +#include "rlutil.h" +#include + +using namespace rlutil; + +bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel) { + if(agent != NULL && sensor != NULL && channel != NULL) { + printf(" > Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + if(agent->get_sensorHandlerOfAgent()->mount_sensorIntoSensorSlot(channel) && sensor->mount_agent(channel)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + setColor(TXTCOLOR_GREY); + printf("in Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", agent->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id()); + setColor(TXTCOLOR_GREY); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Agent, Sensor, or Channel is not valid\n"); + setColor(TXTCOLOR_GREY); + } + return false; +} +/* +void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, unsigned int position) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + + if(agent->mount_sensor(sensor_to_slave, position) && sensor->mount_agent(sensor_to_slave)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - on position %u\n", agent->get_id(), position); + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u) on position %u\n", agent->get_name(), agent->get_id(), position); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ +/* +void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Abstraction* abstraction) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + + if(agent->mount_sensor(sensor_to_slave, abstraction) && sensor->mount_agent(sensor_to_slave)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", agent->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("connected "); + rlutil::setColor(TXTCOLOR_GREY); + printf("with Abstraction Module "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", abstraction->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", abstraction->get_id()); + + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u) connected with Abstraction Module %s (id: %03u)\n", agent->get_name(), agent->get_id(), abstraction->get_name(), abstraction->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ +/* +void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + + if(agent->mount_sensor(sensor_to_slave, confidence_validator) && sensor->mount_agent(sensor_to_slave)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", agent->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("connected "); + rlutil::setColor(TXTCOLOR_GREY); + printf("with Range of Validity "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", confidence_validator->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", confidence_validator->get_id()); + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u) connected with Look up Table %s (id: %03u)\n", agent->get_name(), agent->get_id(), confidence_validator->get_name(), confidence_validator->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ + +bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel, HistoryModule* historyModule) { + if(agent != NULL && sensor != NULL && channel != NULL && historyModule != NULL) { + if(mount_sensorInAgent(agent, sensor, channel)) { + return attach_historyModuleToSensorSlotInAgent(agent, sensor, channel, historyModule); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("Agent, Sensor, Channel, or HistoryModule is not valid\n"); + setColor(TXTCOLOR_GREY); + } + return false; +} + +/* +void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator, Abstraction* abstraction) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + + if(agent->mount_sensor(sensor_to_slave, confidence_validator, abstraction) && sensor->mount_agent(sensor_to_slave)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", agent->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("connected "); + rlutil::setColor(TXTCOLOR_GREY); + printf("with Range of Validity "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", confidence_validator->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", confidence_validator->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("connected "); + rlutil::setColor(TXTCOLOR_GREY); + printf("with Abstraction Module "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", abstraction->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", abstraction->get_id()); + + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u) connected with Look up Table %s (id: %03u) and Abstraction Module %s (id: %03u)\n", agent->get_name(), agent->get_id(), confidence_validator->get_name(), confidence_validator->get_id(), abstraction->get_name(), abstraction->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ + +bool mount_agentInAgent(Agent *masteragent, Agent* slaveagent, Channel* channel) { + if(masteragent != NULL && slaveagent != NULL && channel != NULL) { + if(masteragent->get_slaveAgentHandlerOfAgent()->mount_slaveAgentIntoSlaveAgentSlot(channel)) { + if(slaveagent->get_masterAgentHandlerOfAgent()->mount_masterAgentIntoSlaveAgentSlot(channel)) { + printf(" > Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slaveagent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", slaveagent->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + setColor(TXTCOLOR_GREY); + printf("in Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", masteragent->get_id()); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Could not mount Master Agent %s (id: %03u) in Slave Agent %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id(), slaveagent->get_name(), slaveagent->get_id()); + setColor(TXTCOLOR_GREY); + masteragent->get_slaveAgentHandlerOfAgent()->demount_slaveAgentIntoSlaveAgentSlot(channel); + } + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > One of the Agents or Channel not valid\n"); + setColor(TXTCOLOR_GREY); + } + return false; + + + + + + + /* + if(masteragent->mount_slaveagent(slave_to_master, master_to_slave) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + setColor(TXTCOLOR_GREY); + printf("in Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", masteragent->get_id()); + + if(master_to_slave != NULL && slave_to_master != NULL) { + printf(" > bidirectional communication "); + } + else { + printf(" > unidirectional communication "); + if(master_to_slave != NULL) { + printf("(Master to Slave: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", master_to_slave->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)) ", master_to_slave->get_id()); + } + if(slave_to_master != NULL) { + printf("(Slave to Master: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slave_to_master->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)) ", slave_to_master->get_id()); + } + } + setColor(TXTCOLOR_LIGHTGREEN); + printf("set\n"); + setColor(TXTCOLOR_GREY); + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in Agent %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id()); + setColor(TXTCOLOR_GREY); + } + */ +} + +/* +void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, unsigned int position) { + printf(" > Slave - "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slaveagent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", slaveagent->get_id()); + + if(masteragent->mount_slaveagent(slave_to_master, master_to_slave, position) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in Master - "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - on position %u\n - ", masteragent->get_id(), position); + if(master_to_slave != NULL && slave_to_master != NULL) + printf("bidirectional communication\n"); + else + printf("unidirectional communication\n"); + if(master_to_slave != NULL) { + printf(" - Master to Slave: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", master_to_slave->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", master_to_slave->get_id()); + } + if(slave_to_master != NULL) { + printf(" - Slave to Master: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slave_to_master->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", slave_to_master->get_id()); + } + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in Master - %s (id: %03u) on position %u\n", masteragent->get_name(), masteragent->get_id(), position); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ +/* +void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, Cross_Confidence_Validator* ccv) { + printf(" > Slave - "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slaveagent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", slaveagent->get_id()); + + if(masteragent->mount_slaveagent(slave_to_master, master_to_slave, ccv) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in Master - "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", masteragent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", masteragent->get_id()); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("connected "); + rlutil::setColor(TXTCOLOR_GREY); + printf("with Cross Confidence Validator "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", ccv->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n - ", ccv->get_id()); + + if(master_to_slave != NULL && slave_to_master != NULL) + printf("bidirectional communication\n"); + else + printf("unidirectional communication\n"); + if(master_to_slave != NULL) { + printf(" - Master to Slave: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", master_to_slave->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", master_to_slave->get_id()); + } + if(slave_to_master != NULL) { + printf(" - Slave to Master: "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", slave_to_master->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", slave_to_master->get_id()); + } + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in Master - %s (id: %03u) with Cross Confidence Validator %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id(), ccv->get_name(), ccv->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ +/* +void mount_bunchmodule_in_agent(Agent *agent, Bunch_Module* bunch_module) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", bunch_module->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", bunch_module->get_id()); + + if(agent->mount_bunch_module(bunch_module)) { + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("mounted "); + rlutil::setColor(TXTCOLOR_GREY); + printf("in "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", agent->get_id()); + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} +*/ diff --git a/Version_Max_07_05_2018_CMake/src/mount_nodes.h b/Version_Max_07_05_2018_CMake/src/mount_nodes.h new file mode 100755 index 0000000..fb82f55 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/mount_nodes.h @@ -0,0 +1,29 @@ +#ifndef MOUNT_NODES_HEADERFILE +#define MOUNT_NODES_HEADERFILE + +//#include "Testbench.h" +#include "Agent.h" +#include "ConfidenceModule.h" +#include "Sensor.h" +//#include "Bunch_Module.h" + +bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel); +//void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, unsigned int position); +//void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Abstraction* abstraction); +//void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator); +bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel, HistoryModule* historyModule); +//void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator, Abstraction* abstraction); + +bool mount_agentInAgent(Agent *masteragent, Agent* slaveagent, Channel* channel); + + +/* +void mount_agentInAgent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master); +void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, unsigned int position); +void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, Cross_Confidence_Validator* ccv); + +void mount_bunchmodule_in_agent(Agent *agent, Bunch_Module* bunch_module); +*/ + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/printError.cpp b/Version_Max_07_05_2018_CMake/src/printError.cpp new file mode 100755 index 0000000..e9bb053 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/printError.cpp @@ -0,0 +1,16 @@ +#include +#include "printError.h" + +#define PC_MODE + +void printError(char* errorMsg) { + #ifdef PC_MODE + printf("%s\n", errorMsg); + #endif +} + +void printError(char* errorMsg, const char* additionalInfo) { + #ifdef PC_MODE + printf("%s: %s\n", errorMsg, additionalInfo); + #endif +} diff --git a/Version_Max_07_05_2018_CMake/src/printError.h b/Version_Max_07_05_2018_CMake/src/printError.h new file mode 100755 index 0000000..2042d97 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/printError.h @@ -0,0 +1,7 @@ +#ifndef PRINT_HEADERFILE +#define PRINT_HEADERFILE + +void printError(char*); +void printError(char* errorMsg, const char* additionalInfo); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/project_settings.h b/Version_Max_07_05_2018_CMake/src/project_settings.h new file mode 100755 index 0000000..4c228a3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/project_settings.h @@ -0,0 +1,7 @@ +#ifndef PROJECT_SETTINGS_HEADERFILE +#define PROJECT_SETTINGS_HEADERFILE + +//#define MAX_LENGTH_NAME 50 + + +#endif diff --git a/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp b/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp new file mode 100755 index 0000000..3c309ac --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp @@ -0,0 +1,106 @@ +#include "register_in_testbench.h" + +#include "attach_modulesToTestbench.h" +#include "rlutil.h" +#include + +using namespace rlutil; + +bool register_agentInTestbench(Testbench *tb, Agent *agent) { + if(tb != NULL && agent != NULL) { + printf(" > Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", agent->get_id()); + + if(tb->register_agent(agent)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("registered "); + setColor(TXTCOLOR_GREY); + printf("in Testbench "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s\n", tb->get_name()); + setColor(TXTCOLOR_GREY); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be registered in %s", tb->get_name()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Testbench or Agent is not valid\n"); + } + setColor(TXTCOLOR_GREY); + return false; +} + +bool register_sensorInTestbench(Testbench *tb, Sensor *sensor) { + if(tb != NULL && sensor != NULL) { + printf(" > Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + if(tb->register_sensor(sensor)) { + setColor(TXTCOLOR_LIGHTGREEN); + printf("registered "); + setColor(TXTCOLOR_GREY); + printf("in "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s\n", tb->get_name()); + setColor(TXTCOLOR_GREY); + return true; + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be registered in %s\n", tb->get_name()); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Testbench or sensor is not valid\n"); + } + setColor(TXTCOLOR_GREY); + return false; +} + +bool register_sensorInTestbench(Testbench *tb, Sensor *sensor, CSVreaderModule *csvReaderModule) { + if(tb != NULL && sensor != NULL && csvReaderModule != NULL) { + if(register_sensorInTestbench(tb, sensor)) { + return attach_csvReaderModuleToSensorSlotInAgent(tb, sensor, csvReaderModule); + } + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("Testbench or sensor is not valid\n"); + } + setColor(TXTCOLOR_GREY); + return false; +} + +bool register_channelInTestbench(Testbench *tb, Channel *channel) { + printf(" > Channel "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", channel->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", channel->get_id()); + + if(tb->register_channel(channel)){ + setColor(TXTCOLOR_LIGHTGREEN); + printf("registered "); + setColor(TXTCOLOR_GREY); + printf("in Testbench "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s\n", tb->get_name()); + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be registered in %s\n", tb->get_name()); + } + setColor(TXTCOLOR_GREY); + + return false; +} diff --git a/Version_Max_07_05_2018_CMake/src/register_in_testbench.h b/Version_Max_07_05_2018_CMake/src/register_in_testbench.h new file mode 100755 index 0000000..83e5b1c --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/register_in_testbench.h @@ -0,0 +1,13 @@ +#ifndef REGISTER_IN_TESTBENCH_HEADERFILE +#define REGISTER_IN_TESTBENCH_HEADERFILE + +#include "Testbench.h" + +bool register_agentInTestbench(Testbench *tb, Agent *agent); + +bool register_sensorInTestbench(Testbench *tb, Sensor *sensor); +bool register_sensorInTestbench(Testbench *tb, Sensor *sensor, CSVreaderModule *csvReaderModule); + +bool register_channelInTestbench(Testbench *tb, Channel *channel); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/relationChecker.cpp b/Version_Max_07_05_2018_CMake/src/relationChecker.cpp new file mode 100755 index 0000000..0981ff3 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/relationChecker.cpp @@ -0,0 +1,66 @@ +#include "relationChecker.h" + +#include + +//DATE18 +float deviationValueReferenceValue(float sampleValue, float historyValue) { + + //printf("hier\n"); + + float diff; + + if (sampleValue < 0) { + sampleValue = sampleValue * (-1); + } + + + if (historyValue < 0) { + historyValue = historyValue * (-1); + } + + if (sampleValue > historyValue) + diff = sampleValue - historyValue; + else + diff = historyValue - sampleValue; + + //printf("sample %f, reference %f, diff %f, ", sampleValue, historyValue, diff); + + + if (diff == 0) { + //printf("deviation %f\n", 0); + return 0; + } + else { + //printf("deviation %f\n", (diff / sampleValue)); + return (diff / sampleValue); + } +} + +bool valueIsRelatedToReferenceValue(float referenceValue, float value, float threshold) { + + float diff; + + if (referenceValue > value) + diff = referenceValue - value; + else + diff = value - referenceValue; + + + //printf("referenceValue %f, value %f, diff %f, threshold %f\n", referenceValue, value, diff, threshold); + + if (diff == 0 || (diff / referenceValue <= threshold)) { + return true; + } + + printf("\nRelated Calculation:\nAverage: %f\nActualValue: %f\nDiff: %f\ndeviation: %f\nthreshold: %f\n", referenceValue, value, diff, diff / referenceValue, threshold); + + return false; +} + +bool valueIsRelatedToReferenceValueOrBetweenMinAndMax(float referenceValue, float minimumValue, float maximumValue, float value, float threshold) { + if (value >= minimumValue && value <= maximumValue) { + return true; + } + + return valueIsRelatedToReferenceValue(referenceValue, value, threshold); +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/relationChecker.h b/Version_Max_07_05_2018_CMake/src/relationChecker.h new file mode 100755 index 0000000..55181e5 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/relationChecker.h @@ -0,0 +1,10 @@ +#ifndef RELATIONCHECKER_HEADERFILE +#define RELATIONCHECKER_HEADERFILE + +float deviationValueReferenceValue(float sampleValue, float historyValue); +bool valueIsRelatedToReferenceValue(float referenceValue, float value, float threshold); +bool valueIsRelatedToReferenceValueOrBetweenMinAndMax(float referenceValue, float minimumValue, float maximumValue, float value, float threshold); + + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/rlutil.h b/Version_Max_07_05_2018_CMake/src/rlutil.h new file mode 100755 index 0000000..7f79138 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/rlutil.h @@ -0,0 +1,779 @@ +#pragma once +/** + * File: rlutil.h + * + * About: Description + * This file provides some useful utilities for console mode + * roguelike game development with C and C++. It is aimed to + * be cross-platform (at least Windows and Linux). + * + * About: Copyright + * (C) 2010 Tapio Vierros + * + * About: Licensing + * See + */ + +//#ifndef RLUTIL_HEADERFILE +//#define RLUTIL_HEADERFILE + +/// Define: RLUTIL_USE_ANSI +/// Define this to use ANSI escape sequences also on Windows +/// (defaults to using WinAPI instead). +#if 0 +#define RLUTIL_USE_ANSI +#endif + +/// Define: RLUTIL_STRING_T +/// Define/typedef this to your preference to override rlutil's string type. +/// +/// Defaults to std::string with C++ and char* with C. +#if 0 +#define RLUTIL_STRING_T char* +#endif + +#ifndef RLUTIL_INLINE + #ifdef _MSC_VER + #define RLUTIL_INLINE __inline + #else + #define RLUTIL_INLINE static __inline__ + #endif +#endif + +#ifdef __cplusplus + /// Common C++ headers + #include + #include + #include // for getch() + /// Namespace forward declarations + namespace rlutil { + RLUTIL_INLINE void locate(int x, int y); + } + + //Work Arround (atartpoint) + + #define TXTCOLOR_BLACK 0 + #define TXTCOLOR_BLUE 1 + #define TXTCOLOR_GREEN 2 + #define TXTCOLOR_CYAN 3 + #define TXTCOLOR_RED 4 + #define TXTCOLOR_MAGENTA 5 + #define TXTCOLOR_BROWN 6 + #define TXTCOLOR_GREY 7 + #define TXTCOLOR_DARKGREY 8 + #define TXTCOLOR_LIGHTBLUE 9 + #define TXTCOLOR_LIGHTGREEN 10 + #define TXTCOLOR_LIGHTCYAN 11 + #define TXTCOLOR_LIGHTRED 12 + #define TXTCOLOR_LIGHTMAGENTA 13 + #define TXTCOLOR_YELLOW 14 + #define TXTCOLOR_WHITE 15 + +#else + #include // for getch() / printf() + #include // for strlen() + RLUTIL_INLINE void locate(int x, int y); // Forward declare for C to avoid warnings +#endif // __cplusplus + +#ifdef _WIN32 + #include // for WinAPI and Sleep() + #define _NO_OLDNAMES // for MinGW compatibility + #include // for getch() and kbhit() + #define getch _getch + #define kbhit _kbhit +#else + #include // for getch() and kbhit() + #include // for getch(), kbhit() and (u)sleep() + #include // for getkey() + #include // for kbhit() + #include // for kbhit() + +/// Function: getch +/// Get character without waiting for Return to be pressed. +/// Windows has this in conio.h +RLUTIL_INLINE int getch(void) { + // Here be magic. + struct termios oldt, newt; + int ch; + tcgetattr(STDIN_FILENO, &oldt); + newt = oldt; + newt.c_lflag &= ~(ICANON | ECHO); + tcsetattr(STDIN_FILENO, TCSANOW, &newt); + ch = getchar(); + tcsetattr(STDIN_FILENO, TCSANOW, &oldt); + return ch; +} + +/// Function: kbhit +/// Determines if keyboard has been hit. +/// Windows has this in conio.h +RLUTIL_INLINE int kbhit(void) { + // Here be dragons. + static struct termios oldt, newt; + int cnt = 0; + tcgetattr(STDIN_FILENO, &oldt); + newt = oldt; + newt.c_lflag &= ~(ICANON | ECHO); + newt.c_iflag = 0; // input mode + newt.c_oflag = 0; // output mode + newt.c_cc[VMIN] = 1; // minimum time to wait + newt.c_cc[VTIME] = 1; // minimum characters to wait for + tcsetattr(STDIN_FILENO, TCSANOW, &newt); + ioctl(0, FIONREAD, &cnt); // Read count + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 100; + select(STDIN_FILENO+1, NULL, NULL, NULL, &tv); // A small time delay + tcsetattr(STDIN_FILENO, TCSANOW, &oldt); + return cnt; // Return number of characters +} +#endif // _WIN32 + +#ifndef gotoxy +/// Function: gotoxy +/// Same as . +RLUTIL_INLINE void gotoxy(int x, int y) { + #ifdef __cplusplus + rlutil:: + #endif + locate(x,y); +} +#endif // gotoxy + +#ifdef __cplusplus +/// Namespace: rlutil +/// In C++ all functions except , and are arranged +/// under namespace rlutil. That is because some platforms have them defined +/// outside of rlutil. +namespace rlutil { +#endif + +/** + * Defs: Internal typedefs and macros + * RLUTIL_STRING_T - String type depending on which one of C or C++ is used + * RLUTIL_PRINT(str) - Printing macro independent of C/C++ + */ + +#ifdef __cplusplus + #ifndef RLUTIL_STRING_T + typedef std::string RLUTIL_STRING_T; + #endif // RLUTIL_STRING_T + + #define RLUTIL_PRINT(st) do { std::cout << st; } while(false) +#else // __cplusplus + #ifndef RLUTIL_STRING_T + typedef const char* RLUTIL_STRING_T; + #endif // RLUTIL_STRING_T + + #define RLUTIL_PRINT(st) printf("%s", st) +#endif // __cplusplus + +/** + * Enums: Color codes + * + * BLACK - Black + * BLUE - Blue + * GREEN - Green + * CYAN - Cyan + * RED - Red + * MAGENTA - Magenta / purple + * BROWN - Brown / dark yellow + * GREY - Grey / dark white + * DARKGREY - Dark grey / light black + * LIGHTBLUE - Light blue + * LIGHTGREEN - Light green + * LIGHTCYAN - Light cyan + * LIGHTRED - Light red + * LIGHTMAGENTA - Light magenta / light purple + * YELLOW - Yellow (bright) + * WHITE - White (bright) + */ +enum { + BLACK, + BLUE, + GREEN, + CYAN, + RED, + MAGENTA, + BROWN, + GREY, + DARKGREY, + LIGHTBLUE, + LIGHTGREEN, + LIGHTCYAN, + LIGHTRED, + LIGHTMAGENTA, + YELLOW, + WHITE +}; + +/** + * Consts: ANSI escape strings + * + * ANSI_CLS - Clears screen + * ANSI_CONSOLE_TITLE_PRE - Prefix for changing the window title, print the window title in between + * ANSI_CONSOLE_TITLE_POST - Suffix for changing the window title, print the window title in between + * ANSI_ATTRIBUTE_RESET - Resets all attributes + * ANSI_CURSOR_HIDE - Hides the cursor + * ANSI_CURSOR_SHOW - Shows the cursor + * ANSI_CURSOR_HOME - Moves the cursor home (0,0) + * ANSI_BLACK - Black + * ANSI_RED - Red + * ANSI_GREEN - Green + * ANSI_BROWN - Brown / dark yellow + * ANSI_BLUE - Blue + * ANSI_MAGENTA - Magenta / purple + * ANSI_CYAN - Cyan + * ANSI_GREY - Grey / dark white + * ANSI_DARKGREY - Dark grey / light black + * ANSI_LIGHTRED - Light red + * ANSI_LIGHTGREEN - Light green + * ANSI_YELLOW - Yellow (bright) + * ANSI_LIGHTBLUE - Light blue + * ANSI_LIGHTMAGENTA - Light magenta / light purple + * ANSI_LIGHTCYAN - Light cyan + * ANSI_WHITE - White (bright) + * ANSI_BACKGROUND_BLACK - Black background + * ANSI_BACKGROUND_RED - Red background + * ANSI_BACKGROUND_GREEN - Green background + * ANSI_BACKGROUND_YELLOW - Yellow background + * ANSI_BACKGROUND_BLUE - Blue background + * ANSI_BACKGROUND_MAGENTA - Magenta / purple background + * ANSI_BACKGROUND_CYAN - Cyan background + * ANSI_BACKGROUND_WHITE - White background + */ +const RLUTIL_STRING_T ANSI_CLS = "\033[2J\033[3J"; +const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_PRE = "\033]0;"; +const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007"; +const RLUTIL_STRING_T ANSI_ATTRIBUTE_RESET = "\033[0m"; +const RLUTIL_STRING_T ANSI_CURSOR_HIDE = "\033[?25l"; +const RLUTIL_STRING_T ANSI_CURSOR_SHOW = "\033[?25h"; +const RLUTIL_STRING_T ANSI_CURSOR_HOME = "\033[H"; +const RLUTIL_STRING_T ANSI_BLACK = "\033[22;30m"; +const RLUTIL_STRING_T ANSI_RED = "\033[22;31m"; +const RLUTIL_STRING_T ANSI_GREEN = "\033[22;32m"; +const RLUTIL_STRING_T ANSI_BROWN = "\033[22;33m"; +const RLUTIL_STRING_T ANSI_BLUE = "\033[22;34m"; +const RLUTIL_STRING_T ANSI_MAGENTA = "\033[22;35m"; +const RLUTIL_STRING_T ANSI_CYAN = "\033[22;36m"; +const RLUTIL_STRING_T ANSI_GREY = "\033[22;37m"; +const RLUTIL_STRING_T ANSI_DARKGREY = "\033[01;30m"; +const RLUTIL_STRING_T ANSI_LIGHTRED = "\033[01;31m"; +const RLUTIL_STRING_T ANSI_LIGHTGREEN = "\033[01;32m"; +const RLUTIL_STRING_T ANSI_YELLOW = "\033[01;33m"; +const RLUTIL_STRING_T ANSI_LIGHTBLUE = "\033[01;34m"; +const RLUTIL_STRING_T ANSI_LIGHTMAGENTA = "\033[01;35m"; +const RLUTIL_STRING_T ANSI_LIGHTCYAN = "\033[01;36m"; +const RLUTIL_STRING_T ANSI_WHITE = "\033[01;37m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_BLACK = "\033[40m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_RED = "\033[41m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_GREEN = "\033[42m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_YELLOW = "\033[43m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_BLUE = "\033[44m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_MAGENTA = "\033[45m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_CYAN = "\033[46m"; +const RLUTIL_STRING_T ANSI_BACKGROUND_WHITE = "\033[47m"; +// Remaining colors not supported as background colors + +/** + * Enums: Key codes for keyhit() + * + * KEY_ESCAPE - Escape + * KEY_ENTER - Enter + * KEY_SPACE - Space + * KEY_INSERT - Insert + * KEY_HOME - Home + * KEY_END - End + * KEY_DELETE - Delete + * KEY_PGUP - PageUp + * KEY_PGDOWN - PageDown + * KEY_UP - Up arrow + * KEY_DOWN - Down arrow + * KEY_LEFT - Left arrow + * KEY_RIGHT - Right arrow + * KEY_F1 - F1 + * KEY_F2 - F2 + * KEY_F3 - F3 + * KEY_F4 - F4 + * KEY_F5 - F5 + * KEY_F6 - F6 + * KEY_F7 - F7 + * KEY_F8 - F8 + * KEY_F9 - F9 + * KEY_F10 - F10 + * KEY_F11 - F11 + * KEY_F12 - F12 + * KEY_NUMDEL - Numpad del + * KEY_NUMPAD0 - Numpad 0 + * KEY_NUMPAD1 - Numpad 1 + * KEY_NUMPAD2 - Numpad 2 + * KEY_NUMPAD3 - Numpad 3 + * KEY_NUMPAD4 - Numpad 4 + * KEY_NUMPAD5 - Numpad 5 + * KEY_NUMPAD6 - Numpad 6 + * KEY_NUMPAD7 - Numpad 7 + * KEY_NUMPAD8 - Numpad 8 + * KEY_NUMPAD9 - Numpad 9 + */ +enum { + KEY_ESCAPE = 0, + KEY_ENTER = 1, + KEY_SPACE = 32, + + KEY_INSERT = 2, + KEY_HOME = 3, + KEY_PGUP = 4, + KEY_DELETE = 5, + KEY_END = 6, + KEY_PGDOWN = 7, + + KEY_UP = 14, + KEY_DOWN = 15, + KEY_LEFT = 16, + KEY_RIGHT = 17, + + KEY_F1 = 18, + KEY_F2 = 19, + KEY_F3 = 20, + KEY_F4 = 21, + KEY_F5 = 22, + KEY_F6 = 23, + KEY_F7 = 24, + KEY_F8 = 25, + KEY_F9 = 26, + KEY_F10 = 27, + KEY_F11 = 28, + KEY_F12 = 29, + + KEY_NUMDEL = 30, + KEY_NUMPAD0 = 31, + KEY_NUMPAD1 = 127, + KEY_NUMPAD2 = 128, + KEY_NUMPAD3 = 129, + KEY_NUMPAD4 = 130, + KEY_NUMPAD5 = 131, + KEY_NUMPAD6 = 132, + KEY_NUMPAD7 = 133, + KEY_NUMPAD8 = 134, + KEY_NUMPAD9 = 135 +}; + +/// Function: getkey +/// Reads a key press (blocking) and returns a key code. +/// +/// See +/// +/// Note: +/// Only Arrows, Esc, Enter and Space are currently working properly. +RLUTIL_INLINE int getkey(void) { + #ifndef _WIN32 + int cnt = kbhit(); // for ANSI escapes processing + #endif + int k = getch(); + switch(k) { + case 0: { + int kk; + switch (kk = getch()) { + case 71: return KEY_NUMPAD7; + case 72: return KEY_NUMPAD8; + case 73: return KEY_NUMPAD9; + case 75: return KEY_NUMPAD4; + case 77: return KEY_NUMPAD6; + case 79: return KEY_NUMPAD1; + case 80: return KEY_NUMPAD2; + case 81: return KEY_NUMPAD3; + case 82: return KEY_NUMPAD0; + case 83: return KEY_NUMDEL; + default: return kk-59+KEY_F1; // Function keys + }} + case 224: { + int kk; + switch (kk = getch()) { + case 71: return KEY_HOME; + case 72: return KEY_UP; + case 73: return KEY_PGUP; + case 75: return KEY_LEFT; + case 77: return KEY_RIGHT; + case 79: return KEY_END; + case 80: return KEY_DOWN; + case 81: return KEY_PGDOWN; + case 82: return KEY_INSERT; + case 83: return KEY_DELETE; + default: return kk-123+KEY_F1; // Function keys + }} + case 13: return KEY_ENTER; +#ifdef _WIN32 + case 27: return KEY_ESCAPE; +#else // _WIN32 + case 155: // single-character CSI + case 27: { + // Process ANSI escape sequences + if (cnt >= 3 && getch() == '[') { + switch (k = getch()) { + case 'A': return KEY_UP; + case 'B': return KEY_DOWN; + case 'C': return KEY_RIGHT; + case 'D': return KEY_LEFT; + } + } else return KEY_ESCAPE; + } +#endif // _WIN32 + default: return k; + } +} + +/// Function: nb_getch +/// Non-blocking getch(). Returns 0 if no key was pressed. +RLUTIL_INLINE int nb_getch(void) { + if (kbhit()) return getch(); + else return 0; +} + +/// Function: getANSIColor +/// Return ANSI color escape sequence for specified number 0-15. +/// +/// See +RLUTIL_INLINE RLUTIL_STRING_T getANSIColor(const int c) { + switch (c) { + case BLACK : return ANSI_BLACK; + case BLUE : return ANSI_BLUE; // non-ANSI + case GREEN : return ANSI_GREEN; + case CYAN : return ANSI_CYAN; // non-ANSI + case RED : return ANSI_RED; // non-ANSI + case MAGENTA : return ANSI_MAGENTA; + case BROWN : return ANSI_BROWN; + case GREY : return ANSI_GREY; + case DARKGREY : return ANSI_DARKGREY; + case LIGHTBLUE : return ANSI_LIGHTBLUE; // non-ANSI + case LIGHTGREEN : return ANSI_LIGHTGREEN; + case LIGHTCYAN : return ANSI_LIGHTCYAN; // non-ANSI; + case LIGHTRED : return ANSI_LIGHTRED; // non-ANSI; + case LIGHTMAGENTA: return ANSI_LIGHTMAGENTA; + case YELLOW : return ANSI_YELLOW; // non-ANSI + case WHITE : return ANSI_WHITE; + default: return ""; + } +} + +/// Function: getANSIBackgroundColor +/// Return ANSI background color escape sequence for specified number 0-15. +/// +/// See +RLUTIL_INLINE RLUTIL_STRING_T getANSIBackgroundColor(const int c) { + switch (c) { + case BLACK : return ANSI_BACKGROUND_BLACK; + case BLUE : return ANSI_BACKGROUND_BLUE; + case GREEN : return ANSI_BACKGROUND_GREEN; + case CYAN : return ANSI_BACKGROUND_CYAN; + case RED : return ANSI_BACKGROUND_RED; + case MAGENTA: return ANSI_BACKGROUND_MAGENTA; + case BROWN : return ANSI_BACKGROUND_YELLOW; + case GREY : return ANSI_BACKGROUND_WHITE; + default: return ""; + } +} + +/// Function: setColor +/// Change color specified by number (Windows / QBasic colors). +/// Don't change the background color +/// +/// See +RLUTIL_INLINE void setColor(int c) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_SCREEN_BUFFER_INFO csbi; + + GetConsoleScreenBufferInfo(hConsole, &csbi); + + SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFFF0) | (WORD)c); // Foreground colors take up the least significant byte +#else + RLUTIL_PRINT(getANSIColor(c)); +#endif +} + +/// Function: setBackgroundColor +/// Change background color specified by number (Windows / QBasic colors). +/// Don't change the foreground color +/// +/// See +RLUTIL_INLINE void setBackgroundColor(int c) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_SCREEN_BUFFER_INFO csbi; + + GetConsoleScreenBufferInfo(hConsole, &csbi); + + SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFF0F) | (((WORD)c) << 4)); // Background colors take up the second-least significant byte +#else + RLUTIL_PRINT(getANSIBackgroundColor(c)); +#endif +} + +/// Function: saveDefaultColor +/// Call once to preserve colors for use in resetColor() +/// on Windows without ANSI, no-op otherwise +/// +/// See +/// See +RLUTIL_INLINE int saveDefaultColor(void) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + static char initialized = 0; // bool + static WORD attributes; + + if (!initialized) { + CONSOLE_SCREEN_BUFFER_INFO csbi; + GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); + attributes = csbi.wAttributes; + initialized = 1; + } + return (int)attributes; +#else + return -1; +#endif +} + +/// Function: resetColor +/// Reset color to default +/// Requires a call to saveDefaultColor() to set the defaults +/// +/// See +/// See +/// See +RLUTIL_INLINE void resetColor(void) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (WORD)saveDefaultColor()); +#else + RLUTIL_PRINT(ANSI_ATTRIBUTE_RESET); +#endif +} + +/// Function: cls +/// Clears screen, resets all attributes and moves cursor home. +RLUTIL_INLINE void cls(void) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + // Based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022%28v=vs.85%29.aspx + const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + const COORD coordScreen = {0, 0}; + DWORD cCharsWritten; + CONSOLE_SCREEN_BUFFER_INFO csbi; + + GetConsoleScreenBufferInfo(hConsole, &csbi); + const DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y; + FillConsoleOutputCharacter(hConsole, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten); + + GetConsoleScreenBufferInfo(hConsole, &csbi); + FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten); + + SetConsoleCursorPosition(hConsole, coordScreen); +#else + RLUTIL_PRINT(ANSI_CLS); + RLUTIL_PRINT(ANSI_CURSOR_HOME); +#endif +} + +/// Function: locate +/// Sets the cursor position to 1-based x,y. +RLUTIL_INLINE void locate(int x, int y) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + COORD coord; + // TODO: clamping/assert for x/y <= 0? + coord.X = (SHORT)(x - 1); + coord.Y = (SHORT)(y - 1); // Windows uses 0-based coordinates + SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); +#else // _WIN32 || USE_ANSI + #ifdef __cplusplus + RLUTIL_PRINT("\033[" << y << ";" << x << "H"); + #else // __cplusplus + char buf[32]; + sprintf(buf, "\033[%d;%df", y, x); + RLUTIL_PRINT(buf); + #endif // __cplusplus +#endif // _WIN32 || USE_ANSI +} + +/// Function: setString +/// Prints the supplied string without advancing the cursor +#ifdef __cplusplus + +RLUTIL_INLINE void setString(const RLUTIL_STRING_T & str_) { + + //Work Around (startpoint) + const char * const str_temp = str_.data(); //Changed: "str" -> "str_temp" + wchar_t* str=new wchar_t[4096]; //Add this line + //MultiByteToWideChar(CP_ACP, 0, str_temp, -1, str, 4096); //Add this line + //Work Around (endpoint) + + unsigned int len = str_.size(); +#else // __cplusplus +RLUTIL_INLINE void setString(RLUTIL_STRING_T str) { + unsigned int len = strlen(str); +#endif // __cplusplus +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD numberOfCharsWritten; + CONSOLE_SCREEN_BUFFER_INFO csbi; + + GetConsoleScreenBufferInfo(hConsoleOutput, &csbi); + WriteConsoleOutputCharacter(hConsoleOutput, str, len, csbi.dwCursorPosition, &numberOfCharsWritten); +#else // _WIN32 || USE_ANSI + RLUTIL_PRINT(str); + #ifdef __cplusplus + RLUTIL_PRINT("\033[" << len << 'D'); + #else // __cplusplus + char buf[3 + 20 + 1]; // 20 = max length of 64-bit unsigned int when printed as dec + sprintf(buf, "\033[%uD", len); + RLUTIL_PRINT(buf); + #endif // __cplusplus +#endif // _WIN32 || USE_ANSI +} + +/// Function: setChar +/// Sets the character at the cursor without advancing the cursor +RLUTIL_INLINE void setChar(char ch) { + const char buf[] = {ch, 0}; + setString(buf); +} + +/// Function: setCursorVisibility +/// Shows/hides the cursor. +RLUTIL_INLINE void setCursorVisibility(char visible) { +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + HANDLE hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE ); + CONSOLE_CURSOR_INFO structCursorInfo; + GetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); // Get current cursor size + structCursorInfo.bVisible = (visible ? TRUE : FALSE); + SetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); +#else // _WIN32 || USE_ANSI + RLUTIL_PRINT((visible ? ANSI_CURSOR_SHOW : ANSI_CURSOR_HIDE)); +#endif // _WIN32 || USE_ANSI +} + +/// Function: hidecursor +/// Hides the cursor. +RLUTIL_INLINE void hidecursor(void) { + setCursorVisibility(0); +} + +/// Function: showcursor +/// Shows the cursor. +RLUTIL_INLINE void showcursor(void) { + setCursorVisibility(1); +} + +/// Function: msleep +/// Waits given number of milliseconds before continuing. +RLUTIL_INLINE void msleep(unsigned int ms) { +#ifdef _WIN32 + Sleep(ms); +#else + // usleep argument must be under 1 000 000 + if (ms > 1000) sleep(ms/1000000); + usleep((ms % 1000000) * 1000); +#endif +} + +/// Function: trows +/// Get the number of rows in the terminal window or -1 on error. +RLUTIL_INLINE int trows(void) { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbi; + if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) + return -1; + else + return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height + // return csbi.dwSize.Y; // Buffer height +#else +#ifdef TIOCGSIZE + struct ttysize ts; + ioctl(STDIN_FILENO, TIOCGSIZE, &ts); + return ts.ts_lines; +#elif defined(TIOCGWINSZ) + struct winsize ts; + ioctl(STDIN_FILENO, TIOCGWINSZ, &ts); + return ts.ws_row; +#else // TIOCGSIZE + return -1; +#endif // TIOCGSIZE +#endif // _WIN32 +} + +/// Function: tcols +/// Get the number of columns in the terminal window or -1 on error. +RLUTIL_INLINE int tcols(void) { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbi; + if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) + return -1; + else + return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width + // return csbi.dwSize.X; // Buffer width +#else +#ifdef TIOCGSIZE + struct ttysize ts; + ioctl(STDIN_FILENO, TIOCGSIZE, &ts); + return ts.ts_cols; +#elif defined(TIOCGWINSZ) + struct winsize ts; + ioctl(STDIN_FILENO, TIOCGWINSZ, &ts); + return ts.ws_col; +#else // TIOCGSIZE + return -1; +#endif // TIOCGSIZE +#endif // _WIN32 +} + +/// Function: anykey +/// Waits until a key is pressed. +/// In C++, it either takes no arguments +/// or a template-type-argument-deduced +/// argument. +/// In C, it takes a const char* representing +/// the message to be displayed, or NULL +/// for no message. +#ifdef __cplusplus +RLUTIL_INLINE void anykey() { + getch(); +} + +template void anykey(const T& msg) { + RLUTIL_PRINT(msg); +#else +RLUTIL_INLINE void anykey(RLUTIL_STRING_T msg) { + if (msg) + RLUTIL_PRINT(msg); +#endif // __cplusplus + getch(); +} + +RLUTIL_INLINE void setConsoleTitle(RLUTIL_STRING_T title) { + const char * true_title = +#ifdef __cplusplus + title.c_str(); +#else // __cplusplus + title; +#endif // __cplusplus +#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI) + SetConsoleTitleA(true_title); +#else + RLUTIL_PRINT(ANSI_CONSOLE_TITLE_PRE); + RLUTIL_PRINT(true_title); + RLUTIL_PRINT(ANSI_CONSOLE_TITLE_POST); +#endif // defined(_WIN32) && !defined(RLUTIL_USE_ANSI) +} + +// Classes are here at the end so that documentation is pretty. + +#ifdef __cplusplus +/// Class: CursorHider +/// RAII OOP wrapper for . +/// Hides the cursor and shows it again +/// when the object goes out of scope. +struct CursorHider { + CursorHider() { hidecursor(); } + ~CursorHider() { showcursor(); } +}; + +} // namespace rlutil +#endif + +//#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/settings.h b/Version_Max_07_05_2018_CMake/src/settings.h new file mode 100755 index 0000000..e69de29 diff --git a/Version_Max_07_05_2018_CMake/src/setupNode.cpp b/Version_Max_07_05_2018_CMake/src/setupNode.cpp new file mode 100755 index 0000000..25fcffd --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setupNode.cpp @@ -0,0 +1,45 @@ +#include "setupNode.h" + +#include "rlutil.h" + +using namespace rlutil; + +void setWorkingCycleOfSensor(Sensor* sensor, unsigned int workingCycle) { + if (sensor->set_workingCycle(workingCycle)) { + printf(" > WorkingCycle of Sensor "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", sensor->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", sensor->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to %u\n", workingCycle); + + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", sensor->get_name(), sensor->get_id()); + setColor(TXTCOLOR_GREY); + } +} + +void setWorkingCycleOfAgent(Agent* agent, unsigned int workingCycle) { + if (agent->set_workingCycle(workingCycle)) { + printf(" > WorkingCycle of Agent "); + setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", agent->get_name()); + setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", agent->get_id()); + setColor(TXTCOLOR_LIGHTGREEN); + printf("set "); + setColor(TXTCOLOR_GREY); + printf("to %u\n", workingCycle); + + } + else { + setColor(TXTCOLOR_LIGHTRED); + printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", agent->get_name(), agent->get_id()); + setColor(TXTCOLOR_GREY); + } +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/setupNode.h b/Version_Max_07_05_2018_CMake/src/setupNode.h new file mode 100755 index 0000000..acc5bda --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setupNode.h @@ -0,0 +1,11 @@ +#ifndef SETUPNODE_HEADERFILE +#define SETUPNODE_HEADERFILE + +#include "Agent.h" +#include "Sensor.h" + +void setWorkingCycleOfSensor(Sensor* sensor, unsigned int workingCycle); +void setWorkingCycleOfAgent(Agent* agent, unsigned int workingCycle); + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/setup_agent.cpp b/Version_Max_07_05_2018_CMake/src/setup_agent.cpp new file mode 100755 index 0000000..19029f0 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setup_agent.cpp @@ -0,0 +1,13 @@ +#include "setup_agent.h" + +#include + +//TODO: schönerer output +void set_agents_abstraction_method(Agent* agent, unsigned int abstraction_method) { + /* + if(agent->set_abstraction_method(abstraction_method)) + printf("set!"); + else + printf("not set"); + */ +} diff --git a/Version_Max_07_05_2018_CMake/src/setup_agent.h b/Version_Max_07_05_2018_CMake/src/setup_agent.h new file mode 100755 index 0000000..a4f5aca --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setup_agent.h @@ -0,0 +1,8 @@ +#ifndef SETUP_AGENT_HEADERFILE +#define SETUP_AGENT_HEADERFILE + +#include "Agent.h" + +void set_agents_abstraction_method(Agent* agent, unsigned int abstraction_method); + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp new file mode 100755 index 0000000..f1061b9 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp @@ -0,0 +1,52 @@ +#include "setup_lookuptable.h" +#include +#include "rlutil.h" + +void fill_lookuptable(Lookuptable* lut, int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included) { + printf(" > Score %i with Range ", score); + if(flag_lower_boundary_included) + printf("["); + else + printf("]"); + printf("%6.2f,%6.2f ", lower_boundary, upper_boundary); + if(flag_upper_boundary_included) + printf("] "); + else + printf("[ "); + + if(lut->add_range_to_lookuptable(score, lower_boundary, flag_lower_boundary_included, upper_boundary, flag_upper_boundary_included)) { + printf("was "); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("added "); + rlutil::setColor(TXTCOLOR_GREY); + printf("to "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", lut->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u)\n", lut->get_id()); + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("couldn't be added to %s (id: %03u)\n", lut->get_name(), lut->get_id()); + rlutil::setColor(TXTCOLOR_GREY); + } +} + +void check_and_activate_lookuptable(Lookuptable* lut) { + printf(" > "); + rlutil::setColor(TXTCOLOR_LIGHTCYAN); + printf("%s ", lut->get_name()); + rlutil::setColor(TXTCOLOR_GREY); + printf("(id: %03u) ", lut->get_id()); + + if(lut->check_sort_and_activate()) { + printf("seems to be "); + rlutil::setColor(TXTCOLOR_LIGHTGREEN); + printf("correct\n"); + } + else { + rlutil::setColor(TXTCOLOR_LIGHTRED); + printf("is not correct\n", lut->get_name(), lut->get_id()); + } + rlutil::setColor(TXTCOLOR_GREY); +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/setup_lookuptable.h b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.h new file mode 100755 index 0000000..36e278d --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.h @@ -0,0 +1,10 @@ +#ifndef SETUP_LOOKUPTABLE_HEADERFILE +#define SETUP_LOOKUPTABLE_HEADERFILE + +#include "Lookuptable.h" + +void fill_lookuptable(Lookuptable* lut, int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included); +void check_and_activate_lookuptable(Lookuptable* lut); + + +#endif \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/user_method_abstraction.cpp b/Version_Max_07_05_2018_CMake/src/user_method_abstraction.cpp new file mode 100755 index 0000000..65cd5a9 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/user_method_abstraction.cpp @@ -0,0 +1,3 @@ +void br_abstraction(float input, int* output) { + +} \ No newline at end of file diff --git a/Version_Max_07_05_2018_CMake/src/user_method_abstraction.h b/Version_Max_07_05_2018_CMake/src/user_method_abstraction.h new file mode 100755 index 0000000..6826a78 --- /dev/null +++ b/Version_Max_07_05_2018_CMake/src/user_method_abstraction.h @@ -0,0 +1 @@ +void br_abstraction(float input, int* output); \ No newline at end of file